SQL Server – Backup Stored Procedure Code and Permissions

backupsql serversql server 2014stored-procedures

I often get requests to alter stored procedures, in both test, development and production environments.

I would like a simple way to save the current code of the stored procedure, before the changes, into a table in my "tablebackups" database – which is a database where I save records prior to update or delete them.

I am thinking about something like this:

sp_helptext 'sp_myprocedure'

the idea of usage is something like this:

select * into tablebackups.dbo.my_procedure_20150827_1220
from ss_save_my_procedure 'my_procedure'

has someone got a solution for this already developed?

Best Answer

You can use sys.sql_modules (MSDN):

select top 10 * from sys.sql_modules as m
inner join sys.procedures as p on m.object_id = p.object_id
where p.name ...

It is better to alter them because you won't have to worry about existing permissions. If you drop and create the procedure, you have to set them back.

  • DO: if not exists, create empty dummy SP and then alter SP
  • Don't do: if exists, drop SP and then create new SP

This query should put you in the right direction with the permissions:

select 'Proc' = SCHEMA_NAME(p.schema_id)+'.'+p.name
    , 'Type' = per.state_desc, 'Permission' = per.permission_name
    , 'Login' = pri.name, 'Type' = pri.type_desc 
    , *
From sys.procedures as p
left join sys.database_permissions as per on p.object_id = per.major_id
left join sys.database_principals as pri on per.grantee_principal_id = pri.principal_id
where ...