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

到目前为止,我有:

in Code的优点:

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

存储Procs的优点:

性能 安全


当前回答

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

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

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

其他回答

很明显,使用存储过程比在代码中构造SQL有几个优点。

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

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

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

我站在代码这一边。我们构建了所有应用程序(包括web和客户端)使用的数据访问层,所以从这个角度来看这是DRY。它简化了数据库部署,因为我们只需要确保表模式是正确的。它简化了代码维护,因为我们不需要查看源代码和数据库。

在与数据模型的紧密耦合方面,我没有遇到太多问题,因为我看不出哪里有可能真正打破这种耦合。应用程序及其数据在本质上是耦合的。

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。

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.