May 12, 2009 at 6:31 am
Hi All
I have a problem, I need to be able to write a loop that will loop through all databases and run a stored procedure against that database in a loop, I don’t want to have to use the USE statement.
Scenario: I have a procedure on a database called test, but I want to run the procedure against all the databases without having to change database name from Query analyzer, I want to be able to put this in a loop.
Thanks
Declare @sql varchar(3000)
Set @sql = ‘Use ‘ + @dbname + ‘ exec test.dbo.SPNAme ‘ + @dbname
May 12, 2009 at 7:25 am
Try this:
EXEC sp_msforeachdb 'Use ?; exec test.dbo.SPNAme ''?'' '
It should work.
-- Gianluca Sartori
May 12, 2009 at 8:02 am
You can either use the un-documented procedure "sp_MSforeachdb" or dynamic sql.
--Using un-documented procedure sp_MSforeachdb
EXECUTE dbo.sp_MSforeachdb 'EXECUTE [?].dbo.SomeProcedure'
-- Using Dynamic SQL
DECLARE @sql VARCHAR(MAX)
SELECT @sql = ISNULL( @sql + ';' + CHAR(10), '' ) + 'EXECUTE [' + [name] + '].dbo.SomeProcedure'
FROMsys.databases
PRINT @sql
--EXECUTE( @sql )
--Ramesh
Viewing 3 posts - 1 through 2 (of 2 total)
You must be logged in to reply to this topic. Login to reply