将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。

其他回答

在我工作的地方,sproc的最大优势是我们有更少的代码移植到VB。NET(来自VB6)。而且它的代码更少,因为我们对所有的查询都使用了spprocs。

当我们需要更新查询而不是更新VB代码,重新编译并在所有计算机上重新安装它时,它也有很大的帮助。

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。

存储过程的性能优势通常可以忽略不计。

存储过程的更多优点:

防止反向工程(当然,如果使用加密创建的话) 更好地集中数据库访问 能够透明地更改数据模型(无需部署新客户端);当多个程序访问相同的数据模型时尤其方便

在某些情况下,在代码中动态创建的sql可能比存储的proc具有更好的性能。如果您已经创建了一个存储的proc(例如sp_customersearch),它必须非常灵活,因此具有许多参数,非常复杂,那么您可能可以在运行时在代码中生成一个更简单的sql语句。

有人可能会说,这只是将一些处理从SQL转移到web服务器,但总的来说,这是一件好事。

这种技术的另一个优点是,如果你在SQL分析器中查找,你可以看到你生成的查询,调试它比看到一个存储的带有20个参数的proc调用要容易得多。

存储过程的优先级,因为: 在系统运行时修复一些生产中与数据相关的问题(这对我来说是第一个) - DB和程序之间清晰的契约定义(清晰的关注点分离) -更好的可移植性到不同的DB供应商(如果写得好,代码更改通常只在SP端)。 -更好地进行性能调优

缺点:WHERE子句在使用条件上有很大的变化,需要高性能。