t-sql stored procedure create scripts
I have a bunch of stored procedure names. I want to export the create script for each of the stored procedure. What is the best way to do it?
Right now I am manually selecting the stored proc in SSMS and selecting "Script stored procedure as -> Drop and Create to"
. This seems tedious. I am hoping there is a better way to deal with this. Thank开发者_开发知识库s.
You can right-click on the database in the Object Explorer and do a Task > Generate Scripts.
That allows you to pick a whole bunch of objects to be scripted (e.g. tables, views, stored procs) and you can store those into a single big SQL file, or one SQL file per object. Works really quite well!
Update: if you want to do this in the SQL Server Management Studio app, you can use this SQL script to find the stored procs and their definitions - you cannot however have SQL Server Mgmt Studio write out the files to disk, that doesn't work - but you can copy the results into e.g. Excel.
SELECT
pr.name ,
pr.type_desc ,
pr.create_date ,
mod.definition
FROM sys.procedures pr
INNER JOIN sys.sql_modules mod ON pr.object_id = mod.object_id
WHERE pr.Is_MS_Shipped = 0
To script out all ones matching a particular criteria you could use something like the below.
DECLARE @t VARCHAR(max) = '';
SELECT @t = @t +
'If OBJECT_ID(''' + QUOTENAME(OBJECT_SCHEMA_NAME(object_id)) + '.' + QUOTENAME(OBJECT_NAME(object_id)) + ''',''p'') IS NOT NULL
DROP PROCEDURE ' + QUOTENAME(OBJECT_SCHEMA_NAME(object_id)) + '.' + QUOTENAME(OBJECT_NAME(object_id)) + '
GO
SET ANSI_NULLS '
+ CASE
WHEN uses_ansi_nulls = 1 THEN 'ON'
ELSE 'OFF'
END
+ '
GO
SET QUOTED_IDENTIFIER '
+ CASE
WHEN uses_quoted_identifier = 1 THEN 'ON'
ELSE 'OFF'
END
+ '
GO
' + definition + '
GO
'
FROM [sys].[sql_modules]
WHERE OBJECTPROPERTY (object_id,'IsProcedure' )=1
AND OBJECT_NAME(object_id) LIKE '%some_patttern%'
/*Stops the long text from getting truncated in SSMS*/
SELECT @t AS [processing-instruction(x)]
FOR XML PATH('')
If you select View --> Summary
Then Click "Stored procedures" from the object explorer it will provide you with a list of all your stored procedures which you can Ctrl/Shift select (select multiples). Then from there you can create all the drop scripts at once then all the create scripts. This is one of the many quirks I've found with SSMS.
Note: Another neat feature is the filter option, allowing you to filter through your stored/tables procedures with ease. Simply right click in the object explorer to bring up the menu.
Something like this would help you.
Using dynamic sql and cursors you can generate script, each in a separate file with .sql extension.
This script will generate script for all procedures whose names are mention in IN clause:
DECLARE @name varchar(100)
DECLARE @Definition varchar(max)
DECLARE @sql varchar(300)
DECLARE @schema varchar(10)
CREATE TABLE TEMPTABLE (ID INT IDENTITY(1,1), def varchar(max))
DECLARE script CURSOR
FOR
SELECT OBJECT_NAME(SYS.SQL_MODULES.OBJECT_ID), [DEFINITION] FROM SYS.SQL_MODULES
INNER JOIN SYS.OBJECTS ON SYS.OBJECTS.OBJECT_ID = SYS.SQL_MODULES.OBJECT_ID WHERE SYS.OBJECTS.TYPE='P'
--AND [NAME] IN('SOME PROC 1','SOME PROC 2','SOME PROC 3','SOME PROC 4') --<------ Mention Proc names you want to generate scripts for
OPEN script
FETCH NEXT FROM script INTO @name, @Definition
WHILE @@FETCH_STATUS = 0
BEGIN
FETCH NEXT FROM script INTO @name, @Definition
SET @schema = (select SYS.SCHEMAS.[NAME] from SYS.OBJECTS
INNER JOIN SYS.SCHEMAS ON SYS.OBJECTS.SCHEMA_ID = SYS.SCHEMAS.SCHEMA_ID
WHERE SYS.OBJECTS.[NAME]='' + @name + '')
SET @sql = 'IF EXISTS (SELECT * FROM ' + (@schema) +
'.PROCEDURES WHERE [NAME] = ''' + @name + ''')' + CHAR(10)
SET @sql = @sql + 'DROP PROCEDURE ' + @schema + '.' + @name + CHAR(10) + 'GO' + CHAR(10)
PRINT @sql
INSERT INTO TEMPTABLE VALUES(@sql + @definition)
SET @Sql = ('BCP "SELECT TOP 1 def FROM TEMPTABLE ORDER BY ID DESC" queryout "D:\' + @name + '.sql" -c -T')
EXEC XP_CmdShell @Sql --<---- Export to file
END
CLOSE script
DEALLOCATE script
SELECT * FROM TEMPTABLE --<----------- Optional
DROP TABLE TEMPTABLE
You might look at sp_helptext for some ideas about how you can leverage that to create your scripts.
Visual Studio 2008 Database Professional Edition and Visual Studio 2010 Professional (and above) supports special project types for SQL Server 2005/2008. These projects support the automatic creation of change scripts, containing all changes between the current project and a specified target database.
AFAIK RedGate also provides some tools like this, though, I don't have any experiences with them.
C:\>BCP "Select '--'+pr.name,
pr.type_desc, pr.create_date, pr.modify_date, CHAR(13)+mod.definition
from DATABASE_NAME.sys.objects pr
INNER JOIN DATABASE_NAME.sys.sql_modules mod ON pr.object_id = mod.object_id
where type='p'" queryout "C:/output.sql" -c -T -S SERVER_NAME
Execute from command prompt... it will return all stored procedures in one file with time stamps on with SP with created/modified date
The following will generate scripts for a set of stored procedure names. The scripts will be saved as a series of .sql files. Insert the names of the procedures to script into @Table.
-- Script Multiple SPROC as drop and create
-- SPROCS to script
DECLARE @Table TABLE (Name VARCHAR(MAX));
INSERT INTO @Table (Name) VALUES ('StoredProcedure1'), ('StoredProcedure2')
-- Drop TempTable if extant: http://stackoverflow.com/questions/659051/check-if-a-temporary-table-exists-and-delete-if-it-exists-before-creating-a-temp
IF OBJECT_ID('tempdb..##Temp') IS NOT NULL DROP TABLE dbo.##Temp
-- Loop through SPROCs
-- Cursor: https://www.mssqltips.com/sqlservertip/1599/sql-server-cursor-example/
-- Substring: http://stackoverflow.com/questions/4662496/trim-left-characters-in-sql-server
DECLARE @item VARCHAR(MAX); -- SPROC Name
DECLARE db_cursor CURSOR FOR
SELECT Name FROM @Table WHERE 1=1
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @item
WHILE @@FETCH_STATUS = 0
BEGIN
-- Execute
-- Print to file using Temp Table: http://stackoverflow.com/questions/10568975/can-i-specify-an-input-sql-file-with-bcp
-- Script SPROC via XML: http://stackoverflow.com/a/3292693/5301903
-- ANSI_NULLS and QUOTED_IDENTIFIER retain current settings.
-- Prepare Temp Table
SELECT
'IF EXISTS(SELECT * FROM sys.procedures WHERE Name = '''+Object_name(object_id)+''')
DROP PROCEDURE [dbo].['+Object_name(object_id)+']
GO
SET ANSI_NULLS '+CASE WHEN CAST(ISNULL(OBJECTPROPERTYEX(object_id,N'ExecIsAnsiNullsOn'),0) AS bit) = 1 THEN 'ON' ELSE 'OFF' END+'
GO
SET QUOTED_IDENTIFIER '+CASE WHEN CAST(ISNULL(OBJECTPROPERTYEX(object_id,N'ExecIsQuotedIdentOn'),0) AS bit) = 1 THEN 'ON' ELSE 'OFF' END+'
GO
' + definition + '
GO' AS Text
INTO dbo.##Temp
FROM [sys].[sql_modules]
WHERE 1=1
--AND OBJECTPROPERTY (object_id,'IsProcedure' )=1
--AND OBJECTPROPERTY (object_id,'IsTable' )=1
--AND Object_name(object_id) LIKE @name
AND Object_name(object_id) = @item
-- Print to text https://social.msdn.microsoft.com/Forums/en-US/71aefd98-ee46-48fe-a129-60791c583555/output-results-to-text-file-using-tsql?forum=transactsql
DECLARE @CMD VARCHAR(1000) = 'bcp "SELECT * FROM ##Temp" queryout C:\temp\'+@item+'.sql -c -T -S '+ @@servername
EXECUTE Master.dbo.xp_CmdShell @Cmd
-- Clean up
DROP TABLE dbo.##Temp
-- End Execute
FETCH NEXT FROM db_cursor INTO @item
END
CLOSE db_cursor
DEALLOCATE db_cursor
精彩评论