RE: USE Command With Dynamic Database Names Fails to Change Database
From: Jesse Beveridge (jesse_at_nospam.nospam)
Date: 02/08/05
- Next message: E Sullivan: "sysprocesses and Visual Basic Program"
- Previous message: Allan Mitchell: "Re: DTS Programming Question -- how to remove custom transformations"
- In reply to: Dale Jackson: "USE Command With Dynamic Database Names Fails to Change Database"
- Next in thread: Jesse Beveridge: "Re: USE Command With Dynamic Database Names Fails to Change Database"
- Reply: Jesse Beveridge: "Re: USE Command With Dynamic Database Names Fails to Change Database"
- Reply: Dale Jackson: "RE: USE Command With Dynamic Database Names Fails to Change Databa"
- Messages sorted by: [ date ] [ thread ]
Date: Tue, 8 Feb 2005 11:59:03 -0800
When you call EXEC('somesql') everything in the parenthesis is execute in
it's own scope.
>From BOL:
"Changes in database context last only until the end of the EXECUTE statement"
So after you create your DB's you can preface the subsequent statements with
the database name. (e.g. dbname..tablename).
"Dale Jackson" wrote:
> I am trying to create a new database using a variable name for the database
> name and then switch to the new database to create a set of tables, views and
> stored procedures.
>
> DECLARE @NewDB varchar(35),@SQLStr varchar(1000)
> SELECT @NewDB = 'MyDatabase'
>
> IF NOT EXISTS (SELECT Name FROM Master.dbo.SysDatabases WHERE
> Has_DBAccess(Name) = 1 and Name = @NewDB)
> BEGIN
> SELECT @SQLStr = 'CREATE Database '+@NewDB
> EXEC (@SQLStr)
> END
> go
>
> IF EXISTS (SELECT Name FROM Master.dbo.SysDatabases WHERE Has_DBAccess(Name)
> = 1 and Name = @NewDB)
> BEGIN
> EXEC ('USE '+@NewDB)
> SELECT DB_NAME()
> END
> go
>
> The first command is successful and creates the new database, but the second
> execute statement fails and shows that I'm still connected to the "Master"
> database. Using dynamic SQL to create the hundreds of tables, views and
> procedures from the Master database is not acceptable. Any suggestions?
>
>
- Next message: E Sullivan: "sysprocesses and Visual Basic Program"
- Previous message: Allan Mitchell: "Re: DTS Programming Question -- how to remove custom transformations"
- In reply to: Dale Jackson: "USE Command With Dynamic Database Names Fails to Change Database"
- Next in thread: Jesse Beveridge: "Re: USE Command With Dynamic Database Names Fails to Change Database"
- Reply: Jesse Beveridge: "Re: USE Command With Dynamic Database Names Fails to Change Database"
- Reply: Dale Jackson: "RE: USE Command With Dynamic Database Names Fails to Change Databa"
- Messages sorted by: [ date ] [ thread ]
Relevant Pages
|