Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the downsides of creating SQL Server stored procedures in the following manner?

We check in all our database objects into source control as rerunnable scripts (views, functions, triggers & stored procedures etc...)

When it comes time to deploy, we need to ensure that all the scripts are re-runnable & repeatable so that a stored procedure is be created/updated to the latest version.

Are there any downsides to creating the scripts in the following manner.

IF NOT EXISTS 
(
    SELECT      * 
    FROM        INFORMATION_SCHEMA.ROUTINES
    WHERE       ROUTINE_SCHEMA = 'dbo'
    AND         ROUTINE_NAME = 'MyStoredProcedure'
)
BEGIN
    EXEC ('CREATE PROCEDURE [dbo].[MyStoredProcedure] AS SELECT 1')
    -- ALSO DO ANY INITIAL GRANT PRIVILEGE SCRIPTING HERE
END
GO
ALTER PROCEDURE [dbo].[MyStoredProcedure] (
    @param1 INT,
    @param2 NVARCHAR(50) = 'Default String'
)
AS
BEGIN
    -- DO SOMETHING WITH @param1 AND @param2
    SELECT 1;
END
GO

Essentially the script checks to see if the object exists in the relevant system view, and if it doesn't exist, some dynamic sql creates it as a stub to get around CREATE PROCEDURE/GO statement issues not being allowed in conditional blocks. Then it applies the actual functionality of the script through an ALTER.

So the benefits are obvious to me, I'm just wondering are there any downsides to doing this... other than the slight overhead of writing slightly more verbose scripts.

like image 574
Eoin Campbell Avatar asked Nov 04 '22 08:11

Eoin Campbell


1 Answers

10 year SQL Server developer/architect here, and I can't think of any downsides other than the (relatively slight) upfront cost of creating the script that will do this.

If you are concerned that a plan compiled as trivial at the time of creation is not recompiled when the procedure is ALTERed, you could add an explicit call to SP_RECOMPILE for each, but I have never had this this problem with SQL Server (I have had it with DB2) and so I think that is excessive caution.

This is an interesting and I think useful approach.

like image 153
DeanGC Avatar answered Nov 08 '22 07:11

DeanGC