46

我有一个INSERT INTO SELECT查询。在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))
)
4

1 回答 1

79

您可以为此使用该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
    . . .
)
于 2013-06-01T06:19:34.137 回答