Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Author |
Topic |
changcg
Starting Member
2 Posts |
Posted - 2013-09-18 : 12:26:13
|
Hello,I have a cursor that goes through a table with the names of all the database in my server. So for each fetch, the cursor gets the name of a database and assign it to a variable, @databaseName, and try to do some queries from that database by using the command "USE @databaseName". But "USE" doesn't take the variable @databaseName; it is expecting a database name (i.e. USE master).Here is my code:Declare @databaseName varchar(50)Declare c_getDatabaseName CURSOR for SELECT name from tblDatabasesOPEN c_getDatabaseName FETCH NEXT from c_getDatabaseName into @databaseNameWhile @@FETCH_STATUS = 0 BEGIN USE @databaseName <-- here is the problem GO -- more code here -- more code here ENDCLOSE c_getDatabaseNameDEALLOCATE c_getDatabaseNameGO Any Ideas on how to get USE to take the variable value ?Any help will be greatly appreciated. Thanks in advance.changcg |
|
James K
Master Smack Fu Yak Hacker
3873 Posts |
|
changcg
Starting Member
2 Posts |
Posted - 2013-09-18 : 15:32:16
|
I will try spMSforeachdb, it seems to be powerfull.Thanks a lot for your help. |
|
|
James K
Master Smack Fu Yak Hacker
3873 Posts |
Posted - 2013-09-18 : 16:27:18
|
Great. Now that I am thinking about it, dynamic SQL would not work for you anyway. |
|
|
|
|
|