在“CASE语句”中使用localvariables时,t-sql TVF函数变慢

时间:2012-04-30 20:27:07

标签: performance tsql case

我在多步表值函数中有类似下面的sql ..我稍微缩短了查询以使其易于理解。

CREATE FUNCTION [dbo].[fn_ph] 
(
    -- Add the parameters for the function here
    @pAsOfDate date,
    @pAccountId nvarchar(15)
)
RETURNS @HH TABLE 
(
    -- Add the column definitions for the TABLE variable here
    AsOfDate date,
    AccountId nvarchar(15), 
    LongName varchar(100),
    ShortName varchar(100)
)
AS

BEGIN

declare @longOrShortIndicator int
select @longOrShortIndicator = COUNT(distinct LongOrShortIndicator) from table1 a


select a.*,
 case 
    when a.SecType='CASH' and @longOrShortIndicator > 1 then 'C'
    else a.LongOrShortIndicator
 end as LongOrShortIndicator
from Table1 a

END

表达式when a.SecType='CASH' and @longOrShortIndicator > 1 then 'C'是瓶颈。

如果我删除@longOrShortIndicator > 1查询快速运行

如果我在函数之外运行查询,它会快速返回...

为什么局部变量会降低整个查询的速度?任何帮助将不胜感激。

感谢

2 个答案:

答案 0 :(得分:1)

列表没有显示你想用@HH做什么,你的返回表,但在@longOrShortIndicator你显然计算table1中的行。如果您多次这样做,例如对于你的返回表的所有行,它确实很慢,即使死亡之星也会很慢。

答案 1 :(得分:0)

猜测:也许您可以尝试将@LongOrShortIndicator变量移出查询并转换为IF语句:

declare @longOrShortIndicator int
select @longOrShortIndicator = COUNT(distinct LongOrShortIndicator) from table1 a

IF @longOrShortIndicator > 1 BEGIN
    select a.*,
        CASE when a.SecType='CASH' then 'C'
        else a.LongOrShortIndicator
        end as LongOrShortIndicator
    from Table1 a
END ELSE BEGIN
    select a.*, a.LongOrShortIndicator
    from Table1 a
END