日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 运维知识 > 数据库 >内容正文

数据库

SQL SERVER 中identity

發(fā)布時(shí)間:2023/12/10 数据库 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 SQL SERVER 中identity 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

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
如:

Mssql代碼 ?
  • SET?IDENTITY_Insert?member?ON? ??
  • insert?member(id,username)?values(1,'admin')? ??
  • SET?IDENTITY_Insert?member?OFF???
  • SET IDENTITY_Insert member ON insert member(id,username) values(1,'admin') SET IDENTITY_Insert member OFF


    插入顯式值后并不影響原來的identity值的大小。

    轉(zhuǎn)載于:https://www.cnblogs.com/Derek-He/archive/2013/03/26/2982365.html

    總結(jié)

    以上是生活随笔為你收集整理的SQL SERVER 中identity的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。