Reputation: 26498
I have a query that is dynamically fetching the stored proc names from all the databases. Now I want to execute the stored procs and store the result in a temptable or table variable.
How to do that. Here is my SP so far
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
Please help. Thanks in advance
Upvotes: 1
Views: 408
Reputation: 902
Here's my soluton. Cursors are evil :)
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
Upvotes: 1
Reputation: 1062600
INSERT [TableName] EXEC (@DynSql)
Note that if you introduce data you may want to use sp_ExecuteSQL
, and you probably want to use [
/]
object-name escaping.
Upvotes: 1