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
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.
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.
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.
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.
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.
Only for stored procs without using linked server or dynamic SQL
DECLARE @myProc varchar(200)
SELECT @myProc = 'wibble.dbo.foobar'
EXEC @myProc
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With