Create Stored Procedure IF NOT EXISTS (SQL Server)

This is especially useful if you're writing update scripts like I am.

IF NOT EXISTS(Select * from sysobjects where name = 'usp_UserSproc')
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE usp_UserSproc
(
@ID int = NULL --nullable input
)

AS
BEGIN
SET NOCOUNT ON;
IF @ID IS NOT NULL
SELECT * FROM My_Table WHERE ID=@ID;
ELSE
SELECT * FROM My_Table WHERE ID=1;
END';
END

No comments: