是否有一种方法可以立即停止SQL服务器中SQL脚本的执行,如“break”或“exit”命令?

我有一个脚本,它在开始插入之前执行一些验证和查找,我希望它在任何验证或查找失败时停止。


当前回答

您可以将SQL语句包装在WHILE循环中,并在需要时使用BREAK

WHILE 1 = 1
BEGIN
   -- Do work here
   -- If you need to stop execution then use a BREAK


    BREAK; --Make sure to have this break at the end to prevent infinite loop
END

其他回答

我不会使用RAISERROR- SQL有IF语句可以用于此目的。执行您的验证和查找并设置局部变量,然后使用IF语句中的变量值使插入具有条件。

您不需要检查每个验证测试的变量结果。你通常可以用一个标志变量来确认所有传递的条件:

declare @valid bit

set @valid = 1

if -- Condition(s)
begin
  print 'Condition(s) failed.'
  set @valid = 0
end

-- Additional validation with similar structure

-- Final check that validation passed
if @valid = 1
begin
  print 'Validation succeeded.'

  -- Do work
end

即使您的验证更复杂,您也应该只需要在最终检查中包含几个标志变量。

将适当的代码块包装在try catch块中。然后,如果您愿意,可以使用严重程度为11的Raiserror事件,以便中断到catch块。如果你只想抛出错误,但在try块内继续执行,那么使用较低的严重程度。

试一试……抓住(transact - sql)

将它包含在try catch块中,然后执行将被转移到catch。

BEGIN TRY
    PRINT 'This will be printed'
    RAISERROR ('Custom Exception', 16, 1);
    PRINT 'This will not be printed'
END TRY
BEGIN CATCH
    PRINT 'This will be printed 2nd'
END CATCH;

我用一个事务成功地扩展了noexec开/关解决方案,以全有或全无的方式运行脚本。

set noexec off

begin transaction
go

<First batch, do something here>
go
if @@error != 0 set noexec on;

<Second batch, do something here>
go
if @@error != 0 set noexec on;

<... etc>

declare @finished bit;
set @finished = 1;

SET noexec off;

IF @finished = 1
BEGIN
    PRINT 'Committing changes'
    COMMIT TRANSACTION
END
ELSE
BEGIN
    PRINT 'Errors occured. Rolling back changes'
    ROLLBACK TRANSACTION
END

显然,编译器“理解”IF中的@finished变量,即使有一个错误并且执行被禁用。但是,只有在未禁用执行时,该值才会设置为1。因此,我可以很好地提交或回滚事务。

您可以将SQL语句包装在WHILE循环中,并在需要时使用BREAK

WHILE 1 = 1
BEGIN
   -- Do work here
   -- If you need to stop execution then use a BREAK


    BREAK; --Make sure to have this break at the end to prevent infinite loop
END