Plateforme Level Extreme
Abonnement
Profil corporatif
Produits & Services
Support
Légal
English
Dynamically pass database name to USE
Message
Information générale
Forum:
Microsoft SQL Server
Catégorie:
Syntaxe SQL
Versions des environnements
SQL Server:
SQL Server 2000
Divers
Thread ID:
01483661
Message ID:
01483893
Vues:
31
If you are using SQL2005 or SQL2008, you can use the SQLCMD.exe utility.

see

Here's an example:
:setvar DatabaseName "MyDatabase"
GO

USE [$(DatabaseName)]
...
Kurt
>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.
Précédent
Répondre
Fil
Voir

Click here to load this message in the networking platform