I've got a situation where I need to execute portions of a script against every database on a given instance. I don't know the name of all the databases beforehand so I need to scroll through them all and call the "use" command appropriately.
I need the correct syntax, the following won't work:
DECLARE DBS CURSOR FOR
SELECT dbname
FROM #helpdb
ORDER BY dbname
OPEN DBS
FETCH NEXT
FROM DBS
INTO
@.dbname
WHILE @.@.FETCH_STATUS = 0
BEGIN
USE @.dbname
The last line - the "USE" statement - is invalid. The following for example works:
USE master
But when supplied a declared variable a syntax error results for the use command because it expects an identifier.
So .. what is the correct syntax to pass a declared parameter to "USE", or is there another way to meet this requirement?
Thanks for your time.
This is not possible right now since you cannot use variables in lot of statements in place of options or identifiers. You can use dynamic SQL though and below is the easiest way to do it:
declare @.sp nvarchar(500)
...
while .....
begin
-- use dbo.sp_executesql for SQL Server 2000
set @.sp = quotename(@.dbname) + N'sys.sp_executesql'
exec @.sp N'your sql string that needs to execute against db'
...
end
|||although this allowed the "use .." statement to run, it didn't have the effect I need. The remainder of the script was still running in the context of the original database.|||So here's what I really need:
I need a way to switch the context of a script from one database to another, where I do not know the name of the databases beforehand (so they can't be hard-coded).
|||What I suggested will work provided the code that you want to run within context of the database is executed dynamically. Another approach is to pre-process the script file based on the database name and then run it. With SQL Server 2005, you can do this using SQLCMD pre-processing features.