How Do I Conditionally Create a Stored Procedure

  • I want to achieve something like :

    IF

    BEGIN

    CREATE PROCEDURE sp1

    ....

    END

    ELSE

    BEGIN

    CREATE PROCEDURE sp2

    ....

    END

    Can anyone give an example, please?

  • declare @strsql nvarchar(4000)

    if (select system_user)='mike'

    begin

    print 'True'

    set @strsql='create procedure usp_test as select NULL'

    exec sp_executesql @strsql

    end

    else

    begin

    print 'False'

    set @strsql='create procedure usp_test as select NULL'

    exec sp_executesql @strsql

    end

    MVDBA

  • Thanks. Unfortunately, I forgot to mention that the SPs are big. I think executesql is limited to 8K which will not be enough.

    Thanks, anyway.

  • you could write out the stored procedures to text files and then use ISQLW.exe to run them.

    that way you can use xp_cmdshell to call ISQLW

    MVDBA

  • That looks interesting - I'll give it a try. Thanks for the help.

  • Might be possible to create the large procs independently and then conditionally execute them with dynamic sql

  • Not appropriate in this sceanrio, but thanks for the suggestion - it certainly could be an option in other cases.

Viewing 7 posts - 1 through 6 (of 6 total)

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