我有一个表,主键已经设置到该表,现在我希望该列是自动增量。表有很多记录。可能吗?或哪一个是最快的方式?
答案 0 :(得分:0)
我认为您必须为此付出一些努力,因为您无法在现有列上创建标识列。但是,您可能有一个解决方法,例如首先尝试添加具有标识字段的新列:
ALTER TABLE dbo.Table_name
ADD ID INT IDENTITY
然后将您的ID设为主键:
ALTER TABLE dbo.Table_name
ADD CONSTRAINT PK_YourTable
PRIMARY KEY(ID)
是的,你必须在执行上述步骤之前删除旧的依赖项:
ALTER TABLE Table_name
DROP CONSTRAINT PK_Table1_Col1
修改: - 强>
来自source:
我们可以使用 ALTER TABLE ... SWITCH 来解决这个问题,只修改元数据。有关使用下面介绍的SWITCH方法的限制,请参阅联机丛书。即使是最大的表格,这个过程也几乎是即时的。
USE tempdb;
GO
-- A table with an identity column
CREATE TABLE dbo.Source (row_id INTEGER IDENTITY PRIMARY KEY NOT NULL, data SQL_VARIANT NULL);
GO
-- Some sample data
INSERT dbo.Source (data)
VALUES (CONVERT(SQL_VARIANT, 4)),
(CONVERT(SQL_VARIANT, 'X')),
(CONVERT(SQL_VARIANT, {d '2009-11-07'})),
(CONVERT(SQL_VARIANT, N'áéíóú'));
GO
-- Remove the identity property
BEGIN TRY;
-- All or nothing
BEGIN TRANSACTION;
-- A table with the same structure as the one with the identity column,
-- but without the identity property
CREATE TABLE dbo.Destination (row_id INTEGER PRIMARY KEY NOT NULL, data SQL_VARIANT NULL);
-- Metadata switch
ALTER TABLE dbo.Source SWITCH TO dbo.Destination;
-- Drop the old object, which now contains no data
DROP TABLE dbo.Source;
-- Rename the new object to make it look like the old one
EXECUTE sp_rename N'dbo.Destination', N'Source', 'OBJECT';
-- Success
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
-- Bugger!
IF XACT_STATE() <> 0 ROLLBACK TRANSACTION;
PRINT ERROR_MESSAGE();
END CATCH;
GO
-- Test the the identity property has indeed gone
INSERT dbo.Source (row_id, data)
VALUES (5, CONVERT(SQL_VARIANT, N'This works!'))
SELECT row_id,
data
FROM dbo.Source;
GO
-- Tidy up
DROP TABLE dbo.Source;