sql-servertry-catchraiserror

How to fire up SQL Exception from CATCH it T-SQL?


Assuming I have the following table

Create Table [T] ([id] int IDENTITY(1,1) Primary key, [value] varchar(200))

Now I want to set the IDENTITY_INSERT to ON, but if it fails to set it back to OFF

So I have the following:

BEGIN try
  set IDENTITY_INSERT [T] ON
  insert into [T]([id],[value]) values(1,'test')
  set IDENTITY_INSERT [T] OFF
END try
BEGIN catch
  set IDENTITY_INSERT [T] OFF
  --RAISERROR ?
END catch

Now I want to fire the error up im manner the caller will receive the exact error(include number, arguments, severity etc.. As if I called to insert into [T]([id],[value]) values(1,'test') On non-IDENTITY table.

I mean to sumething like throwing the exception from a catch

try{
  ...
}
catch(Exception e)
{
  throw e;
}

How can I do it?


Solution

  • Do you want to re-throw the error that took you into the CATCH? Than just use THROW without any parameters. You can't use RAISERROR for that since you cannot set both error number and text, nor can you refer to a system-error. So, just THROW will do that.