将SQL保存在c#源代码或Stored Procs中有哪些优点/缺点?我一直在和一个朋友讨论这个问题,我们正在做一个开源项目(c# ASP。网论坛)。目前,大多数数据库访问都是通过在c#中构建内联SQL并调用SQL Server DB来完成的。所以我在试着确定,对于这个特定的项目,哪个是最好的。

到目前为止,我有:

in Code的优点:

更容易维护-不需要运行SQL脚本来更新查询 更容易移植到另一个DB -没有pros到移植

存储Procs的优点:

性能 安全


当前回答

我更喜欢使用O/R映射器,如LLBLGen Pro。

它为您提供了相对轻松的数据库可移植性,允许您使用强类型对象用与应用程序相同的语言编写数据库访问代码,并且在我看来,允许您更灵活地处理所拉回的数据。

实际上,能够使用强类型对象是使用O/R Mapper的充分理由。

其他回答

CON

我发现在存储过程中进行大量的处理会使您的DB服务器在扩展您的行为时成为一个单一的不灵活点。

然而,如果您有多个服务器运行您的代码,那么在您的程序中进行所有这些处理而不是sql-server,可能会允许您进行更多的扩展。当然,这并不适用于只进行正常获取或更新的存储procs,而是适用于执行更多处理(如在数据集上循环)的存储procs。

PROS

Performance for what it may be worth (avoids query parsing by DB driver / plan recreation etc) Data manipulation is not embedded in the C/C++/C# code which means I have less low level code to look through. SQL is less verbose and easier to look through when listed separately. Due to the separation folks are able to find and reuse SQL code much easier. Its easier to change things when schema changes - you just have to give the same output to the code and it will work just fine Easier to port to a different database. I can list individual permissions on my stored procedures and control access at that level too. I can profile my data query/ persistence code separate from my data transformation code. I can implement changeable conditions in my stored procedure and it would be easy to customize at a customer site. It becomes easier to use some automated tools to convert my schema and statements together rather than when it is embedded inside my code where I would have to hunt them down. Ensuring best practices for data access is easier when you have all your data access code inside a single file - I can check for queries that access the non performant table or that which uses a higher level of serialization or select *'s in the code etc. It becomes easier to find schema changes / data manipulation logic changes when all of it is listed in one file. It becomes easier to do search and replace edits on SQL when they are in the same place e.g. change / add transaction isolation statements for all stored procs. I and the DBA guy find that having a separate SQL file is easier / convenient when the DBA has to review my SQL stuff. Lastly you don't have to worry about SQL injection attacks because some lazy member of your team did not use parametrized queries when using embedded sqls.

当存储过程被用于应用程序和数据库之间时,它们是最糟糕的。上面提到的使用它们的许多原因都可以由视图更好地处理。

有关安全的论点是站不住脚的。它只是将安全问题从应用程序转移到数据库。代码就是代码。我曾见过一些存储过程从应用程序中获取SQL,并使用它构建容易受到SQL注入攻击的查询。

一般来说,它们往往会在所谓的数据库开发人员和所谓的应用程序开发人员之间造成裂痕。实际上,所有编写的代码都是应用程序代码,只是执行上下文的不同。

使用丰富的SQL生成库,如LINQ, Rails ActiveRecord或Hibernate/NHibernate,使开发更快。在混合中插入存储过程会降低速度。

我想再投一票赞成使用存储过程(尽管在维护和版本控制时它们会带来麻烦)作为一种限制对底层表的直接访问以获得更好的安全性的方法。

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

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

较小的日志

存储过程的另一个小优点是没有提到的:当涉及到SQL流量时,基于sp的数据访问产生的流量要少得多。当您监视流量进行分析和分析时,这一点变得非常重要——日志将会更小且可读。