I know the following two patterns to write scripts for creating stored procedures, which can be executed repeatedly without throwing errors.
if object_id('my_proc') > 0 drop procedure my_proc go create procedure dbo.my_proc as Print 'This is not a dummy';
and the other which preserves permissions
if object_id('my_proc') is null EXEC ('create procedure dbo.my_proc as Print ''This is a dummy'''); go ALTER PROCEDURE dbo.my_proc as Print 'This is not a dummy';
I guess when the procedure exists and its hash code is the same as that of the new version, than there would be no need to drop and recreate or alter the procedure.
My problem is that HashBytes is limited to a maximum of 8000 bytes and I can't use it generally like
if object_id('my_proc') is null EXEC ('create procedure dbo.my_proc as Print ''This is a dummy'''); go if object_Id('my_proc') > 0 and ( Select HashBytes('MD5',definition) MD5 from sys.sql_modules m join sysobjects o on o.id = m.object_id where o.name = 'my_proc' ) <> 0x9028A1B9D93AC7592EC939CCABF9D3DE begin print 'definition has changed'; EXEC ('ALTER PROCEDURE dbo.my_proc as Print ''This is not a dummy'''); end
For procedures whose definition are longer than 4000 Characters. Any proposals to handle these cases in a similar way?
It is not only that I want to avoid flushing of cached plans.
I also have to cope with different customers having different versions of a stored procedure where I only want to replace one of these variants by a newer version.