简体   繁体   English

将内联SQL转换为存储过程

[英]Converting inline SQL to stored procedure

I'm working on an existing ASP.NET application. 我正在研究现有的ASP.NET应用程序。 The current application uses a lot of inline queries. 当前的应用程序使用了大量的内联查询。 Now they want to rewrite all the queries into stored procedures only. 现在,他们只想将所有查询重写到存储过程中。

My problem is, these queries are very "dynamic" and the queries are concatenated based on different if...else conditions, for example: 我的问题是,这些查询非常“动态”,并且根据不同的if...else条件连接查询,例如:

string query = "Select * from EmpTable WHERE EmpType ='ACTIVE'";

if (conditionA == true)
query += "AND ID = 12345 ";

if (conditionB == true)
query += "AND Dept = 'Finance' ";

else
query += "AND Dept <> 'Finance' ";

if (conditionC == true)
query += "Order by EmpID";

else if (ConditionD == true)
query += "Order by Dept";

They also want to avoid using dynamic query. 他们还希望避免使用动态查询。 What are my options? 我有什么选择?

Edited: I know I can also build dynamic query using stored procedures, I am just wondering what are some other "less pain" options out there. 编辑:我知道我也可以使用存储过程构建动态查询,我只是想知道那里有什么其他“减少痛苦”选项。

Pass in all the parameters you might need, and use the IsNull and/or When clauses to create the same query as in the original program. 传入您可能需要的所有参数,并使用IsNull和/或When子句创建与原始程序中相同的查询。

Alternatively you can simply build the query dynamically in the sproc itself or simply create a query for each permutation. 或者,您可以简单地在sproc本身中动态构建查询,或者只是为每个排列创建一个查询。 Not necessarily fun, or clever but works and makes things easier to maintain in the future - especially when you can use it as a stepping stone for future refactoring of the sprocs. 不一定有趣,或者很聪明,但有效并且将来更容易维护 - 特别是当你可以将它用作未来重构sprocs的垫脚石时。

Edit: there is one more reason to simply convert them all to sprocs - when future devs come along and want to add some SQL, they'll follow the convention and create a new sproc themselves. 编辑:还有一个原因可以简单地将它们全部转换为sprocs - 当未来的开发人员出现并希望添加一些SQL时,他们将遵循约定并自己创建一个新的sproc。 I imagine one reason your code is littered with dynamic SQL is because it is already littered with dynamic SQL. 我想象一下你的代码充斥着动态SQL的一个原因是因为它已经充斥着动态SQL。 Maybe over time you can improve them (slap legacy, must fix at the top of each convert) and you'll get them to fix up the design themselves too. 也许随着时间的推移,你可以改进它们(打击传统,必须修复每个转换的顶部),你也可以让它们自己修复设计。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM