0

I have a process that sends variables to a database push. Depending on 1 variable - the table name changes to where the information is pushed.

I.E. Table A has 3 columns and table B has 3 columns. My attempt at a dynamic insert using IIF looks like this:

DECLARE @TableName VARCHAR(100)
SET @TableName = (SELECT IIF(${@var1}$ = 'A', 'TABLE_A', 'Table_B'))

SELECT @TableName

INSERT INTO @TableName (Var2_Name, Created_Date, Deleted_Date) 
VALUES (@Var2, getutcdate(), getutcdate());

The first SELECT @TableName shows me the value of the IIF but when I try using it in the insert, it fails and says

Must declare the table variable @TableName.

Is there a way for it to recognize the table name when inserting or is there another way to do a dynamic insert.

2 Answers 2

1

If the query is static your tables and columns names must be static too.

For dynamic table or column names, you should generate the full SQL dynamically, and use sp_executesql to execute it.

Something like this should do it, sorry if I made a syntax error, coded on the fly.

DECLARE @TableName varchar(100) = (SELECT IIF(${@var1}$ = 'A', 'TABLE_A', 'Table_B'))

SELECT @sql = 
N 'INSERT INTO ' + @TableName + '(Var2_Name, Created_Date, Deleted_Date) ' + 
N 'VALUES (' + @Var2 + ', getutcdate(), getutcdate())'

EXEC sp_executesql @sql
Sign up to request clarification or add additional context in comments.

Comments

1

you could two inserts

insert into TABLE_A select @Var2, getutcdate(), getutcdate() where @var1 = 'A'
insert into Table_b select @Var2, getutcdate(), getutcdate() where @var1 = 'B'

..or use a condition, your case doesn't require dynamic sql, e.g.:

if (@var1 = 'A')
    insert into Table_A ....
else
    insert into Table_B ....

1 Comment

This is better option than generating full dynamic SQL string.

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.