Running SQL script..

  • I'd like to exit an SQL script gracefully.    I have a script that has many statements and many GOs.   I would like to perform a conditional IF statment at the beginning of the script that will exit out if true.  For some reason,  the entire script is being run regardless.

    Help.  thanks  tpssoft.

    for example.

    if 1 = 1

     begin

      print 'OK to run this'

      retur

    end

    go

    print 'THIS SHOULDN"T RUN!!!!'

  • The go keyword tells sqlserver to end this batch and start a new one. Even if the return keyword is executed (don't know where it would return to... but at least exit), the batch will end at go and a new t-sql batch will start (you cant use the profiler to see what's going on).

  • But a simple modification should get you the results you want (I think :rolleyes

    if 1 = 1

      begin

        print 'OK to run this'

        return

      end

    else

     begin

      print 'THIS SHOULDN"T RUN!!!!'

     end

  • <>

    not sure it would work in this case.

  • The scope of an IF statement is limited to a single batch. You cannot have a single IF span multiple batches. GO is the batch separator used by Query Analyzer.

    Executing RETURN will terminate the current batch, so if you can do everything in a single batch, the RETURN will work as you desire.

    Try this:

    ---------------------------------------

    PRINT 'Batch 1'

    DECLARE @flag tinyint

    SET @flag = 1

    IF @flag = 1

    BEGIN

      PRINT 'Flag is one, exit now.'

      RETURN

    END

    PRINT 'Continue processing batch 1' 

    GO

    PRINT 'Batch 2'

    RETURN

    GO

    PRINT 'Batch 3'

    RETURN

Viewing 5 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic. Login to reply