SQL Server:INSERT INTO SELECT MAX

时间:2015-05-30 10:03:26

标签: sql sql-server

我想从另一个表中插入多行。问题是我想在插入之前得到Max + 1。请注意,我知道我应该使用Identify等...但是,我有这种跨节点的离线数据库同步的复杂场景......

INSERT INTO Purchase_Deliveries_Items    
  (ID,Item_ID)
SELECT 
    (SELECT 
        MAX(ID)+1  -- same MAX ID for all (the problem)
    FROM 
        Purchase_Deliveries_Items), 
    Item_ID,
FROM 
    Purchase_Orders_Items
WHERE 
    PurchaseOrder_ID = 1

2 个答案:

答案 0 :(得分:1)

您可以在ROW_NUMBER

的帮助下,根据最大现有ID获取新内容
%{DOCUMENT_ROOT}_misc

答案 1 :(得分:0)

好像你想要做一种顺序,使用ROW_NUMBER:

INSERT INTO Purchase_Deliveries_Items (
    ID,
    Item_ID
)
SELECT  
    ROW_NUMBER() OVER (
        ORDER BY
            Item_ID
    ) + (SELECT MAX(ID)
            FROM Purchase_Deliveries_Items) newID,
    Item_ID,
FROM Purchase_Orders_Items
WHERE 
    PurchaseOrder_ID = 1