Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/sql-server-2008/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server 2008 SQL:插入过程中的自动增量值_Sql Server 2008_Insert_Auto Increment - Fatal编程技术网

Sql server 2008 SQL:插入过程中的自动增量值

Sql server 2008 SQL:插入过程中的自动增量值,sql-server-2008,insert,auto-increment,Sql Server 2008,Insert,Auto Increment,我有一个现有的表,出于某种原因,设计者决定通过将上次使用的值存储在单独的表中来手动控制主键值(将表更改为使用标识现在不是一个选项) 我现在需要对该表进行大规模更新,如下所示: DECLARE @NeedFieldID int SET @NeedFieldID = 62034 INSERT INTO T_L_NeedField (NeedID, NeedFieldID, FieldName, Sequence, DisplayAs, FieldPrompt, DataType, Vali

我有一个现有的表,出于某种原因,设计者决定通过将上次使用的值存储在单独的表中来手动控制主键值(将表更改为使用标识现在不是一个选项)

我现在需要对该表进行大规模更新,如下所示:

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。

您需要:

但是,最好的办法是将
NeedFieldID
设置为一个标识列,然后让SQL Server为您完成这项工作

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)
    )