将多行Table值函数转换为SQL内联

时间:2015-01-28 11:16:23

标签: sql ssms

考虑到性能问题,我想制作multiline表值函数,inline TVF。

以下是Multiline TVF的示例代码:

CREATE FUNCTION MatchAptNumber (@AptNumberFromUser nvarchar(20))
    RETURNS @MatchedData Table
    (
     RowNumber int  null ,
     PercentMatch int null
    )
AS
Begin

Insert into @MatchedData(RowNumber) select dbo.Patients.Rowid from dbo.Patients where dbo.Patients.Aptnumber = @AptNumberFromUser
update @MatchedData set  PercentMatch= 100

    RETURN;
END;
Go

以下是我如何使用它:

select @constVal = FunctionWeight from dbo.FunctionWeights where FunctionWeights.FunctionName = 'MatchAptNumber';

INSERT INTO #Temp2(RowNumber, ValFromFunc, FuncWeight, percentage)
SELECT RowNumber, PercentMatch, @constVal, PercentMatch * @constVal
from dbo.MatchAptNumber(@Aptnumber);

是否可以将其转换为内嵌TVF并按上述方式使用它?我确实知道两者之间的语法差异,但不确定如何以同样的方式使用它?我可以得到一些指示吗?

1 个答案:

答案 0 :(得分:0)

您可以在SELECT中将'100'作为常量,因此函数变为;

CREATE FUNCTION MatchAptNumber (@AptNumberFromUser nvarchar(20))
    RETURNS TABLE AS RETURN
    SELECT 
        p.Rowid AS RowNumber , 
        CAST(100 AS INT) AS PercentMatch 
    FROM 
        dbo.Patients p
    WHERE 
        p.Aptnumber = @AptNumberFromUser
GO