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

到目前为止,我有:

in Code的优点:

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

存储Procs的优点:

性能 安全


当前回答

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。

其他回答

我参加的Microsoft TechEd安全会议的建议之一是,通过存储过程进行所有调用,并拒绝直接访问表。这种方法被宣传为提供额外的安全性。我不确定仅仅为了安全性是否值得这样做,但如果您已经在使用存储过程,那么这样做也无妨。

我在其他答案中没有发现的一点是:

如果在您的环境中,数据库及其模式是体系结构的核心,应用程序的作用更小,那么更多地使用存储过程可能是有意义的,这可能有助于为所有需要访问DB的应用程序提供一个级别基础,从而减少代码重复(例如,您确定所有访问DB的应用程序都是用c#或其他。net语言编写的吗?)

另一方面,如果应用程序具有更核心的角色,而DB更多地充当应用程序的备份存储,那么减少存储过程的使用并通过提供一个公共持久性层(可能基于ORM工具/框架)来减少代码重复可能是明智的。

在这两种情况下,重要的是不要将DB视为存储过程的方便存储库。将它们保存在版本控制系统的源文件中,并尽可能地尝试自动化它们的部署(这实际上对所有与模式相关的构件都有效)。

在安全性方面,存储过程要安全得多。一些人认为,无论如何,所有的访问都将通过应用程序进行。许多人忘记了一件事,即大多数安全漏洞来自公司内部。想想有多少开发人员知道应用程序的“隐藏”用户名和密码?

此外,正如MatthieuF所指出的,由于应用程序(无论是在桌面服务器还是web服务器上)和数据库服务器之间的往返次数减少,性能可以得到很大的提高。

In my experience the abstraction of the data model through stored procedures also vastly improves maintainability. As someone who has had to maintain many databases in the past, it's such a relief when confronted with a required model change to be able to simply change a stored procedure or two and have the change be completely transparent to ALL outside applications. Many times your application isn't the only one pointed at a database - there are other applications, reporting solutions, etc. so tracking down all of those affected points can be a hassle with open access to the tables.

我还将在加分栏中加上检查,以使SQL编程掌握在专门的人员手中,并使sp更容易隔离和测试/优化代码。

我看到的一个缺点是,许多语言不允许传递表参数,因此传递未知的数据值可能很烦人,一些语言仍然无法处理从单个存储过程中检索多个结果集(尽管后者在这方面并不使sp比内联SQL差)。

存储过程。

如果出现错误或者逻辑稍有变化,您不必重新编译项目。此外,它允许从不同的来源访问,而不仅仅是在项目中编写查询的一个地方。

我不认为维护存储过程更难,你不应该直接在数据库中编写它们,而应该先在单独的文件中编写,然后你可以在任何你需要设置的DB上运行它们。

较小的日志

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