使用 SELECT 执行 INSERT 以插入多条记录 [英] Perform INSERT with SELECT to insert multiple records

查看:106
本文介绍了使用 SELECT 执行 INSERT 以插入多条记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下图中,DodgyOldTable"和MainTable"之间存在 1:1 的关系.表Option"在OptionDesc"字段中包含带有OptionVal1"、OptionVal2"和OptionVal3"的记录.我需要使用 DodgyOldTable 中的选择插入 MainTable_Option.像这样:

In the diagram below there is a 1:1 relationship between 'DodgyOldTable' and 'MainTable'. Table 'Option' contains records with 'OptionVal1', 'OptionVal2' and 'OptionVal3' in the 'OptionDesc' field. I need to do an insert into MainTable_Option with a select from DodgyOldTable. Something like this:

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

如果可能,我想避免使用多个不同的选择语句来执行插入操作.

If possible I want to avoid using several different select statements to perform the insert operation.

替代文字 http://www.freeimagehosting.net/uploads/863f10bf5f.jpg

推荐答案

INSERT 
  MainTable_Option 
  (
  MainTableID, 
  OptionID
  )
SELECT
  d.ID, 
  o.OptionId
FROM
  DodgyOldTable d
  INNER JOIN Option o ON
    (d.OptionVal1 = 'Y' AND o.OptionDesc = 'OptionVal1') OR
    (d.OptionVal2 = 'Y' AND o.OptionDesc = 'OptionVal2') OR
    (d.OptionVal3 = 'Y' AND o.OptionDesc = 'OptionVal3')

这篇关于使用 SELECT 执行 INSERT 以插入多条记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆