通过 IF 语句检索的 SELECT SQL 表
大家好,
我想做的就是这样,我将根据我的参数创建一个 SQL 表,
DECLARE @find varchar(30)
SET @find = 'no'
SELECT * FROM
(
if @find = 'yes'
(
SELECT * FROM myTable
WHERE ID= '5882'
)
ELSE
(
SELECT * FROM myTable
WHERE OLD_ID= '5882'
)
) X
这只是我作为示例给出的一个简单表,我真正的 SQL 查询要大得多,所以我不这样做我认为我可以在此查询中使用动态 sql。所以我需要其他方法。
Hella all,
What I want to do is something like that, I will have an SQL table depending on my parameter,
DECLARE @find varchar(30)
SET @find = 'no'
SELECT * FROM
(
if @find = 'yes'
(
SELECT * FROM myTable
WHERE ID= '5882'
)
ELSE
(
SELECT * FROM myTable
WHERE OLD_ID= '5882'
)
) X
This is just a simple table that I gave as an example, my real sql query is much more bigger and so I don't think I can use dynamic sql within this query. So I need some other way.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用“搜索
CASE
函数”,如下所示:Use the 'searched
CASE
function' like this:您可以使用 EXEC 来执行 SQL 字符串。你必须介意引号。
You can use EXEC to execute a SQL string. You have to mind quotes.
为了确保最佳的执行计划,我建议创建单独的查询,并根据“@find”调用适当的查询。
例如
SPROC1 将查询 ID
SPROC2 将查询 OLD_ID
然后,更改您的调用代码以调用适当的存储过程,或者,如果您只想将 @find 作为参数传递,请创建一个仅充当重定向的第三个存储过程:
SPROC3:
其他方法的风险是执行计划污染,即为一条路径创建计划(例如 @find='no'),然后当后续调用 @find='yes' 时,它最终会使用少得多的路径执行计划不当,导致绩效不佳。换句话说,它最终可能会使用 OLD_ID 上的索引,而不是使用 ID 上的索引,这显然不理想(反之亦然)。
To ensure optimal execution plans, I'd recommend creating separate queries, and calling the appropriate one depending on "@find".
e.g.
SPROC1 would query on ID
SPROC2 would query on OLD_ID
Then either, change your calling code to call the appropriate sproc, OR, if you just want to pass @find in as a parameter, create a 3rd sproc that just acts as a redirect:
SPROC3:
The risk with other approaches is execution plan pollution whereby a plan gets created for one path (e.g. @find='no') and then when a subsequent call comes in with @find='yes' it ends up using the far less appropriate execution plan, resulting in poor performance. In other words, instead of using an index on ID it may end up using the index on OLD_ID which is obviously not ideal (and vice versa).