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.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Can I use a variable at 'USE' statement?

Author  Topic 

Kim Yoon-seop
Starting Member

2 Posts

Posted - 2011-07-12 : 00:37:33
I want to make a procedure to check all databases that I manage.
So I try to change current DB using USE statement.
A database name is a variable.
For example

DECLARE @DB_NAME varchar(10)
SET @DB_NAME = "BS0002"
USE @DB_NAME


When I Excuted the query above, I got an error masage.

So I altered the query like this.


DECLARE @DB_NAME NVARCHAR(10)
DECLARE @STMT NVARCHAR(50)

SET @DB_NAME = 'BS0002'
SET @STMT = 'USE ' + @DB_NAME

EXECUTE sp_executesql @STMT


I got a massage "Command(s) completed successfully." but didn't change current database.

If anyone who knows the answer, please help me.

Thank you.


tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2011-07-12 : 00:44:08
Well you can't do it like that. There are several ways to workaround this, like using the 3-part naming convention for objects or using sp_executesql.

So tell us what you are really trying to do so that we can help you.

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page

Kim Yoon-seop
Starting Member

2 Posts

Posted - 2011-07-12 : 00:56:02
Thank you tkizer.

DECLARE dbname_cursor CURSOR
FOR
SELECT NAME
FROM SYS.DATABASES
WHERE NAME LIKE ('BS%')

OPEN dbname_cursor
FETCH NEXT FROM dbname_cursor
INTO @DB_NAME

WHILE @@FETCH_STATUS = 0
BEGIN

USE @DB_NAME

select @data_size = sum(convert(bigint,case when status & 64 = 0 then size else 0 end))
, @log_size = sum(convert(bigint,case when status & 64 <> 0 then size else 0 end))
, @db_size = @data_size + @log_size
from dbo.sysfiles


I got all of user database name from SYS.DATABASES.
I want to check the size of all user database using cursor so I have to use while statment changing current DB.

Can you understand what I want to do?

I think you mean that 3 part naming is "BS0001.dbo.sysfiles" .
Right?
Go to Top of Page

webfred
Master Smack Fu Yak Hacker

8781 Posts

Posted - 2011-07-12 : 02:06:50
google for

sql server sp_msforeachdb file size

and you will get a lot of ideas


No, you're never too old to Yak'n'Roll if you're too young to die.
Go to Top of Page

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2011-07-12 : 13:24:15
How about just using sp_databases instead?

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page
   

- Advertisement -