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.