将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的优点:
性能 安全
当前回答
我不是存储过程的狂热爱好者,但我在一种情况下使用它们:
当查询相当大时,最好将其作为存储过程存储在数据库中,而不是从代码中发送。这样,就不会从应用服务器向数据库发送大量字符串字符,而只发送“EXEC SPNAME”命令。
当数据库服务器和web服务器不在同一个网络上(例如,internet通信)时,这是多余的。即使事实并非如此,太大的压力也意味着大量的带宽浪费。
但是,伙计,管理起来太糟糕了。我尽量避开他们。
其他回答
@Keith
安全?为什么scprocs会更安全?
存储过程提供了抵御SQL注入攻击的内在保护。
然而,您并没有完全受到保护,因为您仍然可以编写容易受到此类攻击的存储过程(即存储过程中的动态SQL)。
在某些情况下,在代码中动态创建的sql可能比存储的proc具有更好的性能。如果您已经创建了一个存储的proc(例如sp_customersearch),它必须非常灵活,因此具有许多参数,非常复杂,那么您可能可以在运行时在代码中生成一个更简单的sql语句。
有人可能会说,这只是将一些处理从SQL转移到web服务器,但总的来说,这是一件好事。
这种技术的另一个优点是,如果你在SQL分析器中查找,你可以看到你生成的查询,调试它比看到一个存储的带有20个参数的proc调用要容易得多。
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。
我通常写OO代码。我猜你们大多数人可能也有同感。在这种上下文中,所有业务逻辑(包括SQL查询)都属于类定义,这在我看来是显而易见的。分割逻辑(部分驻留在对象模型中,部分驻留在数据库中)并不比将业务逻辑放到用户界面中更好。
关于存储过程的安全性优势,在前面的回答中已经说了很多。它们分为两大类:
1)限制直接访问数据。这在某些情况下确实很重要,当你遇到这样的情况时,存储过程几乎是你唯一的选择。然而,根据我的经验,这样的情况是例外而不是规则。
2) SQL injection/parametrized queries. This objection is a red herring. Inline SQL - even dynamically-generated inline SQL - can be just as fully parametrized as any stored proc and it can be done just as easily in any modern language worth its salt. There is no advantage either way here. ("Lazy developers might not bother with using parameters" is not a valid objection. If you have developers on your team who prefer to just concatenate user data into their SQL instead of using parameters, you first try to educate them, then you fire them if that doesn't work, just like you would with developers who have any other bad, demonstrably detrimental habit.)
我还没有找到一种在源代码控制中轻松维护存储过程的好方法,使其与代码库一样无缝。这是不会发生的。仅这一点就使得在代码中添加SQL对我来说是值得的。在现代系统中,性能差异可以忽略不计。