使用For循环插入+1 id

时间:2017-09-29 14:28:19

标签: sql loops for-loop insert

我有两张桌子:

表1:

InspectionID   ID   Comment
1              1    Text1
1              2    Text2 
2              1    Text1   
3              1    Text1
3              2    Text2

表2:

InspectionID   ID   Comment
1              1    TextA
2              1    TextA 
3              1    TextA  
4              1    TextA
5              1    TextA

我需要一个FOR LOOP公式,它将表2插入到表1中,但是根据InspectionID将Table2的ID更新为下一个按时间顺序排列的编号。我希望我的结果看起来像这样:

表1(完成):

InspectionID   ID   Comment
1              1    Text1
1              2    Text2 
1              3    TextA
2              1    Text1
2              2    TextA
3              1    Text1
3              2    Text2
3              3    TextA

任何人都可以帮我解决这个问题,我从未做过很好的循环。

谢谢!

1 个答案:

答案 0 :(得分:0)

如果您的DBMS支持窗口函数,您可以使用它们 - 无需循环。它们是一种非常强大的工具,适用于各种情况。

SQL Server 2008及更高版本:

INSERT INTO dbo.Table1
(InspectionID, ID, Comment)
SELECT t1.InspectionID
      ,MAX(t1.ID) + ROW_NUMBER() OVER (PARTITION BY t1.InspectionID ORDER BY t2.Comment)
      ,t2.Comment
FROM dbo.Table1 t1
     INNER JOIN dbo.Table2 t2 ON t1.InspectionID = t2.InspectionID
GROUP BY t1.InspectionID
        ,t2.Comment

概念证明(在表2中增加了一行):

CREATE TABLE dbo.Table1
(
    InspectionID INT
   ,ID INT
   ,Comment NVARCHAR(100)
)

CREATE TABLE dbo.Table2
(
    InspectionID INT
   ,ID INT
   ,Comment NVARCHAR(100)
)

INSERT INTO dbo.Table1
VALUES (1,1,'Text1')
      ,(1,2,'Text2')
      ,(2,1,'Text1')
      ,(3,1,'Text1')
      ,(3,2,'Text2')

INSERT INTO dbo.Table2
VALUES (1,1,'TextA')
      ,(2,1,'TextA')
      ,(3,1,'TextA')
      ,(3,1,'TextB')
      ,(4,1,'TextA')
      ,(5,1,'TextA')

INSERT INTO dbo.Table1
(InspectionID, ID, Comment)
SELECT t1.InspectionID
      ,MAX(t1.ID) + ROW_NUMBER() OVER (PARTITION BY t1.InspectionID ORDER BY t2.Comment)
      ,t2.Comment
FROM dbo.Table1 t1
     INNER JOIN dbo.Table2 t2 ON t1.InspectionID = t2.InspectionID
GROUP BY t1.InspectionID
        ,t2.Comment

SELECT *
FROM dbo.Table1
ORDER BY InspectionID, ID

结果:

InspectionID    ID  Comment
1               1   Text1
1               2   Text2
1               3   TextA
2               1   Text1
2               2   TextA
3               1   Text1
3               2   Text2
3               3   TextA
3               4   TextB