identity_insert

时间:2025-12-19 08:40:52编辑:莆田seo君

仅当使用了列列表并且 IDENTITY_INSERT 为 ON 时,才能为表'stulnfo'中的标识列指定显式值。

操作步骤:首先建立一个有标识列的表:CREATE TABLE products (id int IDENTITY PRIMARY KEY, product varchar(40))尝试在表中做以下操作:INSERT INTO products (id, product) VALUES(3, 'garden shovel')结果会导致错误:“当 IDENTITY_INSERT 设置为 OFF 时,不能向表 'products' 中的标识列插入显式值。”改用:SET IDENTITY_INSERT products ONINSERT INTO products (id, product) VALUES(1, 'garden shovel')返回正确。建立另外一个表products2,尝试相同插入操作:CREATE TABLE products2 (id int IDENTITY PRIMARY KEY, product varchar(40))然后执行:SET IDENTITY_INSERT products2 ONINSERT INTO products2 (id, product) VALUES(1, 'garden shovel')导致错误:“表 'material.dbo.products' 的 IDENTITY_INSERT 已经为 ON。无法对表 'products2' 执行 SET 操作。”改为执行:SET IDENTITY_INSERT products OFFSET IDENTITY_INSERT products2 ONINSERT INTO products2 (id, product) VALUES(2, 'garden shovel')执行通过。尝试以下操作:SET IDENTITY_INSERT products2 ONINSERT INTO products2 SELECT * FROM products导致错误:“仅当使用了列的列表,并且 IDENTITY_INSERT 为 ON 时,才能在表 'products2' 中为标识列指定显式值。”改为:SET IDENTITY_INSERT products2 ONINSERT INTO products2 (id, product) SELECT * FROM products执行通过。

数据库中关键字identity如何使用?

在数据库中, 常用的一个流水编号通常会使用 identity 栏位来进行设置, 这种编号的好处是一定不会重覆, 而且一定是唯一的, 这对table中的唯一值特性很重要, 通常用来做客户编号, 订单编号等功能, 以下介绍关于此种栏位常用方式及相关技术.
CREATE TABLE products (id int IDENTITY PRIMARY KEY, product varchar(40))

取得identity值:
因为 identity 特性, 所以在 insert into 该 table 时, 不能指定该 identity 栏位值, 仅能指定其他栏位值, 而 identity 由资料库维护, 所以一般要在 insert 后取得该 identity 栏位值, 则通常使用下面方式:

利用全局变量 @@identity 来取得最后影响的 insert 后产生的 identity 值, 如此一来便能方便地使用 identity 栏位.

若要启用识别插入(identity insert)时, 也就是如空缺号要指定 identity 栏位值时, 或者是处理资料表整理或备出时, 会用到的方式:
set identity_insert products on
insert into products (id, product)values(12, 'screwdriver')
要注意的地方是可以 insert 空缺号, 也可以加至最后, 但系统会自动更新 identity 至最大值, 要注意一旦启用 identity_insert 时, 就一定要给定 identity 值, 另外并不能 update 该 identity 栏位值, 也就是说 identity_insert 该 identity 栏位仅 for insert, 不能 update.

查询目前 identity 值:
有时我们需要查询目前 table 中该 identity 栏位最大值是多少时, 可以利用 dbcc 指令, 如下:
dbcc checkident('product', NORESEED)
可以获得目前最大值的结果.

重设目前最大 identity 值:
一样利用 dbcc 指令, 如下:
dbcc checkident('product',RESEED,100)
如此一来, 便能将目前的最大 identity 值指向100, 当然若故意设比目前最大值小时, 系统仍会接受, 但若 identity 遇上重覆资料时(如将 identity 设为 primary key时), 将会发生重大问题, 该 table 变成无法 insert 资料, 因为会发生 primary key violation, 解决方法当然就是将目前的 identity 修复, 直接使用
dbcc checkident('products', RESEED)

dbcc checkident('products')


上一篇:巴西烤肉自助餐

下一篇:没有了