WHERE-CASE子句子查询性能 [英] WHERE-CASE clause Subquery Performance
问题描述
该问题可能特定于SQL Server. 当我编写查询时:
The question can be specific to SQL server. When I write a query such as :
SELECT * FROM IndustryData WHERE Date='20131231'
AND ReportTypeID = CASE WHEN (fnQuarterDate('20131231')='20131231') THEN 1
WHEN (fnQuarterDate('20131231')!='20131231') THEN 4
END;
是否对表的每个行执行了在Where子句中的Case中的函数调用fnQuarterDate(或任何子查询)?
如果我预先在类似这样的变量中获取函数(或任何子查询)的值会怎么样呢?
How would it be better if I get the function's (or any subquery) value beforehand inside a variable like:
DECLARE @X INT
IF fnQuarterDate('20131231')='20131231'
SET @X=1
ELSE
SET @X=0
SELECT * FROM IndustryData WHERE Date='20131231'
AND ReportTypeID = CASE WHEN (@X = 1) THEN 1
WHEN (@X = 0) THEN 4
END;
我知道在MySQL中,如果WHERE子句中的IN(..)内有一个子查询,则对每一行执行一次子查询,我只想为SQL SERVER找出相同的子查询.
I know that in MySQL if there is a subquery inside IN(..) within a WHERE clause, it is executed for each row, I just wanted to find out the same for SQL SERVER.
...
仅填充大约3万行的表,然后发现时差:
Just populated table with about 30K rows and found out the Time Difference:
Query1 = 70ms;查询2 = 6毫秒.我认为可以解释这一点,但仍然不知道其背后的实际事实.
Query1= 70ms ; Query 2= 6ms. I think that explains it but still don't know the actual facts behind it.
如果不是一个UDF,而是一个简单的子查询,还会有什么区别吗?
Also would there be any difference if instead of a UDF there was a simple subquery ?
推荐答案
我认为该解决方案在理论上可以帮助您提高性能,但是它也取决于标量函数的实际作用.我认为在这种情况下(我的猜测是将日期格式化为该季度的最后一天)确实可以忽略不计.
I think the solution may in theory help you increase the performance, but it also depends on what the scalar function actually does. I think that in this case (my guess is formatting the date to last day in the quarter) would really be negligible.
您可能需要阅读此页面,其中包含建议的解决方法:
You may want to read this page with suggested workarounds: