SQL SERVER 中identity
SQL SERVER 中identity用法:?
在數(shù)據(jù)庫中, 常用的一個(gè)流水編號(hào)通常會(huì)使用 identity 欄位來進(jìn)行設(shè)置, 這種編號(hào)的好處是一定不會(huì)重覆, 而且一定是唯一的, 這對(duì)table中的唯一值特性很重要, 通常用來做客戶編號(hào), 訂單編號(hào)等功能, 以下介紹關(guān)于此種欄位常用方式及相關(guān)技術(shù).
CREATE TABLE products (id int IDENTITY PRIMARY KEY, product varchar(40))
取得identity值:
因?yàn)?identity 特性, 所以在 insert into 該 table 時(shí), 不能指定該 identity 欄位值, 僅能指定其他欄位值, 而 identity 由資料庫維護(hù), 所以一般要在 insert 后取得該 identity 欄位值, 則通常使用下面方式:
利用全局變量 @@identity 來取得最后影響的 insert 后產(chǎn)生的 identity 值, 如此一來便能方便地使用 identity 欄位.
若要啟用識(shí)別插入(identity insert)時(shí), 也就是如空缺號(hào)要指定 identity 欄位值時(shí), 或者是處理資料表整理或備出時(shí), 會(huì)用到的方式:
set identity_insert products on
insert into products (id, product)values(12, 'screwdriver')
要注意的地方是可以 insert 空缺號(hào), 也可以加至最后, 但係統(tǒng)會(huì)自動(dòng)更新 identity 至最大值, 要注意一旦啟用 identity_insert 時(shí), 就一定要給定 identity 值, 另外并不能 update 該 identity 欄位值, 也就是說 identity_insert 該 identity 欄位僅 for insert, 不能 update.
查詢目前 identity 值:
有時(shí)我們需要查詢目前 table 中該 identity 欄位最大值是多少時(shí), 可以利用 dbcc 指令, 如下:
dbcc checkident('product', NORESEED)
可以獲得目前最大值的結(jié)果.
重設(shè)目前最大 identity 值:
一樣利用 dbcc 指令, 如下:
dbcc checkident('product',RESEED,100)
如此一來, 便能將目前的最大 identity 值指向100, 當(dāng)然若故意設(shè)比目前最大值小時(shí), 係統(tǒng)仍會(huì)接受, 但若 identity 遇上重覆資料時(shí)(如將 identity 設(shè)為 primary key時(shí)), 將會(huì)發(fā)生重大問題, 該 table 變成無法 insert 資料, 因?yàn)闀?huì)發(fā)生 primary key violation, 解決方法當(dāng)然就是將目前的 identity 修復(fù), 直接使用
dbcc checkident('products', RESEED)
或
dbcc checkident('products')
在SQL Server數(shù)據(jù)庫中為標(biāo)識(shí)(IDENTITY)列插入顯式值:
SET IDENTITY_Insert [TableName] ON
如:
插入顯式值后并不影響原來的identity值的大小。
轉(zhuǎn)載于:https://www.cnblogs.com/Derek-He/archive/2013/03/26/2982365.html
總結(jié)
以上是生活随笔為你收集整理的SQL SERVER 中identity的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: codevs1040 统计单词个数
- 下一篇: MySQL中varchar,varbin