将SQL保存在c#源代码或Stored Procs中有哪些优点/缺点?我一直在和一个朋友讨论这个问题,我们正在做一个开源项目(c# ASP。网论坛)。目前,大多数数据库访问都是通过在c#中构建内联SQL并调用SQL Server DB来完成的。所以我在试着确定,对于这个特定的项目,哪个是最好的。
到目前为止,我有:
in Code的优点:
更容易维护-不需要运行SQL脚本来更新查询 更容易移植到另一个DB -没有pros到移植
存储Procs的优点:
性能 安全
将SQL保存在c#源代码或Stored Procs中有哪些优点/缺点?我一直在和一个朋友讨论这个问题,我们正在做一个开源项目(c# ASP。网论坛)。目前,大多数数据库访问都是通过在c#中构建内联SQL并调用SQL Server DB来完成的。所以我在试着确定,对于这个特定的项目,哪个是最好的。
到目前为止,我有:
in Code的优点:
更容易维护-不需要运行SQL脚本来更新查询 更容易移植到另一个DB -没有pros到移植
存储Procs的优点:
性能 安全
当前回答
目前在这里的其他几个线程中正在讨论这个问题。我一直是存储过程的支持者,尽管有一些很好的论据支持Linq to Sql。
在代码中嵌入查询将您与数据模型紧密地结合在一起。存储过程是一种很好的契约式编程形式,这意味着DBA可以自由地更改过程中的数据模型和代码,只要存储过程的输入和输出所表示的契约得到维护。
当查询隐藏在代码中,而不是在一个易于管理的中心位置时,调优生产数据库可能会非常困难。
这里是另一个当前的讨论
其他回答
我更喜欢把它们保存在代码中(使用ORM,而不是内联或特别),这样它们就可以被源代码控制覆盖,而不必保存.sql文件。
此外,存储过程本身并不更安全。使用sproc可以像使用内联一样轻松地编写糟糕的查询。参数化内联查询与sproc一样安全。
较小的日志
存储过程的另一个小优点是没有提到的:当涉及到SQL流量时,基于sp的数据访问产生的流量要少得多。当您监视流量进行分析和分析时,这一点变得非常重要——日志将会更小且可读。
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。
在我工作的地方,sproc的最大优势是我们有更少的代码移植到VB。NET(来自VB6)。而且它的代码更少,因为我们对所有的查询都使用了spprocs。
当我们需要更新查询而不是更新VB代码,重新编译并在所有计算机上重新安装它时,它也有很大的帮助。
我通常写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.)