Perform INSERT with SELECT to insert multiple records

后端 未结 7 1291
情深已故
情深已故 2021-02-05 08:13

In the diagram below there is a 1:1 relationship between \'DodgyOldTable\' and \'MainTable\'. Table \'Option\' contains records with \'OptionVal1\', \'OptionVal2\' and \'OptionV

7条回答
  •  [愿得一人]
    2021-02-05 08:26

    You could UNION all of selects together to give one result set but it depends on your reasons for not wanting the multiple selects - if there are too many or the number of selects may change frequently it'll still be a pain to amend the query with the additional selects. Unfortunatly I think you will have to put the logic somewhere that determines which bit(s) of DodgyOldTable map to the new structure and either write a migration script (or SSIS package) to bulk migrate (if this is a one off job) or UNION your results together...

    INSERT MainTable_Option ([MainTableID],[OptionID])
    SELECT ID, (CASE WHEN OptionVal1 = 'y' THEN (SELECT OptionID FROM Option WHERE OptionDesc = 'OptionVal1') END
    FROM DodgyOldTable
    WHERE OptionVal1 = 'y
    UNION
    SELECT ID, (CASE WHEN OptionVal2 = 'y' THEN (SELECT OptionID FROM Option WHERE OptionDesc = 'OptionVal2') END
    FROM DodgyOldTable
    WHERE OptionVal2 = 'y
    ...
    

提交回复
热议问题