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

到目前为止,我有:

in Code的优点:

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

存储Procs的优点:

性能 安全


当前回答

我通常写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有几个优点。

代码实现和SQL变得彼此独立。 代码更容易阅读。 写一次用多次。 修改一次 不需要向程序员提供关于数据库的内部细节。等等,等等。

这样想

你有4个web服务器和一堆使用相同SQL代码的windows应用程序 现在您意识到SQl代码有一个小问题 所以你宁愿...... 在一个地方改变过程 或 将代码推送到所有的网络服务器上,重新安装所有Windows盒子上的所有桌面应用程序(单击一次可能会有帮助)

我更喜欢存储过程

它也更容易做一个过程的性能测试,把它放在查询分析器 设置io/time on统计信息 设置showplan_text,瞧

不需要运行分析器来查看到底调用了什么

这只是我的小意思

程序员希望代码在他们的应用程序中,DBA希望它在数据库中。

如果你两者都有,你可以通过使用存储过程在两者之间分配工作,程序员不必担心所有这些表如何连接在一起等(对不起,我知道你想控制一切。)

我们有一个第三方应用程序,它允许在数据库中的视图或存储过程上创建自定义报告。如果我把代码中的所有逻辑都放在另一个应用程序中,就不能重用它。如果你使用数据库编写所有的应用程序,这不是问题。

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。

存储过程的优点 1).提高安全性,因为存储过程中的SQL本质上是静态的(大多数)。这将防止SQL注入。 2)。可重用性。如果需要为多个应用程序/组件返回相同的数据,这可能是一个更好的选择,而不是重复SQL语句。 3).减少客户端与数据库服务器之间的调用。

我不确定其他数据库,但您可以在大型机上的db2中使用主机语言创建存储过程,这使得它们非常强大。