Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Dynamically pass database name to USE
Message
General information
Forum:
Microsoft SQL Server
Category:
SQL syntax
Title:
Dynamically pass database name to USE
Environment versions
SQL Server:
SQL Server 2000
Miscellaneous
Thread ID:
01483661
Message ID:
01483661
Views:
116
I am writing a script that creates my database, stored procedures, tables, user data types etc. The script is over 800 lines and all works perfectly if I hard code the database name on the USE line. Here's the start of it:

-- Create the upower database
declare @dbname varchar(30)
declare @sql varchar(200)

set @dbname = 'utestbase'
set @sql = 'create database ' + @dbname

exec (@sql)
go

use utestbase
go

Now, obviously I want to pass in the "utestbase" value or any other value when I run the script. I just can't figure out how to execute the USE command with a variable, i.e. use @dbname.

I've seen posts on other websites that describe using dynamic sql, as I have done for the create database function. However, it appears that in order to have the USE command in dynamic SQL you have to include the entire script in the batch. I can't do that because, when I try to construct the statement with concatenation, apostrophes just won't work. As you can imagine I have apostrophes all through my code.

How can I set my dynamically named database as the active database before executing my 800 lines of code to create tables and stored procedures, etc?

Thank you.
Elgin Rogers
Epic Solutions
www.epicsolutions.net
Next
Reply
Map
View

Click here to load this message in the networking platform