将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的优点:
性能 安全
当前回答
存储过程的优点:
更容易检查代码。
耦合更少,因此更容易测试。
更容易调谐。
从网络流量的角度来看,性能通常更好——如果您有一个游标或类似的东西,那么就不会多次访问数据库
您可以更容易地保护对数据的访问,删除对表的直接访问,通过procs加强安全性——这也允许您相对快速地找到更新表的任何代码。
如果涉及到其他服务(如Reporting服务),您可能会发现将所有逻辑存储在存储过程中,而不是存储在代码中,并且必须复制它会更容易
缺点:
对开发人员来说更难管理的是:脚本的版本控制:每个人都有自己的数据库吗?版本控制系统是否与数据库和IDE集成在一起?
其他回答
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。
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注入攻击的查询。
一般来说,它们往往会在所谓的数据库开发人员和所谓的应用程序开发人员之间造成裂痕。实际上,所有编写的代码都是应用程序代码,只是执行上下文的不同。
使用丰富的SQL生成库,如LINQ, Rails ActiveRecord或Hibernate/NHibernate,使开发更快。在混合中插入存储过程会降低速度。
@Keith
安全?为什么scprocs会更安全?
存储过程提供了抵御SQL注入攻击的内在保护。
然而,您并没有完全受到保护,因为您仍然可以编写容易受到此类攻击的存储过程(即存储过程中的动态SQL)。
这样想
你有4个web服务器和一堆使用相同SQL代码的windows应用程序 现在您意识到SQl代码有一个小问题 所以你宁愿...... 在一个地方改变过程 或 将代码推送到所有的网络服务器上,重新安装所有Windows盒子上的所有桌面应用程序(单击一次可能会有帮助)
我更喜欢存储过程
它也更容易做一个过程的性能测试,把它放在查询分析器 设置io/time on统计信息 设置showplan_text,瞧
不需要运行分析器来查看到底调用了什么
这只是我的小意思