Incorrect syntax near 'THROW'

2019-01-25 04:37发布

IF @SQL IS NOT NULL
BEGIN
    BEGIN TRY 
        EXEC sp_executesql @SQL
        PRINT 'SUCCESS: ' + @SQL
    END TRY 
    BEGIN CATCH
        SET @ErrorMessage = 
                    N'Error dropping constraint' + @CRLF
                    + 'Table ' + @TableName + @CRLF
                    + 'Script: ' + @SQL + @CRLF
                    + 'Error message: ' + ERROR_MESSAGE() + @CRLF
        THROW  50100, @ErrorMessage, 1;
    END CATCH
END

When the CATCH executes, I get the following error:

Msg 102, Level 15, State 1, Line 257
Incorrect syntax near 'THROW'.

Replacing THROW with PRINT @ErrorMessage works.

Replacing @ErrorMessage variable with a literal string works.

According to the docs, however, THROW is supposed to be able to take a variable. Not sure what to make of this.

3条回答
爷的心禁止访问
2楼-- · 2019-01-25 05:15

From MSDN:

The statement before the THROW statement must be followed by the semicolon (;) statement terminator.

查看更多
3楼-- · 2019-01-25 05:20

From the Documentation on THROW, Remarks:

The statement before the THROW statement must be followed by the semicolon (;) statement terminator.

It's a good habit to always end your statements with a semi-colon.

查看更多
Explosion°爆炸
4楼-- · 2019-01-25 05:25

I just hit the same error but for a completely different reason. The machine I'm using is slightly old but has SSMS 2012 (the version that Throw was introduced). However the actual SQL server is 10.5 (which is 2008 R2; see https://docs.microsoft.com/en-us/sql/t-sql/statements/alter-database-transact-sql-compatibility-level) and so the command is not valid.

Hopefully there won't be too many instances of ten year old setups out there but double check if you get this and you're sure your syntax is correct!

查看更多
登录 后发表回答