我有SQL Server数据库,我想更改标识列,因为它已启动

更改或重置此列的最佳方式是什么?

推荐答案

You can not update identity column.

与使用update语句处理其他列不同,SQL Server不允许更新标识列.

尽管有一些替代方案可以实现类似的需求.

  • When Identity column value needs to be updated for new records

使用DBCC CHECKIDENT which checks the current identity value for the table and if it's needed, changes the identity value.

DBCC CHECKIDENT('tableName', RESEED, NEW_RESEED_VALUE)
  • When Identity column value needs to be updated for existing records

使用IDENTITY_INSERT which allows explicit values to be inserted into the identity column of a table.

SET IDENTITY_INSERT YourTable {ON|OFF}

Example:

-- Set Identity insert on so that value can be inserted into this column
SET IDENTITY_INSERT YourTable ON
GO
-- Insert the record which you want to update with new value in the identity column
INSERT INTO YourTable(IdentityCol, otherCol) VALUES(13,'myValue')
GO
-- Delete the old row of which you have inserted a copy (above) (make sure about FK's)
DELETE FROM YourTable WHERE ID=3
GO
--Now set the idenetity_insert OFF to back to the previous track
SET IDENTITY_INSERT YourTable OFF

Sql相关问答推荐

为主表中的每一行查找N个最新行

postgresql插入json不工作

获取每5分钟时间间隔的总和

通过 Select 值的顺序进行排序ClickHouse

删除MariaDB数据库中的JSON数据

如何在snowflake中进行SQL的反向填充

Oracle SQL根据列中的条件 Select 最大记录数

在SQL Server中设置关联对象的有效JSON格式

重用传递给 node 的参数-postgres upsert查询

IF NOT EXISTS子查询的性能瓶颈

当active=1时,是否可以创建id为的唯一索引?

SQL中相同表内的VLOOKUP等价

在 PostgreSQL 中使用 ltree 列进行累积

使用临时表判断记录是否存在 - 如果存在则执行相同的操作

在 Oracle 21c 中透视文本值

如何从postgresql中的项目映射(关联数组)设置值?

我们可以使用连接改进包含多个子查询的查询吗

Postgres存在限制问题「小值」

标量子查询中的窗口函数不起作用

为什么 get_json_object() 无法从存储在 Hive SQL 表中的 JSON 中提取值?