June 15, 2010 at 10:19 am
I was wondering if any one could tell me why the following does not work, and the Database is not switched to the database name I set as @CaseName
DECLARE @CaseName nvarchar(256)
Set @CaseName = 'Test'
.........
EXECUTE ('USE ['+@CaseName+']')
-- ******************************************************
-- Create database schemas
-- ******************************************************
PRINT ''
PRINT '*** Creating Database Schemas'
GO
CREATE SCHEMA [RawData] AUTHORIZATION [dbo]
GO
CREATE SCHEMA [Artifacts] AUTHORIZATION [dbo]
GO
The EXECUTE ('USE ['+@CaseName+']') statement dos not work, and will not change to my Test database to create the schemas on Test.
June 15, 2010 at 10:56 am
With the fear of answering this "wrong", I'll throw it out there anyway.
When I try to use a database dynamically, it's usually within a procedure. Then I can use dynamic SQL to do what I need it to do.
Here's a quick piece of code that can maybe help you with your situation.
declare @db varchar(20)
declare @sql varchar(50)
set @db = 'test'
set @sql = 'use [' + @db + ']; select * from table1'
exec (@sql)
I'm anxious to see how some of the experts handle this too.
June 15, 2010 at 11:01 am
calvo's example is exactly correct, i think; the EXEC() statement is stand alone, and does not affect the session/window it is a part of.
so to do what you want, you have to switch to dynamic sql, just as calvo demoed; i think this is what you are after specifically:
declare @sql varchar(50)
set @sql = 'use [' + +@CaseName + ']; CREATE SCHEMA [RawData] AUTHORIZATION [dbo];CREATE SCHEMA [Artifacts] AUTHORIZATION [dbo];'
exec (@sql)
Lowell
June 15, 2010 at 2:43 pm
use db statement and other statements need to be in same exec for change of db context to work
e.g.
set @statement = N'use [' + @name +']'+char(13)+N'exec sp_helpdb [' + @name +']'
exec sp_executesql @statement
---------------------------------------------------------------------
June 15, 2010 at 5:33 pm
Did you look at BOL? Specifically, read the section "Using EXECUTE with a Character String".
Wayne
Microsoft Certified Master: SQL Server 2008
Author - SQL Server T-SQL Recipes
Viewing 5 posts - 1 through 4 (of 4 total)
You must be logged in to reply to this topic. Login to reply
This website stores cookies on your computer.
These cookies are used to improve your website experience and provide more personalized services to you, both on this website and through other media.
To find out more about the cookies we use, see our Privacy Policy