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

到目前为止,我有:

in Code的优点:

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

存储Procs的优点:

性能 安全


当前回答

我对存储过程的投票;作为接近数据的抽象层,集合高效,可被许多“客户端”(客户端语言)重用。T-SQL语言有点原始(我猜这是SO的大多数c#人都接触过的),但Oracle的PL/SQL与任何现代编程语言不相上下。

至于版本控制,只需将存储过程代码放在版本控制下的文本文件中,然后运行脚本在数据库中创建procs。

其他回答

我非常支持代码而不是SPROC。第一个原因是保持代码紧密耦合,第二个原因是源代码控制的便利性,而不需要大量自定义实用程序。

在我们的DAL中,如果我们有非常复杂的SQL语句,我们通常将它们作为资源文件,并在需要时更新它们(这也可以是一个单独的程序集,并在每个db中交换,等等……)

这使得我们的代码和sql调用存储在同一个版本控制中,而不会“忘记”运行一些外部应用程序进行更新。

较小的日志

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

你列出了2个procs的优点:

性能——不完全是。在Sql 2000或更高版本中,查询计划优化非常好,并被缓存。我相信甲骨文等公司也在做类似的事情。我不认为有什么理由再用scprocs来衡量业绩了。

安全?为什么scprocs会更安全?除非您有一个非常不安全的数据库,否则所有的访问都将来自dba或通过应用程序。总是参数化所有的查询-永远不要内联用户输入的东西,你会没事的。

无论如何,这是性能的最佳实践。

Linq绝对是我现在进行一个新项目的方式。请看这篇类似的文章。

我通常写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.)

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.