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

到目前为止,我有:

in Code的优点:

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

存储Procs的优点:

性能 安全


当前回答

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

此外,正如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差)。

其他回答

较小的日志

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

我更喜欢使用O/R映射器,如LLBLGen Pro。

它为您提供了相对轻松的数据库可移植性,允许您使用强类型对象用与应用程序相同的语言编写数据库访问代码,并且在我看来,允许您更灵活地处理所拉回的数据。

实际上,能够使用强类型对象是使用O/R Mapper的充分理由。

你的编程语言和应用程序框架可能是:

高级的,特别是与SQL相比 易于通过自动化流程进行版本和部署,特别是与SQL相比

如果这两个条件是两个,则跳过存储过程。

Something that I haven't seen mentioned thus far: the people who know the database best aren't always the people that write the application code. Stored procedures give the database folks a way to interface with programmers that don't really want to learn that much about SQL. Large--and especially legacy--databases aren't the easiest things to completely understand, so programmers might just prefer a simple interface that gives them what they need: let the DBAs figure out how to join the 17 tables to make that happen.

话虽如此,用于编写存储过程的语言(PL/SQL就是一个臭名昭著的例子)是相当残酷的。它们通常不提供您在当今流行的命令式语言、OOP或函数式语言中看到的任何细节。认为COBOL。

因此,请坚持使用仅抽象了关系细节的存储过程,而不是那些包含业务逻辑的存储过程。

@Keith

安全?为什么scprocs会更安全?

存储过程提供了抵御SQL注入攻击的内在保护。

然而,您并没有完全受到保护,因为您仍然可以编写容易受到此类攻击的存储过程(即存储过程中的动态SQL)。