get the text of a stored procedure into a variable in SQL Server

梦想与她 提交于 2019-12-04 03:16:05

问题


I want to loop through several stored procs and extract one string form each of them to use in another procedure (basically the 4-part remote server string)

So I can get the stored procs list from SysObjects (with Type = P) into a table, then I can loop or cursor through that table variable calling sp_helptext on each one.

But how can I get the text result of sp_helptext into a variable so I can do a CharIndex on the word 'BOCTEST' etc?

Is there a table like sys.procedures that stores the text.


回答1:


The portable way is to use the ANSI/ISO view INFORMATION_SCHEMA.ROUTINES, but you'll only get the first 4000 characters of the stored procedure definition:

declare @source_code varchar(max)

select @source_code = t.ROUTINE_DEFINITION
from information_schema.routines t
where specific_schema = 'owner-schema'             -- e.g., dbo
  and specific_name   = 'my_stored_procedure_name' -- your stored procedure name here

Or you can use the system view sys.sql_modules in the same vein:

declare @source_code varchar(max)

select @source_code = definition
from sys.sql_modules
where object_id = object_id('dbo.my_stored_procedure_name')

Or, the simplest way:

declare @source_code varchar(max)
set @source_code = object_definition( 'dbo.my_stored_procedure_name' )



回答2:


Nicholas Carey's third option needs some changes,

object_definition function needs object_id as parameter,

so the code should be

declare @source_code varchar(max)
declare @objectid int
select @objectid=object_id('dbo.my_stored_procedure_name')
select @source_code = object_definition(@objectid )

Check to this link more details https://msdn.microsoft.com/en-IN/library/ms176090.aspx




回答3:


You can use the system stored procedure sp_helptext to get the stored procedure definition into a table and then just query against that temp table / table variable something like this..

DECLARE @TABLE TABLE
(Line_Number INT IDENTITY(1,1), Text_Column NVARCHAR(MAX));

INSERT INTO @TABLE(Text_Column)
EXECUTE sp_helptext Your_Proc_Name

SELECT * 
FROM @TABLE
WHERE Text_Column LIKE '%BOCTEST%'

UPDATE

SELECT p.name
      ,m.[definition]
FROM  sys.procedures p 
INNER JOIN sys.sql_modules m
ON    P.[object_id] = m.[object_id]
WHERE m.[definition] LIKE '%BOCTEST%'


来源:https://stackoverflow.com/questions/21708681/get-the-text-of-a-stored-procedure-into-a-variable-in-sql-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!