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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > 数据库 >内容正文

数据库

SQL SERVER 中identity

發布時間:2023/12/10 数据库 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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代碼 ?
  • 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值的大小。

    轉載于:https://www.cnblogs.com/Derek-He/archive/2013/03/26/2982365.html

    總結

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

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。