Evaluate in T-SQL

后端 未结 11 2208
悲&欢浪女
悲&欢浪女 2020-12-17 23:42

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

11条回答
  •  庸人自扰
    2020-12-17 23:57

    You can't specify a dynamic table name in SQL Server.

    There are a few options:

    1. Use dynamic SQL
    2. Play around with synonyms (which means less dynamic SQL, but still some)

    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.

提交回复
热议问题