基于其他表插入多行(一对多)

时间:2014-06-26 11:10:35

标签: sql sql-server-2008

有两个表Inspector(Parent)和InspectorOfficeAccess(Child),我需要让来自国家(73,74)的检查员可以访问办公室(1,20,24,31,44)。

Inspector表中有许多检查员(超过100个),国家73和74.是否可以在InspectorOfficeAccess表中使用officeid插入所有检查员并使用一个查询?

第二个屏幕截图用于显示最终结果的外观。 InspectorOfficeAcess表为空。

每个检查员将插入5次办公室ID(1,20,24,31,44),其中检查员国家IN(73,74)

enter image description here

ADDED

到目前为止我已尝试过这个

insert into InspectorOfficeAccess 
select i.inspectorid,o.Offices    from Inspectors i
cross join 
        (
        SELECT 1 AS Offices
        UNION 
        SELECT 20
        UNION 
        SELECT 24
        UNION 
        SELECT 31
        UNION
        SELECT 44 
        ) o
where i.CountryID IN (73,74) 

3 个答案:

答案 0 :(得分:0)

试试这个

Insert into InspectorOfficeAcess
Select InspectorOfficeAccessiD,i.InspectorID,oficeid
from  Inspector i 
cross apply(Select 1 union Select 20 union Select 24 union Select 31 union Select 44) d
    where countryid in (73,74)

答案 1 :(得分:0)

如果你必须从其他表中选择Office Id,那么另一种方法是:

Insert into InspectorOfficeAccess
Select I.InspectorID,O.OfficeId
from  Inspector I 
Cross Join Office O
where I.CountryId in (73,74) and O.OfficeId in (1,20,24,31,44);

您可以查看Demo here.

答案 2 :(得分:0)

这适用于您的情况:

SELECT *
FROM (SELECT InspectorID
      FROM Inspector
      WHERE countryid in (73,74)) Inspector
,(VALUES (1),(20),(24),(31),(44)) 
AS InspectorOfficeAcess(InspectorOfficeAcessID)