2014-08-29 161 views
3

可變我想插入:INSERT INTO與DB

  • 數據庫TEST,表SUBJECT,現場aSubject@Database = 'TS'
  • 數據庫TEST1,表SUBJECT,現場aSubject@Database = 'TS1'
  • 別的數據庫DEMO,表SUBJECT,字段aSubject

我嘗試這樣做:

DECLARE @Database varchar(10) 
Set @Database = 'TS' 

INSERT INTO 
(
CASE 
WHEN @Database = 'TS' THEN 'TEST.dbo.SUBJECT' 
WHEN @Database = 'TS1' then 'TEST1.dbo.SUBJECT' 
ELSE 'DEMO.dbo.SUBJECT' END 
) (aSubject) 
SELECT 'Company' 

我得到錯誤:

Msg 102, Level 15, State 1, Line 5 
Incorrect syntax near '('. 
+3

表或列名不能是一個變量。實際上,您必須創建一個擴展變量的新SQL語句。一種方法是動態SQL,比如'declare @sql varchar(max)='select ...'; exec @sql;' – Andomar 2014-08-29 10:56:03

回答

4
DECLARE @Database SYSNAME; 
Set @Database = 'TS' 

SET @Database = CASE 
        WHEN @Database = 'TS' THEN 'TEST' 
        WHEN @Database = 'TS1' THEN 'TEST1' 
        ELSE 'DEMO' 
       END 


DECLARE @sql NVARCHAR(MAX); 


SET @sql= N' INSERT INTO ' + QUOTENAME(@Database) + N'.[dbo].[SUBJECT] ' 
     + N' SELECT ''Company'' ' 

EXECUTE sp_executesql @sql