用DB变量INSERT INTO

时间:2014-08-29 10:52:15

标签: sql-server tsql variables insert-into

我想插入:

    TEST 时,
  • 到数据库SUBJECT,表aSubject,字段@Database = 'TS'TEST1
  • 时,
  • 到数据库SUBJECT,表aSubject,字段@Database = 'TS1'
  • else to database DEMO,table SUBJECT,field 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 '('.

1 个答案:

答案 0 :(得分: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