Search code examples
sql-serverconditional-statementsinsert-into

Is there a way to choose a table in an INSERT INTO clause with a conditional?


I have two tables, we can call them table1 and table2, and a variable to determine which table to INSERT INTO. I want to do something like this:

DECLARE @intoTable2 BIT = 0;
INSERT INTO
    IF @intoTable2 = 1
        table2
    ELSE
        table1
--put column names and values here...

All of the column names between the two tables are the same except the first one, so I would also need a corresponding IF statement for the first column as well. (I could just write out two INSERT INTO statements and wrap them in an IF-ELSE clause, but there are a lot of column names, and I'm just trying to keep it from being too clunky.


Solution

  • but there are a lot of column names, and I'm just trying to keep it from being too clunky.

    It's not always possible in TSQL to avoid cut-and-paste. Keep the long column list on one line to enable cut-and-paste and not waste vertical space

    In TSQL the INSERT would come after the IF.

    DECLARE @intoTable2 BIT = 0;
    IF @intoTable2 = 1
    BEGIN
        INSERT INTO table2 ( ... )
        values ( ... );
    END
    ELSE
    BEGIN
        INSERT INTO table2 ( ... )
        values ( ... );
    END
    

    Or you could use dynamic sql

    declare @sql = concat(N'insert into ', case when @intoTable2 = 0 then 'table1' else 'table2' end, ' values ...')
      --print(@sql)  
      exec (@sql)