2

将主键字段从 SMALLINT 更改为 INT 的最佳方法(低影响/低风险)是什么?该字段被配置为使用“身份增量”来自动增量。

我从以下 SQL 开始:

ALTER TABLE category_types ALTER COLUMN id INT NOT NULL;

但是,它会生成以下错误:

ALTER TABLE ALTER COLUMN id 失败,因为一个或多个对象访问此列。

还需要什么?我需要删除密钥然后重新创建它们吗?这会影响自动增量吗?

注意:该表没有太多行,因此解决方案的性能并不重要。

4

3 回答 3

2

我意识到这是一篇旧帖子,但以防万一有人偶然发现它:jciberta 给出了一个带有轻微错误的答案。它应该是:

-- 从 smallint 更改为 int

SET IDENTITY_INSERT category_types ON

ALTER TABLE category_types DROP CONSTRAINT CategoryTypes

ALTER TABLE category_types ALTER COLUMN id INT

ALTER TABLE category_types ADD CONSTRAINT CategoryTypesPK PRIMARY KEY (id)

SET IDENTITY_INSERT category_types OFF
于 2016-08-27T15:56:42.617 回答
1

这是 sql server management studio 的输出,但应该会有所帮助。它涉及创建一个临时表,然后将现有数据复制到新表中。删除原始表并重命名临时表。如果表是空的,它就不会这样做,只能修改原始表。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
于 2013-08-02T03:26:43.360 回答
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
于 2016-03-03T17:03:43.840 回答