SQL Server Incorrect syntax near Throw - what am I missing?

aelbi1ox  于 2023-06-21  发布在  其他
关注(0)|答案(2)|浏览(124)

I am trying to execute a THROW statement like so ( value and 12345 being some random values):

use testdb;
go

begin try
if('value' in (select distinct shelf from itemloc))
update itemloc
set shelf = 'value'
where item = '12345';
end try
begin catch
;Throw 160073, 'Failed to update shelf value', 1;
end catch;

Using this reference

I looked at this question and I have the ; before my THROW . I'm also checking the syntax against the reference and fail to see why executing this returns
Msg 102, Level 15, State 1, Line 11 Incorrect syntax near 'Throw'.

ruyhziif

ruyhziif1#

You're inside a CATCH , you can't choose your error here, you would just use THROW; . Also, you don't need to start your statement with a semicolon, you already put one at the end of your last statement. It's a terminator (it goes at the end of the line), not at the beginning and end.

If you want to use a custom error, use RAISERROR . For example:

USE TESTDB;
GO

BEGIN TRY    
    IF('value' IN (SELECT DISTINCT shelf FROM itemloc))
        UPDATE itemloc
        SET shelf = 'value'
        WHERE item = '12345';
END TRY
BEGIN CATCH
    DECLARE @ERROR VARCHAR(MAX);
    SET @ERROR = 'Failed to update shelf value';
    RAISERROR(@ERROR, 11, 160073); 
END CATCH
e5njpo68

e5njpo682#

Add colons,

IF 'A'='A'
BEGIN;
  THROW 51000, 'ERROR', 1;
END;

相关问题