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
 SQL Server 2005 Forums
 Transact-SQL (2005)
 How to use declared variable in USE statement ?

Author  Topic 

clerus
Starting Member

8 Posts

Posted - 2008-12-16 : 05:22:37
-- Hello Guys !!!
-- Do you have a solution for this?

-- The scenario goes something like this..
Declare @dbName nvarchar(100)
Set @dbName = 'SampleDatabase'
Print 'The database is : ' + @dbName


-- Then output will be..
The database is : SampleDatabase

-- In this part, it was succesfully executed.
-- But when we try to use the variable @dbName this way...
Declare @dbName nvarchar(100)
Set @dbName = 'SampleDatabase'
Use @dbName
<<--- the error is in here

-- Error message appears..
Incorrect syntax near '@dbName'.

-- How can we run Use @dbName as though we are
-- using Use SampleDatabase ?

-- Thanks very much in advance!!


"The good you do today may be forgotten tomorrow. Do good anyway."
--Mother Theresa--

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2008-12-16 : 05:25:10
[code]
Declare @dbName nvarchar(100)
Set @dbName = 'SampleDatabase'
EXEC ('Use '+ @dbName)
[/code]
Go to Top of Page

clerus
Starting Member

8 Posts

Posted - 2008-12-16 : 05:59:53
Wow thanks a lot! it works! Great!
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2008-12-16 : 07:04:50
welcome
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2008-12-16 : 07:10:19
Make sure you read this fully
www.sommarskog.se/dynamic_sql.html

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page

clerus
Starting Member

8 Posts

Posted - 2008-12-16 : 20:41:08
oh this will be a really big help
Actually Im just a beginner in the field of SQL and I'm very happy and blessed I've found this SQL Forum. I hope could be like you guys in the future.

Umm may I know how long have you been in the SQL field as DBA's?
Again thanks to you guys,madhivanan and visakh16
You're the best !!!
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2008-12-16 : 23:35:28
quote:
Originally posted by clerus

oh this will be a really big help
Actually Im just a beginner in the field of SQL and I'm very happy and blessed I've found this SQL Forum. I hope could be like you guys in the future.

Umm may I know how long have you been in the SQL field as DBA's?

Again thanks to you guys,madhivanan and visakh16
You're the best !!!



I'm not DBA,I'm on development.I've about 5 yrs exp
Go to Top of Page

clerus
Starting Member

8 Posts

Posted - 2008-12-17 : 04:19:01
Aha cool
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2008-12-17 : 04:21:46
Cheers
Go to Top of Page
   

- Advertisement -