3

I want to insert:

  • to database TEST, table SUBJECT, field aSubject when @Database = 'TS'
  • to database TEST1, table SUBJECT, field aSubject when @Database = 'TS1'
  • else to database DEMO, table SUBJECT, field aSubject

I tried this:

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'

I get error:

Msg 102, Level 15, State 1, Line 5
Incorrect syntax near '('.
1
  • 3
    A table or column name cannot be a variable. In effect you have to create a new SQL statement that expands the variables. One way to do that is dynamic SQL, like declare @sql varchar(max) = 'select ...'; exec @sql; Commented Aug 29, 2014 at 10:56

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.