Groups | Blog | Home
all groups > sql server new users > september 2006 >

sql server new users : how to use variable in USE method?



Hugo Kornelis
9/26/2006 10:02:20 PM
[quoted text, click to view]

Hi Mark,

You can't use a variable after USE.

One alternative woould be to use dynamic SQL. Since the effect of USE is
limited to the scope, you'd have to put the complete functionality in
the dynamic SQL. Beware of the many pitfalls of dynamic SQL, as
described by Erland: http://www.sommarskog.se/dynamic_sql.html

Another alternative is to use the undocumented system stored procedure
sp_MSforeachdb. Use google to find usage examples.

--
mark
9/27/2006 2:26:54 AM
I wrote a store procedure like this:

declare @dbname nvarchar(50)
declare db_cursor cursor for
select name as database_name from master.dbo.sysdatabases
where has_dbaccess(name) = 1 and (name like '[0-9]%')

open db_cursor

FETCH NEXT FROM db_cursor INTO @dbname

WHILE @@FETCH_STATUS = 0
BEGIN
use @dbname
...

FETCH NEXT FROM db_cursor INTO @dbname
END
....


I cannot compile the commands. How to modify?

Thanks.

Mark

mark
9/27/2006 10:28:37 PM
Thank you very much. It's very helpful.


"Hugo Kornelis" <hugo@perFact.REMOVETHIS.info.INVALID> ????
news:ak1jh2h4drkjdt9squ3gadnhg1u4jjosc7@4ax.com...
[quoted text, click to view]

Paul A. Mestemaker II [MSFT]
9/28/2006 7:50:17 PM
If you are using SQL Server Management Studio, you can enable SQLCMD Mode
and use commands just like you were using SQLCMD from the command line.

http://www.microsoft.com/sql/technologies/manageability/default.mspx
http://msevents.microsoft.com/cui/eventdetail.aspx?eventID=1032290602&Culture=en-US

Paul A. Mestemaker II
Program Manager
Microsoft SQL Server Manageability
http://blogs.msdn.com/sqlrem/

[quoted text, click to view]

AddThis Social Bookmark Button