SQL Server:ID为<的重复行0并获取新创建的ID

时间:2013-05-10 18:23:45

标签: sql tsql sql-server-2008-r2

我已从SQL Server 2008 R2中的MS Access恢复了一个表。

MS Access中的旧表使用的是复制类型为整数的PK(因此存在负值)

将表导入SQL Server 2008 R2后,我更改了整数标识列的PK。

我现在要做的是制作一个脚本,它将带有负PK的所有行,用新的PK(自动编号)复制该行并更改其他表FK的值(负值)新创建的PK(自动编号)。然后,最后,删除刚重复的OLD行。

感谢您的帮助

这是表格的一个例子:

CREATE TABLE [dbo].[TESTCopy](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Field1] [nchar](10) NOT NULL,
[Field2] [nchar](10) NOT NULL,
[Field3] [nchar](10) NOT NULL,
CONSTRAINT [PK_TESTCopy] PRIMARY KEY CLUSTERED 
(
[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

1 个答案:

答案 0 :(得分:0)

您可以使用游标执行此操作,但他们对性能和其他问题不满意:

DECLARE @CurrentID INT
DECLARE @NewID INT
DECLARE @Field1 NCHAR(10)
DECLARE @Field2 NCHAR(10)
DECLARE @Field3 NCHAR(10)

DECLARE curUpdateKeys CURSOR FOR
                    SELECT ID, Field1, Field2, Field3
                    FROM dbo.TESTCopy
                    WHERE ID < 0

OPEN curUpdateKeys

FETCH NEXT FROM curUpdateKeys INTO @CurrentID, @Field1, @Field2, @Field3

WHILE @@FETCH_STATUS = 0
BEGIN

-- Add new record
    INSERT INTO dbo.TESTCopy
        (Field1, Field2, Field3)
    VALUES 
        (@Field1, @Field2, @Field3)
-- Capture new record ID
    SET @NewID = SCOPE_IDENTITY()


-- Update your foreign keyed tables with new record ID
-- Repeat for every table
    UPDATE dbo.FK_TABLES
        SET fkTESTCopyID = @NewID
    WHERE dbo.FK_TABLES.fkTESTCopyID = @CurrentID

-- Remove original row with negative record ID ID
    DELETE
    FROM dbo.TESTCopy
    WHERE ID = @CurrentID

    FETCH NEXT FROM curUpdateKeys INTO @CurrentID, @Field1, @Field2, @Field3
END

CLOSE curUpdateKeys
DEALLOCATE curUpdateKeys