0

I am trying to store a database name in a variable:

DECLARE @SQLString  varchar(max)
DECLARE @DBIn  varchar(50)

SET @DBIn ='myDB'
SET @SQLString = 'USE ' + @DBIn 

select @SQLString
EXEC(@SQLString)

There are no errors when I execute this code but it does not actually works (the database does not change as it would if I just run a USE [myDB]).

1
  • 4
    It would change in the scope of the dynamic sql, not outside of it Commented Feb 4, 2015 at 17:32

2 Answers 2

2

Why not just add database name to schema.table name?

DECLARE @SQLString  varchar(max)
DECLARE @DBIn  varchar(50)

SET @DBIn ='myDB'
SET @SQLString = 'SELECT * FROM ' + @DBIn + '.dbo.MyTable' 

select @SQLString
EXEC(@SQLString)
Sign up to request clarification or add additional context in comments.

3 Comments

George, I get the following error: "Invalid object name 'myDB.dbo.MyTable' "
That means you don't have table 'MyTable' in the database, I gave it just as example. I've re-read your question, it looks like you want to change database scope, but it is really not needed because you can query every object on same server by using <DBNAME>.<SCHEMANAME>.<OBJECTNAME>
You are correct. I think what is left is for me to change my username.. :) thanks
0

DB name is changed for the script which is included in @SQLString. For e.g, below code will work:

DECLARE @SQLString  varchar(max)
DECLARE @DBIn  varchar(50)

SET @DBIn ='myDB'
SET @SQLString = 'USE ' + @DBIn+ ' SELECT TOP 100 * FROM dbo.MyTable'

select @SQLString
EXEC(@SQLString)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.