将SQL保存在c#源代码或Stored Procs中有哪些优点/缺点?我一直在和一个朋友讨论这个问题,我们正在做一个开源项目(c# ASP。网论坛)。目前,大多数数据库访问都是通过在c#中构建内联SQL并调用SQL Server DB来完成的。所以我在试着确定,对于这个特定的项目,哪个是最好的。
到目前为止,我有:
in Code的优点:
更容易维护-不需要运行SQL脚本来更新查询 更容易移植到另一个DB -没有pros到移植
存储Procs的优点:
性能 安全
将SQL保存在c#源代码或Stored Procs中有哪些优点/缺点?我一直在和一个朋友讨论这个问题,我们正在做一个开源项目(c# ASP。网论坛)。目前,大多数数据库访问都是通过在c#中构建内联SQL并调用SQL Server DB来完成的。所以我在试着确定,对于这个特定的项目,哪个是最好的。
到目前为止,我有:
in Code的优点:
更容易维护-不需要运行SQL脚本来更新查询 更容易移植到另一个DB -没有pros到移植
存储Procs的优点:
性能 安全
当前回答
I'm firmly on the side of stored procs assuming you don't cheat and use dynamic SQL in the stored proc. First, using stored procs allows the dba to set permissions at the stored proc level and not the table level. This is critical not only to combating SQL injection attacts but towards preventing insiders from directly accessing the database and changing things. This is a way to help prevent fraud. No database that contains personal information (SSNs, Credit card numbers, etc) or that in anyway creates financial transactions should ever be accessed except through strored procedures. If you use any other method you are leaving your database wide open for individuals in the company to create fake financial transactions or steal data that can be used for identity theft.
存储的proc也比从应用程序发送的SQL更容易维护和性能调优。它们还允许dba查看数据库结构更改对数据访问方式的影响。我从未遇到过允许动态访问数据库的优秀dba。
其他回答
我不是存储过程的狂热爱好者,但我在一种情况下使用它们:
当查询相当大时,最好将其作为存储过程存储在数据库中,而不是从代码中发送。这样,就不会从应用服务器向数据库发送大量字符串字符,而只发送“EXEC SPNAME”命令。
当数据库服务器和web服务器不在同一个网络上(例如,internet通信)时,这是多余的。即使事实并非如此,太大的压力也意味着大量的带宽浪费。
但是,伙计,管理起来太糟糕了。我尽量避开他们。
你列出了2个procs的优点:
性能——不完全是。在Sql 2000或更高版本中,查询计划优化非常好,并被缓存。我相信甲骨文等公司也在做类似的事情。我不认为有什么理由再用scprocs来衡量业绩了。
安全?为什么scprocs会更安全?除非您有一个非常不安全的数据库,否则所有的访问都将来自dba或通过应用程序。总是参数化所有的查询-永远不要内联用户输入的东西,你会没事的。
无论如何,这是性能的最佳实践。
Linq绝对是我现在进行一个新项目的方式。请看这篇类似的文章。
较小的日志
存储过程的另一个小优点是没有提到的:当涉及到SQL流量时,基于sp的数据访问产生的流量要少得多。当您监视流量进行分析和分析时,这一点变得非常重要——日志将会更小且可读。
Definitely easier to maintain if you put it in a stored procedure. If there's difficult logic involved that will potentially change in the future it is definitely a good idea to put it in the database when you have multiple clients connecting. For example I'm working on an application right now that has an end user web interface and an administrative desktop application, both of which share a database (obviously) and I'm trying to keep as much logic on the database as possible. This is a perfect example of the DRY principle.
很明显,使用存储过程比在代码中构造SQL有几个优点。
代码实现和SQL变得彼此独立。 代码更容易阅读。 写一次用多次。 修改一次 不需要向程序员提供关于数据库的内部细节。等等,等等。