SQL SERVER 中identity

SQL SERVER 中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')



在SQL Server数据库中为标识(IDENTITY)列插入显式值:
SET IDENTITY_Insert [TableName] ON
如:

Mssql代码 复制代码 收藏代码
  1. SET IDENTITY_Insert member ON    
  2. insert member(id,username) values(1,'admin')    
  3. SET IDENTITY_Insert member OFF   
SET IDENTITY_Insert member ON 
insert member(id,username) values(1,'admin') 
SET IDENTITY_Insert member OFF 


插入显式值后并不影响原来的identity值的大小。

原文地址:https://www.cnblogs.com/dekevin/p/2491906.html