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
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
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 normalCREATE
statement by creating the database object if the database object does not exist and works like a normalALTER
statement if the database object already exists.
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