同一查询的不同执行时间 - SQL Server
我有一个查询:
Select a from tbl_abc where id in ( select id from tbl_xyz where mainid = 12)
当我执行这个查询时,执行需要 1-2 秒,但是当我在存储过程中使用相同的查询时,下面的查询需要超过 5 分钟:
If(Select a from tbl_abc where id in ( select id from tbl_xyz where mainid = 12))
BEGIN
-- CREATE TEMPORARY TABLE [Say: #temp1]
#temp1 => Select a from tbl_abc where id in ( select id from tbl_xyz where mainid = 12)
inserting the same value in the temp table
drop #temp1
END
可能是什么原因这?我该如何解决这个问题?我正在从 asp.net 运行 SP
I have a query:
Select a from tbl_abc where id in ( select id from tbl_xyz where mainid = 12)
When I am executing this query, it is taking 1-2 seconds to execute, but when I am using the same query in stored procedure, the below query is taking more than 5 minute:
If(Select a from tbl_abc where id in ( select id from tbl_xyz where mainid = 12))
BEGIN
-- CREATE TEMPORARY TABLE [Say: #temp1]
#temp1 => Select a from tbl_abc where id in ( select id from tbl_xyz where mainid = 12)
inserting the same value in the temp table
drop #temp1
END
what could be the reason of this? and how can I resolve this? I am running the SP from asp.net
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
EXISTS 将为您短路 IF
但是,为什么不查询 tbl_abc 和 tbl_xyz 一次呢?
An EXISTS will short circuit the IF for you
However, why not query tbl_abc and tbl_xyz once?
试试这个
我也有同样的情况并这样解决。
这可能是因为该查询执行了两次并且它包含一个子查询。不知道执行这样的查询时内部到底发生了什么。但像这样改变查询解决了我延迟的问题
try this
i also had the same situation and solved like this.
this may be because the query is executing two times and it contains a subquery. don't know what exactly happens inside while executing a query like this. but changing the query like this solved my problem of getting delayed
mainid 值实际上是硬编码的 (12),还是这只是一个示例,实际上,您将此值作为参数传递给存储过程? (如果是硬编码,您不妨忽略以下内容)。
如果“12”实际上是一个参数,那么您可能会成为参数嗅探的受害者。 这是一个带有一些有用答案的问题。
提到但未解释的一种解决方案是屏蔽参数 - 通过声明局部变量、将其设置为参数的值并在查询中使用它来实现此目的。
Is the mainid value actually hard coded (12), or is this just and example and, in reality, you are passing this value in to your stored proc as a parameter? (If it is hard coded, you may wish to ignore the following).
If "12" is infact a parameter, you could be the victim of Parameter Sniffing. Here's a question with some useful answers.
One solution mentioned but not explained is to mask the parameters - do this by declaring a local variable, setting it to the value of your parameter and use this in your query.