user2405574
user2405574

Reputation: 263

I am unable to use THROW SQL Server 2008 R2

SQL Server 2008 R2 Management Studio does not recognized my throw in the below example, it says

incorrect syntax near Throw

I am trying to throw an error here, so I can handled it in my website when someone insert the same value twice.

Begin Try
 insert into BusinessID (BusinessID) values (@ID)
 insert into BusinessID (BusinessID) values (@ID)

End Try

Begin Catch

Print 'PK already exist'
THROW
End Catch

Upvotes: 26

Views: 28003

Answers (2)

Pawan
Pawan

Reputation: 1075

Use RAISERROR instead of Throw in your sql block.

Begin Try
 insert into BusinessID (BusinessID) values (@ID)
 insert into BusinessID (BusinessID) values (@ID)

End Try

Begin Catch

Print 'PK already exist'
  DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;

SELECT 
    @ErrorMessage = ERROR_MESSAGE(),
    @ErrorSeverity = ERROR_SEVERITY(),
    @ErrorState = ERROR_STATE();

-- Use RAISERROR inside the CATCH block to return error
-- information about the original error that caused
-- execution to jump to the CATCH block.
RAISERROR (@ErrorMessage, -- Message text.
           @ErrorSeverity, -- Severity.
           @ErrorState -- State.
           );
End Catch

Upvotes: 4

Nenad Zivkovic
Nenad Zivkovic

Reputation: 18559

THROW Statement is introduced in SQL Server 2012

http://msdn.microsoft.com/en-us/library/ee677615.aspx

You can use RAISERROR instead.

http://msdn.microsoft.com/en-us/library/483588bd-021b-4eae-b4ee-216268003e79(v=sql.105)

BEGIN CATCH
    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;

    SELECT 
        @ErrorMessage = ERROR_MESSAGE(),
        @ErrorSeverity = ERROR_SEVERITY(),
        @ErrorState = ERROR_STATE();

    RAISERROR (@ErrorMessage, -- Message text.
               @ErrorSeverity, -- Severity.
               @ErrorState -- State.
               );
END CATCH;

Upvotes: 48

Related Questions