问题描述
我有一个理论上的问题.
I have a theoretical question.
我看不出在PHP文件中声明 function 与在执行相同操作的数据库中创建存储过程之间有什么区别.
I can't see any difference between declaring a function within a PHP file and creating a stored procedure in a database that does the same thing.
为什么我想创建一个存储过程来返回一个特定国家/地区的所有城市的列表,而我可以使用PHP 函数 em>查询数据库,它将得到相同的结果?
Why would I want to create a stored procedure to, for example, return a list of all the Cities for a specific Country, when I can do that with a PHP function to query the database and it will have the same result?
在这种情况下,使用存储过程有什么好处?还是哪个更好?要在数据库中使用PHP或存储过程中的函数?两者之间有什么区别?
What are the benefits of using stored procedures in this case? Or which is better? To use functions in PHP or stored procedures within the database? And what are the differences between the two?
谢谢.
推荐答案
一些好处包括:
-
可维护性:您可以在过程中更改逻辑,而无需编辑app1,app2和app3调用.
Maintainability: you can change the logic in the procedure without needing to edit app1, app2 and app3 calls.
安全性/访问控制:担心谁可以调用预定义过程比控制谁可以访问哪些表或哪些表行要容易得多.
Security/Access Control: it's easier to worry about who can call a predefined procedure than it is to control who can access which tables or which table rows.
性能:如果您的应用程序与数据库不在同一服务器上,并且您正在执行的操作涉及多个查询,则使用过程通过涉及对数据库的单次调用来减少网络开销,而不是来电与查询一样多.
Performance: if your app is not situated on the same server as your DB, and what you're doing involves multiple queries, using a procedure reduces the network overhead by involving a single call to the database, rather than as many calls as there are queries.
性能(2):通常会缓存过程的查询计划,使您可以一次又一次地重复使用它,而无需重新准备它.
Performance (2): a procedure's query plan is typically cached, allowing you to reuse it again and again without needing to re-prepare it.
(在您的特定示例中,所带来的好处是零.)
(In the case of your particular example, the benefits are admittedly nil.)
这篇关于在SQL和MySQL中创建存储过程有什么好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!