views:

37

answers:

3

Is there a way to do something like this without converting the sql to a string and calling exec

DECLARE @source_database varvhar(200)
SELECT @source_database = 'wibble'

SELECT * FROM SELECT @source_database.dbo.mytable
+3  A: 

No. I'm afraid not.

It is necessary to use dynamic sql in order to use a variable for either a database or column name.

Mitch Wheat
That is what I was expecting to hear, thanks.
Andrew
+2  A: 

Only for stored procs without using linked server or dynamic SQL

DECLARE @myProc  varchar(200)
SELECT @myProc  = 'wibble.dbo.foobar'

EXEC @myProc
gbn
A: 

There is another (not necessarily pretty) alternative:

IF (@source_database = 'wibble')
    USE wibble;
ELSE IF (@source_database = 'wibble2')
    USE wibble2;
ELSE
    RAISERROR(....)

SELECT * FROM dbo.myTable

If you have any real number of databases, this may be tiresome. But it's an option nonetheless.

AdaTheDev
Thanks for the suggestion. I didn't put my question into the context of the solution that I am working on. I have a source database and a target database so the use statement works fine to ensure the source database is correct but, I then need to explicitly reference the target database in the sql query.
Andrew