Search code examples
sql-servert-sqlraiserror

SQL Server migration 2008 to 2016 - raiserror syntax error


We are going to migrate from SQL Server 2008 to 2016. I am in the process of identifying errors and I get the following error in a trigger:

Incorrect syntax near '51001'.

I looked through the Raiserror documentation on the Microsoft website and it did not help. The following is the SQL. Any help would be appreciated.

IF (SELECT count(*) FROM dbo.u_sample_concrete ref, deleted
WHERE  ref.lab_cd =  deleted.lab_id) > 0
BEGIN
    RAISERROR 51001 ''Trigger td_tblLAB on table dbo.tblLAB:  Primary key values found in table dbo.u_sample_concrete (lab_cd).  Delete restricted; the transaction is being rolled back.''
    ROLLBACK TRANSACTION
    RETURN
END

Solution

  • The Microsoft Documentation does indeed show 4 things wrong with your statement.

    1. The parameters must be inside brackets raiserror().
    2. 4 parameters are expected when msd_id (51001) is used - you are providing 2.
    3. Parameters should be separated by commas ,.
    4. You are double quoting the string, when it should be single quoted.
    RAISERROR (51001, -1,- 1, 'Trigger td_tblLAB on table dbo.tblLAB:  Primary key values found in table dbo.u_sample_concrete (lab_cd).  Delete restricted; the transaction is being rolled back.')
    

    Note: its best practice now to use throw rather than raiserror.