Perform INSERT with SELECT to insert multiple records

后端 未结 7 1297
情深已故
情深已故 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:38

    What about CROSS JOIN solution?

    DECLARE @DodgyOldTable TABLE (ID INT, OptionVal1 CHAR, OptionVal2 CHAR, 
      OptionVal3 CHAR)
    INSERT INTO @DodgyOldTable
    SELECT 1, 'y', 'n', 'y' UNION
    SELECT 2, 'y', 'n', 'n' UNION
    SELECT 3, 'n', 'n', 'y' UNION
    SELECT 4, 'y', 'y', 'y' UNION
    SELECT 5, 'n', 'n', 'n'
    
    DECLARE @Option TABLE (OptionID INT, OptionDesc VARCHAR(100))
    INSERT INTO @Option
    SELECT 1, 'OptionVal1' UNION
    SELECT 2, 'OptionVal2' UNION
    SELECT 3, 'OptionVal3'
    
    SELECT ID, OptionID FROM
    (
        SELECT 
            ID, 
            CASE    
              WHEN (OptionVal1 = 'y' AND OptionDesc = 'OptionVal1') 
                OR (OptionVal2 = 'y' AND OptionDesc = 'OptionVal2') 
                OR (OptionVal3 = 'y' AND OptionDesc = 'OptionVal3')
              THEN OptionID 
              ELSE NULL 
            END AS OptionID 
        FROM @DodgyOldTable DOT CROSS JOIN @Option O 
    )CRS
    WHERE OptionID IS NOT NULL
    

提交回复
热议问题