Creating a stored procedure if it does not already exist

后端 未结 9 1007
谎友^
谎友^ 2021-02-05 01:12

I want to check if a list of stored procedures exist. I want this all to be done in 1 script, one by one. So far I have this format:

USE [myDatabase]
GO

IF NO         


        
相关标签:
9条回答
  • 2021-02-05 01:53

    I know that there's an accepted answer, but the answer does not address exactly what the original question asks, which is to CREATE the procedure if it does not exist. The following always works and has the benefit of not requiring dropping procedures which can be problematic if one is using sql authentication.

    USE [MyDataBase]
    GO
    
    IF OBJECT_ID('mySchema.myProc') IS NULL
    EXEC('CREATE PROCEDURE mySchema.myProc AS SET NOCOUNT ON;')
    GO
    
    ALTER PROCEDURE mySchema.myProc
        @DeclaredParmsGoHere    DataType
    
    AS 
       BEGIN
           DECLARE @AnyVariablesINeed    Their DataType
       SELECT myColumn FROM myTable WHERE myIndex = @IndexParm
    
    0 讨论(0)
  • 2021-02-05 01:54

    Updated on Sep 2020

    You can use CREATE OR ALTER statement (was added in SQL Server 2016 SP1):

    The CREATE OR ALTER statement acts like a normal CREATE statement by creating the database object if the database object does not exist and works like a normal ALTER statement if the database object already exists.

    0 讨论(0)
  • 2021-02-05 01:56

    I like to use ALTER so I don't lose permissions and if you have a syntax error the old version still exists:

    BEGIN TRY
        --if procedure does not exist, create a simple version that the ALTER will replace.  if it does exist, the BEGIN CATCH will eliminate any error message or batch stoppage
        EXEC ('CREATE PROCEDURE AAAAAAAA AS DECLARE @A varchar(100); SET @A=ISNULL(OBJECT_NAME(@@PROCID), ''unknown'')+'' was not created!''; RAISERROR(@A,16,1);return 9999')
    END TRY BEGIN CATCH END CATCH
    GO
    
    ALTER PROCEDURE AAAAAAAA 
    (
         @ParamsHere varchar(10)
    )
    AS
    PRINT 'HERE IN '+(OBJECT_NAME(@@PROCID))
    GO
    
    0 讨论(0)
提交回复
热议问题