简体   繁体   中英

How do I create a Stored Procedure if it doesn't exist in TSQL

I have tried this:

if object_id('a_proc22') is not null
CREATE PROCEDURE a_proc22 AS SELECT 1
go

but it gives me a syntax error.

But this seemed to compile:

if object_id('a_proc22') is not null
EXEC('CREATE PROCEDURE a_proc22 AS SELECT 1')
go

Why is the first one incorrect?

I'm guessing the error is something like "CREATE/ALTER PROCEDURE must be the first statement in a query", so, well, that means that CREATE PROCEDURE must be the first statement in a query. If you wrapped it up on an EXEC , then when its executed, it is the first statement on that query, so that's why it works.

IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[a_proc22]')
           AND TYPE IN (N'P', N'PC'))
DROP PROCEDURE [dbo].[a_proc22];
GO

CREATE PROCEDURE [dbo].[a_proc22]
AS
BEGIN 

-- Code here

END
GO

Your first statement is giving error because after if condition you can not place a create/alter procedure statement. Try this

if Exists(select * from sys.procedures  -- if exists then drop it
    where name = 'a_proc22')
    Drop procedure a_proc22
    GO
    CREATE PROCEDURE a_proc22 -- create the new procedure
    AS
    SELECT 1
    go
if object_id('a_proc22') is not null
drop procedure a_proc22 
go
create procedure a_proc22 
AS 
SELECT 1 

The GO is the important thing here after the drop, you can't have create first, some SQL validation I guess for security purposes.

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[a_proc22]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[a_proc22]
--and create here... Or you can remove the drop and create with if not exists
GO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM