Creating a stored procedure if it does not already exist

后端 未结 9 1021
谎友^
谎友^ 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:29

    One idiom that I've been using lately that I like quite a lot is:

    if exists (select 1 from sys.objects where object_id = object_id('dbo.yourProc'))
       set noexec on
    go
    create procedure dbo.yourProc as
    begin
       select 1 as [not yet implemented]
    end
    go
    set noexec off
    alter procedure dbo.yourProc as
    begin
       /*body of procedure here*/
    end
    

    Essentially, you're creating a stub if the procedure doesn't exist and then altering either the stub (if it was just created) or the pre-existing procedure. The nice thing about this is that you don't drop a pre-existing procedure which drops all the permissions as well. You can also cause issues with any application that happens to want it in that brief instant where it doesn't exist.

    [Edit 2018-02-09] - In SQL 2016 SP1, create procedure and drop procedure got some syntactic sugar that helps with this kind of thing. Specifically, you can now do this:

    create or alter dbo.yourProc as
    go
    
    drop procedure if exists dbo.yourProc;
    

    Both provide idempotency in the intended statement (i.e. you can run it multiple times and the desired state). This is how I'd do it now (assuming you're on a version of SQL Server that supports it).

提交回复
热议问题