T-SQL STOP or ABORT command in SQL Server

后端 未结 9 503
轻奢々
轻奢々 2021-01-01 08:44

Is there a command in Microsoft SQL Server T-SQL to tell the script to stop processing? I have a script that I want to keep for archival purposes, but I don\'t want anyone t

相关标签:
9条回答
  • 2021-01-01 09:07

    To work around the RETURN/GO issue you could put RAISERROR ('Oi! Stop!', 20, 1) WITH LOG at the top.

    This will close the client connection as per RAISERROR on MSDN.

    The very big downside is you have to be sysadmin to use severity 20.

    Edit:

    A simple demonstration to counter Jersey Dude's comment...

    RAISERROR ('Oi! Stop!', 20, 1)  WITH LOG
    SELECT 'Will not run'
    GO
    SELECT 'Will not run'
    GO
    SELECT 'Will not run'
    GO
    
    0 讨论(0)
  • 2021-01-01 09:07

    Despite its very explicit and forceful description, RETURN did not work for me inside a stored procedure (to skip further execution). I had to modify the condition logic. Happens on both SQL 2008, 2008 R2:

    create proc dbo.prSess_Ins
    (
        @sSessID    varchar( 32 )
    ,   @idSess     int out
    )
    as
    begin
        set nocount on
    
        select  @id=    idSess
            from    tbSess
            where   sSessID = @sSessID
    
        if  @idSess > 0 return  -- exit sproc here
    
        begin   tran
            insert  tbSess  ( sSessID ) values  ( @sSessID )
            select  @idSess=    scope_identity( )
        commit
    end
    

    had to be changed into:

        if  @idSess is null
        begin
            begin   tran
                insert  tbSess  ( sSessID ) values  ( @sSessID )
                select  @idSess=    scope_identity( )
            commit
        end
    

    Discovered as a result of finding duplicated rows. Debugging PRINTs confirmed that @idSess had value greater than zero in the IF check - RETURN did not break execution!

    0 讨论(0)
  • 2021-01-01 09:09

    I know the question is old and was answered correctly in few different ways but there is no answer as mine which I have used in similar situations. First approach (very basic):

    IF (1=0)
    BEGIN
        PRINT 'it will not go there'
        -- your script here
    END
    PRINT 'but it will here'
    

    Second approach:

    PRINT 'stop here'
    RETURN
        -- your script here
    PRINT 'it will not go there'
    

    You can test it easily by yourself to make sure it behave as expected.

    0 讨论(0)
提交回复
热议问题