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

前端 未结 3 1316
天命终不由人
天命终不由人 2021-01-18 07:10

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

3条回答
  •  盖世英雄少女心
    2021-01-18 07:16

    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' )
    

提交回复
热议问题