我的IF / ELSE有什么问题? " ELSE:ELSE'附近的语法错误。'。"

时间:2014-12-29 21:44:46

标签: sql-server ssis

我的代码类似于:

DECLARE @IdentificationNumber INT
DECLARE @Foreign_ID BIGINT

IF ((SELECT COUNT(*) FROM [main-table] WHERE [identification-number] = @IdentificationNumber) > 0)

    SET @Foreign_ID = (SELECT [Foreign_ID] FROM [main-table] WHERE [identification-number] = @IdentificationNumber) 

    BEGIN
        UPDATE [main-table]
        SET [column1] = '', [column2] = '', [column3] = ''
        WHERE [Foreign_ID] = @Foreign_ID
    END

    BEGIN
        UPDATE [table2]
        SET [column4] = '', [column5] = '', [column6] = ''
        WHERE [Foreign_ID] = @Foreign_ID
    END

    BEGIN
        UPDATE [table3] 
        SET [column7] = '', [column8] = '', [column9] = ''
        WHERE [Foreign_ID] = @Foreign_ID
    END
    -- and so on, up to 14

ELSE -- "Incorrect syntax near 'ELSE'.

    BEGIN
        INSERT into ... -- blah blah blah. 
    END

...但在尝试使用ELSE时遇到错误:Incorrect syntax near 'ELSE'.

1 个答案:

答案 0 :(得分:13)

IF - Else语法是

If condition
begin
--statement
end
else 
begin
--statement
end

在您IF statement首先Begin - End之后的查询中,所有这些语句必须包含在Begin - End中。像

IF ((SELECT COUNT(*) FROM [main-table] WHERE [identification-number] = @IdentificationNumber) > 0)
Begin -- Missing
    SET @Foreign_ID = (SELECT [Foreign_ID] FROM [main-table] WHERE [identification-number] = @IdentificationNumber) 

    BEGIN
        UPDATE [main-table]
        SET [column1] = '', [column2] = '', [column3] = ''
        WHERE [Foreign_ID] = @Foreign_ID
    END

    BEGIN
        UPDATE [table2]
        SET [column4] = '', [column5] = '', [column6] = ''
        WHERE [Foreign_ID] = @Foreign_ID
    END

    BEGIN
        UPDATE [table3] 
        SET [column7] = '', [column8] = '', [column9] = ''
        WHERE [Foreign_ID] = @Foreign_ID
    END
END -- Missing
else
....