admin

在SQL Server的INSERT INTO SELECT查询中的字段中添加增量数字

sql

我有一个INSERT INTOSELECT查询。在SELECT语句中,我有一个子查询,我想在其中添加一个递增数字。如果我的SELECT查询仅返回一条记录,则此查询将正常工作;但是,如果返回多行,则在所有这些行的增量字段中插入相同的数字。有什么方法可以限制它每次添加一个增量数字?

INSERT INTO PM_Ingrediants_Arrangements_Temp 
(AdminID,ArrangementID,IngrediantID,Sequence)
(SELECT 
     @AdminID, @ArrangementID, PM_Ingrediants.ID, 
     (SELECT 
          MAX(ISNULL(sequence,0)) + 1 
      FROM
          PM_Ingrediants_Arrangements_Temp 
      WHERE 
          ArrangementID=@ArrangementID)
FROM 
    PM_Ingrediants 
WHERE 
    PM_Ingrediants.ID IN (SELECT 
                              ID 
                          FROM 
                              GetIDsTableFromIDsList(@IngrediantsIDs))
)

阅读 224

收藏
2021-05-10

共1个答案

admin

您可以使用此row_number()功能。

INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
    SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
            row_number() over (order by (select NULL))
    FROM PM_Ingrediants 
    WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
                             )

如果要从表中已有的最大值开始,请执行以下操作:

INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
    SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
           coalesce(const.maxs, 0) + row_number() over (order by (select NULL))
    FROM PM_Ingrediants cross join
         (select max(sequence) as maxs from PM_Ingrediants_Arrangement_Temp) const
    WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
                             )

最后,您可以使该sequence列成为自动递增的身份列。这样就无需每次都增加它:

create table PM_Ingrediants_Arrangement_Temp ( . . .
    sequence int identity(1, 1) -- and might consider making this a primary key too
    . . .
)
2021-05-10