tags:

views:

54

answers:

2

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

+1  A: 
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.

Marc Gravell
I just did insert into #temp EXEC (@DynSql)I got the error Msg 208, Level 16, State 0, Line 17Invalid object name '#temp'.
priyanka.sarkar
Also after that I have to execute the stored procs and store the result in a temptable or table variable.
priyanka.sarkar
Well - does #temp exist? Try using a table variable... it works fine for me.
Marc Gravell
yes it worked.. thanks a lot
priyanka.sarkar
+1  A: 

Hello priyanka,

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
Aryadev
thank you very much.. sp_executesql are really nice
priyanka.sarkar