使用CASE减少动态SQL以使用“IN”或不
我正在转换一个我之前编写为字符串的存储过程,然后使用 BIT 参数决定是否附加某些 WHERE/ON 子句
这个 sp 传递了许多逗号分隔的字符串,然后一些动态 WHERE 子句就像:
IF @pUse_Clause_A THEN SET @WhereClause = @WhereClause + ' AND [FIELD_A] IN (' + @pComma_Separated_List_A + ')'
在这种情况下,@pComma_Separated_List_A 类似于“1,3,6,66,22”...我想要包含的内容的列表。
现在我将这些从字符串更改为 TVP,s,这样我就可以使用“真正的”SQL,例如 AND [FIELD_A] IN (SELECT [TVP_FIELD] FROM @pTVP_A)
当我这样做时,我不喜欢字符串构建方法
但是,我也不喜欢必须嵌套 IF 语句。
IF A
ENTIRE SQL WHERE A
ELSE
ENTIRE SQL WITHOUT WHERE CLAUSE
我添加的参数越多,它就越复杂:
IF A
IF B
SQL WHERE A AND B
ELSE
SQL WHERE A
ELSE
IF B
SQL WHERE B
ELSE
SQL
我宁愿做的是这样的:
SELECT * FROM TABLE
WHERE 1=1
CASE USE_A WHEN 1 THEN
AND [FIELD_A] IN (SELECT A FROM TBP_A)
END
CASE USE_B WHEN 1 THEN
AND [FIELD_B] IN (SELECT B FROM TVP_B)
END
我知道它忽略了所选“IF”结果之外的 SQL,但所有重复的语句似乎都很草率
I am converting a stored procedure which I had previously written as a string then, using BIT parameters I decided whether to append certain WHERE/ON clauses
This sp is passed a number of comma-separated strings and then some of the dynamic WHERE clauses are like:
IF @pUse_Clause_A THEN SET @WhereClause = @WhereClause + ' AND [FIELD_A] IN (' + @pComma_Separated_List_A + ')'
In this case, @pComma_Separated_List_A is something like '1,3,6,66,22' ... a list of the things I want included.
Now I am changing these from strings into TVP,s so I can just use "real" SQL like
AND [FIELD_A] IN (SELECT [TVP_FIELD] FROM @pTVP_A)
When I do this, I don't like the string-building method
However, I also don't like having to nest the IF statements.
IF A
ENTIRE SQL WHERE A
ELSE
ENTIRE SQL WITHOUT WHERE CLAUSE
The more parameters I add, the more complicated it gets:
IF A
IF B
SQL WHERE A AND B
ELSE
SQL WHERE A
ELSE
IF B
SQL WHERE B
ELSE
SQL
What I would rather do is something like this:
SELECT * FROM TABLE
WHERE 1=1
CASE USE_A WHEN 1 THEN
AND [FIELD_A] IN (SELECT A FROM TBP_A)
END
CASE USE_B WHEN 1 THEN
AND [FIELD_B] IN (SELECT B FROM TVP_B)
END
I know it ignored SQL outside the chosen "IF" result, but having all that duplicated statement seems sloppy
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据给定参数动态改变搜索是一个复杂的主题,并且以一种不同的方式进行,即使只有非常微小的差异,也会产生巨大的性能影响。关键是使用索引,忽略紧凑的代码,忽略担心重复代码,必须制定好的查询执行计划(使用索引)。
阅读本文并考虑所有方法。您的最佳方法将取决于您的参数、数据、模式和实际使用情况:
动态搜索《T-SQL 条件》,作者:Erland Sommarskog
动态 SQL 的诅咒与祝福,作者:Erland Sommarskog< /a>
Dynamically changing searches based on the given parameters is a complicated subject and doing it one way over another, even with only a very slight difference, can have massive performance implications. The key is to use an index, ignore compact code, ignore worrying about repeating code, you must make a good query execution plan (use an index).
Read this and consider all the methods. Your best method will depend on your parameters, your data, your schema, and your actual usage:
Dynamic Search Conditions in T-SQL by by Erland Sommarskog
The Curse and Blessings of Dynamic SQL by Erland Sommarskog