将存储过程的文本获取到SQL Server中的变量中

Our*_*nas 6 sql stored-procedures sql-server-2008-r2

我想循环遍历几个存储过程并从每个过程中提取一个字符串形式以用于另一个过程(基本上是4部分远程服务器字符串)

所以我可以从SysObjects(使用Type = P)将存储的procs列表放到一个表中,然后我可以循环或通过该表变量调用sp_helptext每个表.

但是如何将文本结果sp_helptext变为变量,以便我可以对" BOCTEST "等单词执行CharIndex

是否存在类似sys.procedures的表来存储文本.

Nic*_*rey 7

可移植的方法是使用ANSI/ISO视图INFORMATION_SCHEMA.ROUTINES,但是您只能获得存储过程定义的前4000个字符:

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
Run Code Online (Sandbox Code Playgroud)

或者您可以sys.sql_modules以相同的方式使用系统视图:

declare @source_code varchar(max)

select @source_code = definition
from sys.sql_modules
where object_id = object_id('dbo.my_stored_procedure_name')
Run Code Online (Sandbox Code Playgroud)

或者,最简单的方法:

declare @source_code varchar(max)
set @source_code = object_definition( 'dbo.my_stored_procedure_name' )
Run Code Online (Sandbox Code Playgroud)

  • 除非过程大于4000个字符,否则您将从INFORMATION_SCHEMA获得任意块.我几年前提出[其他几个原因来避免使用便携式解决方案]时甚至忘了争论这个事实(http://sqlblog.com/blogs/aaron_bertrand/archive/2011/11/03/the-case-针对-信息架构views.aspx).在SQL Server中执行此操作的正确方法是使用`sys.sql_modules`或`object_definition()`. (2认同)
  • 对不起,你是对的,我把INFORMATION_SCHEMA的不良行为与sys.syscomments的不良行为混为一谈.但是它不是varchar(max) - 定义作为**n**varchar(max)存储在底层目录中,但是information_schema将它截断为nvarchar(4000). (2认同)