SQL Server消除函数调用并用join替换

时间:2017-04-12 14:23:30

标签: sql-server tsql

我试图通过删除该功能来重写“查询”部分。
由于该表具有超过800k的记录,因此对于所有800k记录,该函数被调用三次 我想消除功能并用JOIN替换?

id status
12 complete
12  required
12  active
13  complete
13  complete
14  complete
14  required

以下是我使用JOIN进行的查询 有没有更好的方法来做到这一点?我们可以只使用一个连接而不是三个连接吗?

--Function
CREATE FUNCTION [dbo].[MapValue] 
(
    @ObjCode AS INT,
    @ObjName AS VARCHAR(50),
    @ObjValue AS INT
)
RETURNS VARCHAR(100)
AS
BEGIN
    DECLARE @returnValue AS VARCHAR(100)

    SELECT @returnValue = Value FROM dbo.tblMap
    WHERE ObjCode = @ObjCode AND ObjName = @ObjName AND ObjValue = @ObjValue

    -- Return the result of the function
    RETURN @returnValue

END

--Query
SELECT  ObjectId, ObjectTypeCode,
        dbo.MapValue(4, 'ACode', ACode) AS AType,
        dbo.MapValue(4, 'SCode', SCode) AS SCode,
        dbo.MapValue(4, 'PCode', PCode) AS PCode
FROM    dbo.APoint
WHERE   ObjectTypeCode = 1

1 个答案:

答案 0 :(得分:4)

您可以使用case和一个左连接:

SELECT  ObjectId, ObjectTypeCode,
        CASE WHEN map.ObjName = 'ActivityTypeCode' THEN map.Value END AS AType,
        CASE WHEN map.ObjName = 'statecode' THEN map.Value END As SCode,
        CASE WHEN map.ObjName = 'PriorityCode' THEN map.Value END As PCode
FROM    dbo.APoint ap
LEFT JOIN tblMap map ON map.ObjCode = 4 
                    AND map.ObjName IN('ActivityTypeCode', 'statecode', 'PriorityCode') 
                    AND map.ObjValue = ap.ActivityTypeCode
WHERE   ObjectTypeCode = 1
GROUP BY ObjectId, ObjectTypeCode