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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With