SQL Statement Termination using RAISERROR

邮差的信 提交于 2019-12-04 03:56:53

问题


(SQL 2005) Is it possible for a raiserror to terminate a stored proc.

For example, in a large system we've got a value that wasn't expected being entered into a specific column. In an update trigger if you write:

if exists (select * from inserted where testcol = 7) begin raiseerror('My Custom Error', 16, 1) end

the update information is still applied. however if you run

if exists (select * from inserted where testcol = 7) begin select 1/0 end

a divide by 0 error is thrown that actually terminates the update. is there any way i can do this with a raiseerror so i can get custom error messages back?


回答1:


In a trigger, issue a ROLLBACK, RAISERROR and then RETURN.

see Error Handling in SQL Server - Trigger Context by Erland Sommarskog




回答2:


Can you not just add a CHECK constraint to the column to prevent it from being inserted in the first place?

ALTER TABLE YourTable ADD CONSTRAINT CK_No_Nasties
    CHECK (testcol <> 7)

Alternatively you could start a transaction in your insert sproc (if you have one) and roll it back if an error occurs. This can be implemented with TRY, CATCH in SQL Server 2005 and avoids having to use a trigger.




回答3:


Begin try
@temp number
@temp=1/0
End try
Begin catch
@errormsg varchar(100)
@errormsg=error_massage()
Raiseerror(@errormsg,16,1)
End catch



回答4:


You should check for valid data prior to performing the update.

IF (@testvalue = 7)
    RAISERROR("Invalid value.", 16, 1);
ELSE
    UPDATE...


来源:https://stackoverflow.com/questions/1239291/sql-statement-termination-using-raiserror

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!