使用 RAISERROR 终止 SQL 语句

发布于 2024-07-30 12:29:04 字数 389 浏览 1 评论 0原文

(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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

别再吹冷风 2024-08-06 12:29:05

您应该在执行更新之前检查数据是否有效。

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

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

IF (@testvalue = 7)
    RAISERROR("Invalid value.", 16, 1);
ELSE
    UPDATE...
指尖微凉心微凉 2024-08-06 12:29:04

在触发器中,发出 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

娇女薄笑 2024-08-06 12:29:04

您不能只向该列添加一个 CHECK 约束以防止它首先被插入吗?

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

或者,您可以在插入存储过程(如果有的话)中启动一项事务,并在发生错误时将其回滚。 这可以通过 SQL Server 2005 中的 TRYCATCH 来实现,并且避免使用触发器。

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.

七颜 2024-08-06 12:29:04
Begin try
@temp number
@temp=1/0
End try
Begin catch
@errormsg varchar(100)
@errormsg=error_massage()
Raiseerror(@errormsg,16,1)
End catch
Begin try
@temp number
@temp=1/0
End try
Begin catch
@errormsg varchar(100)
@errormsg=error_massage()
Raiseerror(@errormsg,16,1)
End catch
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文