CASE语句在T-SQL函数中不使用“NOT LIKE”条件

时间:2012-03-16 16:27:54

标签: sql sql-server-2008 tsql case coalesce

这种语法出了什么问题?我该如何解决?

以下是错误:

Msg 156, Level 15, State 1, Procedure fnTestResultStringNEW, Line 16
Incorrect syntax near the keyword 'LIKE'.
Msg 102, Level 15, State 1, Procedure fnTestResultStringNEW, Line 40
Incorrect syntax near 'END'.

以下是T-SQL代码:

ALTER FUNCTION [dbo].[fnTestResultStringNEW]
(
    @testId INT
)
RETURNS NVARCHAR(512)
AS
BEGIN
    DECLARE @totalString NVARCHAR(512)  
    SET @totalString = ''
    SELECT @totalString = 
        COALESCE(       
            CASE substance.sortorder NOT LIKE '%.0' THEN
                CASE WHEN @totalString = '' THEN
                    testresult.result 
                ELSE
                    @totalString + ', ' + testresult.result             
                END
            ELSE
                CASE WHEN @totalString = '' THEN
                    testresult.result 
                ELSE
                    @totalString            
                END
            END     
        , '')
    FROM [dbo].[testresult_audit] AS testresult
    JOIN [dbo].[test_testresult] 
        ON  testresult.testresultid = test_testresult.testresultid 
            AND testresult.versionnumber = test_testresult.testresultversionnumber
    LEFT OUTER JOIN substance ON substance.substanceid = testresult.substanceid
    WHERE 
    test_testresult.testid = @testid
    ORDER BY substance.sortorder, testresult.result

    RETURN @totalString
END

这有效:

ALTER FUNCTION [dbo].[fnTestResultStringNEW]
(
    @testId INT
)
RETURNS NVARCHAR(512)
AS
BEGIN
    DECLARE @totalString NVARCHAR(512)  
    SET @totalString = ''
    SELECT @totalString = 
        COALESCE(       
            --CASE substance.sortorder NOT LIKE '%.0' THEN
                CASE WHEN @totalString = '' THEN
                    testresult.result 
                ELSE
                    @totalString + ', ' + testresult.result             
                END
            --ELSE
            --  CASE WHEN @totalString = '' THEN
            --      testresult.result 
            --  ELSE
            --      @totalString            
            --  END
            --END       
        , '')
    FROM [dbo].[testresult_audit] AS testresult
    JOIN [dbo].[test_testresult] 
        ON  testresult.testresultid = test_testresult.testresultid 
            AND testresult.versionnumber = test_testresult.testresultversionnumber
    LEFT OUTER JOIN substance ON substance.substanceid = testresult.substanceid
    WHERE 
    test_testresult.testid = @testid
    ORDER BY substance.sortorder, testresult.result

    RETURN @totalString
END

1 个答案:

答案 0 :(得分:8)

您错过了WHEN

CASE substance.sortorder NOT LIKE '%.0' THEN

更改为:

CASE WHEN substance.sortorder NOT LIKE '%.0' THEN