使用 RAISERROR 终止 SQL 语句
(SQL 2005) raiserror 是否可以终止存储过程。
例如,在大型系统中,我们得到了一个不希望输入到特定列中的值。 在更新触发器中,如果您编写:
ifexists(select*frominsertwheretestcol=7) 开始 raiseerror('我的自定义错误', 16, 1) 最终
更新信息仍然适用。 但是,如果您运行
ifexists (select * from insert where testcol = 7) 开始 选择 1/0 end
会抛出除以 0 的错误,从而实际终止更新。 有什么方法可以通过 raiseerror 来做到这一点,以便我可以返回自定义错误消息?
(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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您应该在执行更新之前检查数据是否有效。
You should check for valid data prior to performing the update.
在触发器中,发出 ROLLBACK、RAISERROR,然后 RETURN。
请参阅 Erland Sommarskog 的 SQL Server 中的错误处理 - 触发器上下文
In a trigger, issue a ROLLBACK, RAISERROR and then RETURN.
see Error Handling in SQL Server - Trigger Context by Erland Sommarskog
您不能只向该列添加一个 CHECK 约束以防止它首先被插入吗?
或者,您可以在插入存储过程(如果有的话)中启动一项事务,并在发生错误时将其回滚。 这可以通过 SQL Server 2005 中的 TRY、CATCH 来实现,并且避免使用触发器。
Can you not just add a CHECK constraint to the column to prevent it from being inserted in the first place?
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.