将条件插入表中

问题描述 投票:0回答:3

我有两个桌子

表1

            OfficeID  OfficeName
            -------------------
            1          UK
            2          JP
            3          US1
            4          US2
            5          US3
            6          US4

[OfficeID是一个身份自动递增列。

我需要在table1中增加几个办公室(例如US5,US6):

insert into  Table1 (OfficeName) 
values ('US5'), ('US6')

我还有另一张桌子2

            OrgID   OfficeID
            ---------------- 
            1            1
            2            2 
            3            3
            3            4
            3            5
            3            6  

在插入US5和US6之后,表1中的新数据将是

            OfficeID  OfficeName
            -------------------
            1          UK
            2          JP
            3          US1
            4          US2
            5          US3
            6          US4
            7          US5
            8          US6

此后,我想在表2中插入officeID,以便我的表2看起来像这样:

            OrgID   OfficeID
            ---------------- 
            1            1
            2            2 
            3            3
            3            4
            3            5
            3            6 
            3            7
            3            8

这是我要尝试的方式

insert into Table2 (OfficeID) 
    select OfficeID 
    from table1 
    where OfficeID in ((7), (8))
      and table2.OrgID = 3

如何实现?谢谢

sql-server sql-server-2012
3个回答
2
投票

您应该定义要插入的所有列:

         insert into Table2  (OfficeID, OrgID) 
         select OfficeID, 3 from table1 where OfficeID in ((7),(8))

0
投票

如果要在表2中插入标识列,请尝试OUTPUT子句

Insert into Table1 (OfficeName)
    OUTPUT inserted.OfficeID, 3 INTO Table2  (OfficeID, OrgID) 

values
('US5'),
('UK6')
go


0
投票

由于要尝试按表2上的列进行过滤并且在select语句中无法访问,因此尝试对表2进行内部联接,请尝试此操作

 INSERT INTO Table2  (OfficeID) 
 SELECT OfficeID FROM table1 INNER JOIN table2 ON (CLAUSE) WHERE table1.OfficeID in ((7),(8))
 AND   table2.OrgID=3
© www.soinside.com 2019 - 2024. All rights reserved.