2013-08-01 81 views
1

將主鍵字段從SMALLINT更改爲INT的最佳方式(低影響/低風險)是什麼?該字段被配置爲使用「身份增量」來自動遞增。在SQL Server中將SMALLINT中的自動遞增主鍵字段更改爲INT

我開始用下面的SQL:

ALTER TABLE category_types ALTER COLUMN id INT NOT NULL; 

但是,它會生成以下錯誤:

ALTER TABLE ALTER COLUMN id failed because one or more objects access this column.

需要說些什麼?我需要放棄鑰匙然後重新創建它們嗎?這會影響自動增量嗎?

注意:該表沒有太多行,因此解決方案的性能並不重要。

+0

嗨,我是在SQL Server中沒有任何專業知識,但是以爲你忘了「身份」在ALTER語句的結束。 – Babblo

回答

1

這是從SQL Server管理工作室輸出,但應該有一定的幫助。它涉及到創建臨時表,然後將現有數據複製到新表中。刪除原始表並重命名臨時表。如果表是空的,它不會這樣做,只能修改原始表。 SET IDENTITY_INSERT [table] ON/OFF允許您在插入時設置標識列。

/* To prevent any potential data loss issues, you should review this script in detail before running it outside the context of the database designer.*/ 
BEGIN TRANSACTION 
SET QUOTED_IDENTIFIER ON 
SET ARITHABORT ON 
SET NUMERIC_ROUNDABORT OFF 
SET CONCAT_NULL_YIELDS_NULL ON 
SET ANSI_NULLS ON 
SET ANSI_PADDING ON 
SET ANSI_WARNINGS ON 
COMMIT 
BEGIN TRANSACTION 
GO 
CREATE TABLE dbo.Tmp_category_types 
    (
    id int NOT NULL IDENTITY (1, 1), 
    ) ON [PRIMARY] 
GO 
ALTER TABLE dbo.Tmp_category_types SET (LOCK_ESCALATION = TABLE) 
GO 
SET IDENTITY_INSERT dbo.Tmp_category_types ON 
GO 
IF EXISTS(SELECT * FROM dbo.category_types) 
    EXEC('INSERT INTO dbo.Tmp_category_types (id, x) 
     SELECT CONVERT(int, id), x FROM dbo.category_types WITH (HOLDLOCK TABLOCKX)') 
GO 
SET IDENTITY_INSERT dbo.Tmp_category_types OFF 
GO 
DROP TABLE dbo.category_types 
GO 
EXECUTE sp_rename N'dbo.Tmp_category_types', N'category_types', 'OBJECT' 
GO 
ALTER TABLE dbo.category_types ADD CONSTRAINT 
    PK_category_types PRIMARY KEY CLUSTERED 
    (
    id 
    ) WITH(STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] 

GO 
COMMIT 
0

除了設置IDENTITY_INSERT爲關閉,你不得不更改數據類型之前取消鏈接關係(主鍵,外鍵)。之後你必須鏈接他們再次。

例如:

-- Change from smallint to int 
SET IDENTITY_INSERT category_types OFF 
alter table category_types drop CONSTRAINT CategoryTypesPK 
alter table category_types alter column id int 
alter table category_types add CONSTRAINT CategoryTypesPK PRIMARY KEY (id) 
SET IDENTITY_INSERT category_types ON 
2

我意識到這是一個古老的職位,但以防萬一有人絆倒它:jciberta作出了回答有輕微的錯誤。應改爲:

- 從SMALLINT改爲int

SET IDENTITY_INSERT category_types ON

ALTER TABLE category_types下降約束CategoryTypes

ALTER TABLE category_types改變列ID INT

alter table category_types add CONSTRAINT CategoryTypesPK PRIMARY KEY(id)

SET IDENTITY_INSERT category_types OFF

相關問題