I\'ve got a stored procedure that allows an IN parameter specify what database to use. I then use a pre-decided table in that database for a query. The problem I\'m having i
You can't specify a dynamic table name in SQL Server.
There are a few options:
You've said you don't like 1, so lets go for 2.
First option is to restrict the messyness to one line:
begin transaction t1;
declare @statement nvarchar(100);
set @statement = 'create synonym temptablesyn for db1.dbo.test;'
exec sp_executesql @statement
select * from db_syn
drop synonym db_syn;
rollback transaction t1;
I'm not sure I like this, but it may be your best option. This way all of the SELECTs will be the same.
You can refactor this to your hearts content, but there are a number of disadvantages to this, including the synonym is created in a transaction, so you can't have two of the queries running at the same time (because both will be trying to create temptablesyn). Depending upon the locking strategy, one will block the other.
Synonyms are permanent, so this is why you need to do this in a transaction.