Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL is it possible to use a variable in a select statement to specify the database

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
like image 269
Andrew Avatar asked Feb 12 '10 10:02

Andrew


People also ask

How do I use a variable in SQL select statement?

The syntax for assigning a value to a SQL variable within a SELECT query is @ var_name := value , where var_name is the variable name and value is a value that you're retrieving. The variable may be used in subsequent queries wherever an expression is allowed, such as in a WHERE clause or in an INSERT statement.

Can you declare a variable in a select statement?

Variables in SQL procedures are defined by using the DECLARE statement. Values can be assigned to variables using the SET statement or the SELECT INTO statement or as a default value when the variable is declared.

How do you set a variable in a select statement in SQL server?

Setting a Value in a Transact-SQL Variable To assign a value to a variable, use the SET statement. This is the preferred method of assigning a value to a variable. A variable can also have a value assigned by being referenced in the select list of a SELECT statement.

What are the advantages when using a variable in T SQL?

Advantages of table variables. Table variables don't require locking and logging resources, nor do they have to be stored in a database (although see hinit below). For this reason, they will run more quickly than temporary tables.


2 Answers

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.

like image 198
Mitch Wheat Avatar answered Nov 15 '22 08:11

Mitch Wheat


Only for stored procs without using linked server or dynamic SQL

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

EXEC @myProc
like image 21
gbn Avatar answered Nov 15 '22 08:11

gbn