如何从动态生成的查询+ sql server执行存储过程

时间:2009-11-10 07:06:13

标签: tsql

我有一个查询,它从所有数据库中动态获取存储的proc名称。 现在我想执行存储过程并将结果存储在temptable或表变量中。

如何做到这一点。这是我到目前为止的SP

Declare @GetDBNames sysname
Declare @DynSql nvarchar(max)

Declare DBNames cursor for 
Select '['+name+']' from master.dbo.sysdatabases 

open DBNames
FETCH NEXT FROM DBNames into @GetDBNames

WHILE @@FETCH_STATUS=0
BEGIN

SET @DynSql = '
Select Specific_Catalog as Database_Name, Routine_Name as ''Stored Procedure Name''
From '+ @GetDBNames+'.Information_Schema.Routines '

EXEC (@DynSql)
FETCH NEXT FROM DBNames into @GetDBNames
END

Close DBNames
Deallocate DBNames 

请帮忙。 提前致谢

2 个答案:

答案 0 :(得分:1)

INSERT [TableName] EXEC (@DynSql)

请注意,如果您引入数据,则可能需要使用sp_ExecuteSQL,并且您可能希望使用[ / ]对象名称转义。

答案 1 :(得分:1)

这是我的解决方案。游标是邪恶的:))

Declare @DynSql nvarchar(max)
declare @result table ([Database_Name] nvarchar(128), [Stored Procedure Name] sysname)

SET @DynSql = ''
select @DynSql = @DynSql + '
Select SPECIFIC_CATALOG COLLATE DATABASE_DEFAULT as Database_Name, ROUTINE_NAME COLLATE DATABASE_DEFAULT as [Stored Procedure Name]
From ' + NAME + '.INFORMATION_SCHEMA.ROUTINES' + CHAR(13) + 'union all' + CHAR(13) 
from master.dbo.sysdatabases

--remove last "union all"
SET @DynSql = left(@DynSql, LEN(@DynSql) - 10) 

insert @result
exec sp_executesql @DynSql 

select * from @result