SQL:插入期间的自动递增值

时间:2012-01-04 18:59:41

标签: sql-server-2008 insert auto-increment

我有一个现有的表,由于某种原因,设计者决定通过将最后使用的值存储在单独的表中来手动控制主键值(更改表以使用Identity现在不是一个选项)。

我现在需要对此表进行大量更新,如下所示:

DECLARE @NeedFieldID int
SET @NeedFieldID = 62034

    INSERT INTO T_L_NeedField (NeedID, NeedFieldID, FieldName, Sequence, DisplayAs, FieldPrompt, DataType, ValidOptions, IsRequiredForSale)
    (
        SELECT 
            DISTINCT n.NeedID, 
                @NeedFieldID + 1,           
            'DetailedOutcome',
            999,
            'Detailed Outcome',
            'Select appropriate reason for a No Sale outcome',
            'T',
            'Pricing, Appointment Date / Time Not Available, Will Call Back, Declined', 
            0
        FROM  T_L_Need n
            INNER JOIN T_L_NeedField nf
                ON n.NeedID = nf.NeedID
        WHERE (n.Need LIKE 'Schedule%' AND n.Disabled = 0)
    )

显然'@NeedFieldID + 1'不起作用(只是用它来显示我想做的事)。当SQL插入每个不同NeedId的值时,如何增加@NeedFieldID?我正在使用SQL Server 2008。

1 个答案:

答案 0 :(得分:5)

您想要row_number()

DECLARE @NeedFieldID int
SET @NeedFieldID = 62034

    INSERT INTO T_L_NeedField (NeedID, NeedFieldID, FieldName, Sequence, DisplayAs, FieldPrompt, DataType, ValidOptions, IsRequiredForSale)
    (
        SELECT 
            DISTINCT n.NeedID, 
                @NeedFieldID + row_number() over (order by n.NeedID),           
            'DetailedOutcome',
            999,
            'Detailed Outcome',
            'Select appropriate reason for a No Sale outcome',
            'T',
            'Pricing, Appointment Date / Time Not Available, Will Call Back, Declined', 
            0
        FROM  T_L_Need n
            INNER JOIN T_L_NeedField nf
                ON n.NeedID = nf.NeedID
        WHERE (n.Need LIKE 'Schedule%' AND n.Disabled = 0)
    )

但是,最好的办法是让NeedFieldID成为一个标识列,让SQL Server为您完成工作。