Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
266 views
in Technique[技术] by (71.8m points)

sql server - Generating create stored procedure script using SQL syntax only

I am aware it is possible in SQL Server Management Studio to generate a create stored procedure script using the Object Explorer (right click on stored procedure, "Script stored procedure as...", Create To)

Is it possible to generate a create script string using SQL syntax only?

declare @createSPstring varchar(max)
/*
insert code to generate the create stored procedure string and put it into @createSPString...
*/
select @createSPstring
question from:https://stackoverflow.com/questions/65933441/generating-create-stored-procedure-script-using-sql-syntax-only

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can get the full text from the view: sys.sql_modules

However your selectmight not get the full code, since a nvarchar(maX) is cut of in SSMS.

One option is to use print to print each row from the definition. Here I split the definition on char(13) to get each row and use a cursor (yes i know) to print each row.

DECLARE @createSPstring VARCHAR(MAX)
-- get definition of procedure "test"
SELECT @createSPstring = definition
FROM sys.sql_modules
WHERE object_id = OBJECT_ID('test')

-- Declare cursor - split definition on line break
DECLARE rows CURSOR FOR
    SELECT [value] row
    FROM STRING_SPLIT(@createSPstring, CHAR(13))

DECLARE @row NVARCHAR(MAX)
OPEN rows

FETCH NEXT FROM rows INTO @row

WHILE @@fetch_status = 0
BEGIN
    --Print each row
    PRINT REPLACE(@row,'char(10)','')
    FETCH NEXT FROM rows INTO @row
END

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...