-
USE @dbname (Use statement with variable)
Hi
I need to run a stored procedure on each database in my SQL server. I want to have a loop to go through each db.
Is there a way I can run 'Use @dbname', I tried Execute and sp_executesql but it didn't work.
I want to execute the SP withing each db.
Thanks
-
USE @dbname (Use statement with variable) (reply)
Hi,
there are several ways you can do this. By far the easiest way is to use the system proc sp_MSforeachdb as follows.
sp_MsForeachdb 'EXEC <dbname>.dbo.<procname>'
this will execute the proc in every database (including master,model,msdb and tempdb) and you don't even need to code for the loop.
If you do want to code the loop then you can use the EXEC statement.
DECLARE @DBName varchar(40)
--loop code goes here somewhere
EXEC('USE ' + @DBName + ' EXEC <dbname>.dbo.<procname>'
Hope that helps,
Karl
------------
AAA at 6/12/2002 4:27:12 PM
Hi
I need to run a stored procedure on each database in my SQL server. I want to have a loop to go through each db.
Is there a way I can run 'Use @dbname', I tried Execute and sp_executesql but it didn't work.
I want to execute the SP withing each db.
Thanks
-
USE @dbname (Use statement with variable) (reply)
I have a similar situation which is not to exec a proc, but to update existing procs and triggers for each db in the server. dynamic exec 'Use...'
did not do much for me since the updProc.sql has > 30,000 chars and with many 'go' keywords and /* */ marks.
Any idea to loop to implement changes on one server, and eventually on many servers?
thanks
David
------------
Karl at 6/13/2002 4:12:54 AM
Hi,
there are several ways you can do this. By far the easiest way is to use the system proc sp_MSforeachdb as follows.
sp_MsForeachdb 'EXEC <dbname>.dbo.<procname>'
this will execute the proc in every database (including master,model,msdb and tempdb) and you don't even need to code for the loop.
If you do want to code the loop then you can use the EXEC statement.
DECLARE @DBName varchar(40)
--loop code goes here somewhere
EXEC('USE ' + @DBName + ' EXEC <dbname>.dbo.<procname>'
Hope that helps,
Karl
------------
AAA at 6/12/2002 4:27:12 PM
Hi
I need to run a stored procedure on each database in my SQL server. I want to have a loop to go through each db.
Is there a way I can run 'Use @dbname', I tried Execute and sp_executesql but it didn't work.
I want to execute the SP withing each db.
Thanks
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
|