Home Database Mysql Tutorial T-SQL开发-10.IDENTITY属性使用小结

T-SQL开发-10.IDENTITY属性使用小结

Jun 07, 2016 pm 02:52 PM
use Attributes develop

从SQL Server 2012开始有了Sequence,简单用列如下: CREATESEQUENCETestSeqSTARTWITH1INCREMENTBY1;SELECTNEXTVALUEFORTestSeqASNextValue; 在这之前,表中生成序列号大多都是借助IDENTITY列属性,当然也有一些时候,是在自定义表中,自己维护序列号。 一.

从SQL Server 2012开始有了Sequence,简单用列如下:

CREATE SEQUENCE TestSeq
START WITH 1 INCREMENT BY 1;
SELECT NEXT VALUE FOR TestSeq AS NextValue;
Copy after login

在这之前,表中生成序列号大多都是借助IDENTITY列属性,当然也有一些时候,是在自定义表中,自己维护序列号。

一. 创建IDENTITY列

if OBJECT_ID('test','U') is not null
    drop table test
GO
create table test(id int identity, c1 char(1))
insert test values('a');
insert test values('b');
select * from test
Copy after login

1. 没有指定IDENTITY(seed ,increment),默认就是 IDENTITY(1, 1),效果同如下语句

create table test(id int identity(1,1), c1 char(1))
Copy after login

2. 通过函数或者系统视图,都可以查看是否为IDENTITY列

SELECT COLUMNPROPERTY(OBJECT_ID('test'),'id','IsIdentity') AS is_identity

select object_name(object_id) as table_name, is_identity,* 
from sys.columns 
where object_id=object_id('test') 
--and is_identity=1
Copy after login

3. 重置IDENTITY列的初始值,通常在数据删除/归档后进行

DELETE test
DBCC CHECKIDENT('test', RESEED, 1)
DBCC CHECKIDENT('test', NORESEED)

--TRUNCATE表后会自动重置IDENTITY列
TRUNCATE TABLE test
DBCC CHECKIDENT('test', NORESEED)
Copy after login

二. 获取IDENTITY列值

插入了数据,有时还需要获取刚才生成的序列值另作他用,返回给前端也好,或者插入其他将来需要关联的表。

记得曾经有个面试题:假设当前表IDENTITY列最大值为N,在存储过程中,对这个表插入1行数据,获取到的IDENTITY列值有时小于或者大于N+1,可能是什么原因?

获取IDENTITY列值有三种方式:
(1) IDENT_CURRENT( 'table_name' ) 返回为任何会话和任何作用域中的特定表最后生成的标识值。
(2) @@IDENTITY 返回为当前会话的所有作用域中的任何表最后生成的标识值。
(3) SCOPE_IDENTITY() 返回为当前会话和当前作用域中的任何表最后生成的标识值。

IDENT_CURRENT( 'table_name' ) 针对特定表,是全局的。@@IDENTITY和SCOPE_IDENTITY()针对所有表,区别在于作用域,也就是上下文:
(1) 如果当前INSERT语句上有函数,触发器等(不同作用域的)对象返回的IDENTITY值,那么@@IDENTITY会取所有表上的最后1个,而不是当前表上的;

(2) SCOPE_IDENTITY()会取当前作用域所有表上最后1个IDENTITY值,被调用的函数,触发器已经超出了作用域/上下文。所以在使用INSERT后,接着使用SCOPE_IDENTITY()获取IDENTITY列值,就不会有问题了:

insert test values('z');
select SCOPE_IDENTITY() as curr_value
Copy after login

一个GO语句/批处理,也是一个上下文的分界点,但是SQL语句是顺序执行的,所以一个会话里,只要在INSERT之后用SCOPE_IDENTITY()来获取IDENTITY值是没问题的。

三. 修改IDENTITY列值/属性
1. 对已存在的列增加/删除IDENTITY属性

if OBJECT_ID('t_id') is not null
    drop table t_id
GO
create table t_id(id int,c1 char(1))
insert into t_id
select 1,'a' union all
select 2,'b'

alter table t_id alter column id int identity(1,2)
/*
Msg 156, Level 15, State 1, Line 2
Incorrect syntax near the keyword 'identity'.
*/
Copy after login

直接修改列属性会报错,IDENTITY属性只能伴随着列增加/删除。

(1) 利用中间表
在SSMS界面上设计表(SSMS/Tables/Design),可以直接增加/删除列上的IDENTITY属性,如果生成脚本看看的话(右击编辑框/工具栏/菜单栏),可以发现SSMS是利用了中间表,并非在原表直接修改属性。

表上有约束,索引等对象时,脚本会更加繁杂些。示例如下图:

如果出现如下错误:
Saving changes is not permitted. The changes that you have made require the following tables to be dropped and re-created. You have either made changes to a table that can't be re-created or enabled the option Prevent saving changes that require the table to be re-created.

是因为SSMS里有个选项没设置,SQL Server认为有删除/重建表的脚本不安全,所以默认关闭了,需要手动开启一下,去掉那个勾:

对表上已存在列添加IDENTITY属性,生成的脚本如下:

BEGIN TRANSACTION
SET QUOTED_IDENTIFIER ON
SET ARITHABORT ON
SET NUMERIC_ROUNDABORT OFF
SET CONCAT_NULL_YIELDS_NULL ON
SET ANSI_NULLS ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
COMMIT
BEGIN TRANSACTION
GO
CREATE TABLE dbo.Tmp_t_id
    (
    id int NOT NULL IDENTITY (1, 1),
    c1 char(1) NULL
    )  ON [PRIMARY]
GO
ALTER TABLE dbo.Tmp_t_id SET (LOCK_ESCALATION = TABLE)
GO
SET IDENTITY_INSERT dbo.Tmp_t_id ON
GO
IF EXISTS(SELECT * FROM dbo.t_id)
     EXEC('INSERT INTO dbo.Tmp_t_id (id, c1)
        SELECT id, c1 FROM dbo.t_id WITH (HOLDLOCK TABLOCKX)')
GO
SET IDENTITY_INSERT dbo.Tmp_t_id OFF
GO
DROP TABLE dbo.t_id
GO
EXECUTE sp_rename N'dbo.Tmp_t_id', N't_id', 'OBJECT' 
GO
COMMIT
Copy after login

对表上已存在列删除IDENTITY属性,生成的脚本如下:

BEGIN TRANSACTION
SET QUOTED_IDENTIFIER ON
SET ARITHABORT ON
SET NUMERIC_ROUNDABORT OFF
SET CONCAT_NULL_YIELDS_NULL ON
SET ANSI_NULLS ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
COMMIT
BEGIN TRANSACTION
GO
CREATE TABLE dbo.Tmp_t_id
    (
    id int NOT NULL,
    c1 char(1) NULL
    )  ON [PRIMARY]
GO
ALTER TABLE dbo.Tmp_t_id SET (LOCK_ESCALATION = TABLE)
GO
IF EXISTS(SELECT * FROM dbo.t_id)
     EXEC('INSERT INTO dbo.Tmp_t_id (id, c1)
        SELECT id, c1 FROM dbo.t_id WITH (HOLDLOCK TABLOCKX)')
GO
DROP TABLE dbo.t_id
GO
EXECUTE sp_rename N'dbo.Tmp_t_id', N't_id', 'OBJECT' 
GO
COMMIT
Copy after login

(2) 利用中间列

对表上已存在列删除IDENTITY属性

if OBJECT_ID('t_id') is not null
    drop table t_id
GO
create table t_id(id int identity(1,1),c1 char(1))

insert into t_id
select 'a' union all
select 'b'
select * from t_id
SELECT COLUMNPROPERTY(OBJECT_ID('t_id'),'id','IsIdentity')

--在表上新增一个列,把IDENTITY列值复制过去
alter table t_id add id_new int
GO
update t_id set id_new = id

--删除原来的列,并重命名新增列
alter table t_id drop column id
exec sp_rename 't_id.id_new','id'
select * from t_id
SELECT COLUMNPROPERTY(OBJECT_ID('t_id'),'id','IsIdentity')
Copy after login

对表上已存在列添加IDENTITY属性,用中间列的方式不太可行,因为IDENTITY列不接受UPDATE,新增的IDENTITY列无法直接复制原id的值,还得借助中间表,但如果不需要原来id的值,那么可以:

if OBJECT_ID('t_id') is not null
    drop table t_id
GO
create table t_id(id int,c1 char(1))

insert into t_id
select 1,'a' union all
select 3,'b'
select * from t_id
SELECT COLUMNPROPERTY(OBJECT_ID('t_id'),'id','IsIdentity')

--在表上新增一个IDENTITY列,不复制原来的ID值
alter table t_id add id_new int identity(1,1) not null 

--删除原来的列,并重命名新增列
alter table t_id drop column id
exec sp_rename 't_id.id_new','id'
select * from t_id
SELECT COLUMNPROPERTY(OBJECT_ID('t_id'),'id','IsIdentity')
Copy after login

2. 在IDENTITY列上做增删改操作(DML)
(1) 删除操作没有问题,直接DELETE即可

delete test where id = 2
Copy after login

(2) 如果要显式INSERT某个值,需要开启IDENTITY_INSERT这个SESSION级的选项

set IDENTITY_INSERT test on;
insert test(id,c1) values(3,'c');
set IDENTITY_INSERT test off;
select * from test
Copy after login

(3) 如果要UPDATE IDENTITY列值,无论是否开启IDENTITY_INSERT这个选项都无法更新

set IDENTITY_INSERT test on;
update test set id = 10 where id = 1
set IDENTITY_INSERT test off;
/*
Msg 8102, Level 16, State 1, Line 1
Cannot update identity column 'id'.
*/
Copy after login

非要修改的话,就得借助中间表,在不含IDENTITY属性的中间表里做完UPDATE,然后再把数据导回来。中间表可参考上面的脚本。

3. IDENTITY列属性复制
(1) 直接从单表SELECT INTO table_name,原表其他约束,索引等等都不会被复制,但是IDENTITY属性会被复制。

select * into test2 from test
select * from test2
select columnproperty(OBJECT_ID('test'),'id','IsIdentity')
select columnproperty(OBJECT_ID('test2'),'id','IsIdentity')
Copy after login

(2) 如果有IDENTITY属性的表和其他表JOIN,那么IDENTITY属性不会被复制。

select a.* into test3 
from test a inner join sys.objects b
on a.id = b.object_id
select * from test3
select columnproperty(OBJECT_ID('test3'),'id','IsIdentity')
Copy after login

假如复制表时,不想要IDENTITY属性,正好可以利用一下这个特点,如下:

select a.* into test4
from test a inner join sys.objects b 
on 1=2
Copy after login

(3) 如果用SELECT INTO table_name导数据时,FROM子句有多表关联,且想要保留IDENTITY属性,这时可以用INSERT,并考虑使用TABLOCK提示

if OBJECT_ID('test5','U') is not null
drop table test5
GO

create table test5(id int identity, c1 char(1))
select * from test5
GO

set IDENTITY_INSERT test5 on;
insert into test5 WITH(TABLOCK) (id,c1)
select a.* from test a inner join test2 b on a.id = b.id
set IDENTITY_INSERT test5 off;

select * from test5
select columnproperty(OBJECT_ID('test5'),'id','IsIdentity')
Copy after login

这里使用了WITH(TABLOCK)选项,在SIMPLE或者BULK_LOGGED恢复模式下,SELECT…INTO table_name和INSERT INTO table_name WITH(TABLOCK)都能最小化日志。

4. 借助SWITCH来处理IDENTITY属性,推荐
同样也是利用中间表,上面的几个列子都使用了INSERT,这里使用SWITCH,不再有数据倒来倒去的开销,需要SQL Server 2008及以上版本,能比较有效地同时解决上面的3个问题:
(1) 不能直接对表上现有列增加/删除IDENTITY属性;
(2) 不能直接更新IDENTITY列;
(3) 复制表时,有选择的复制IDENTITY列属性(多表关联,对关联后的表做SWITCH以实现);

CREATE TABLE Temp1
(
ID INT IDENTITY(1,1) PRIMARY KEY,
X VARCHAR(10)
)

INSERT INTO Temp1 
OUTPUT INSERTED.*
SELECT 'Foo' UNION ALL
SELECT 'Bar' UNION ALL
SELECT 'Baz'

CREATE TABLE Temp2
(
ID INT PRIMARY KEY,
X VARCHAR(10)
)

ALTER TABLE Temp1 SWITCH TO Temp2;
SELECT COLUMNPROPERTY(OBJECT_ID('Temp1'),'id','IsIdentity')
SELECT COLUMNPROPERTY(OBJECT_ID('Temp2'),'id','IsIdentity')

INSERT INTO Temp2
OUTPUT INSERTED.*
SELECT 10,'Foo' UNION ALL
SELECT 20,'Bar' UNION ALL
SELECT 5, 'Baz'

UPDATE Temp2 SET ID = ID + 1;

ALTER TABLE Temp2 SWITCH TO Temp1;
SELECT * FROM Temp2
SELECT * FROM Temp1
Copy after login

另外,从SQL Server 2012开始,如果开发时使用了SEQUENCE,这些IDENTITY列的限制就都不会存在了。

四. IDENTITY函数
这是一个函数,使用时和IDENTITY属性的格式很相似,不过两者没什么关系,纯粹因为名字相同,顺便提一下。

select IDENTITY(int,1,1) as id into #t 
from sysobjects

select cast(IDENTITY(int,1,1) as varchar(1000)) as id into #t2 
from sysobjects
-- can not use expression with identity function directly
Copy after login

IDENTITY函数限制比较多,只能用在SELECT INTO语句里,不能结合表达式使用,而且有了ROW_NUMBER(),IDENTITY函数就更显得不好用了。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What software is crystaldiskmark? -How to use crystaldiskmark? What software is crystaldiskmark? -How to use crystaldiskmark? Mar 18, 2024 pm 02:58 PM

CrystalDiskMark is a small HDD benchmark tool for hard drives that quickly measures sequential and random read/write speeds. Next, let the editor introduce CrystalDiskMark to you and how to use crystaldiskmark~ 1. Introduction to CrystalDiskMark CrystalDiskMark is a widely used disk performance testing tool used to evaluate the read and write speed and performance of mechanical hard drives and solid-state drives (SSD). Random I/O performance. It is a free Windows application and provides a user-friendly interface and various test modes to evaluate different aspects of hard drive performance and is widely used in hardware reviews

How to download foobar2000? -How to use foobar2000 How to download foobar2000? -How to use foobar2000 Mar 18, 2024 am 10:58 AM

foobar2000 is a software that can listen to music resources at any time. It brings you all kinds of music with lossless sound quality. The enhanced version of the music player allows you to get a more comprehensive and comfortable music experience. Its design concept is to play the advanced audio on the computer The device is transplanted to mobile phones to provide a more convenient and efficient music playback experience. The interface design is simple, clear and easy to use. It adopts a minimalist design style without too many decorations and cumbersome operations to get started quickly. It also supports a variety of skins and Theme, personalize settings according to your own preferences, and create an exclusive music player that supports the playback of multiple audio formats. It also supports the audio gain function to adjust the volume according to your own hearing conditions to avoid hearing damage caused by excessive volume. Next, let me help you

Four recommended AI-assisted programming tools Four recommended AI-assisted programming tools Apr 22, 2024 pm 05:34 PM

This AI-assisted programming tool has unearthed a large number of useful AI-assisted programming tools in this stage of rapid AI development. AI-assisted programming tools can improve development efficiency, improve code quality, and reduce bug rates. They are important assistants in the modern software development process. Today Dayao will share with you 4 AI-assisted programming tools (and all support C# language). I hope it will be helpful to everyone. https://github.com/YSGStudyHards/DotNetGuide1.GitHubCopilotGitHubCopilot is an AI coding assistant that helps you write code faster and with less effort, so you can focus more on problem solving and collaboration. Git

How to use NetEase Mailbox Master How to use NetEase Mailbox Master Mar 27, 2024 pm 05:32 PM

NetEase Mailbox, as an email address widely used by Chinese netizens, has always won the trust of users with its stable and efficient services. NetEase Mailbox Master is an email software specially created for mobile phone users. It greatly simplifies the process of sending and receiving emails and makes our email processing more convenient. So how to use NetEase Mailbox Master, and what specific functions it has. Below, the editor of this site will give you a detailed introduction, hoping to help you! First, you can search and download the NetEase Mailbox Master app in the mobile app store. Search for "NetEase Mailbox Master" in App Store or Baidu Mobile Assistant, and then follow the prompts to install it. After the download and installation is completed, we open the NetEase email account and log in. The login interface is as shown below

How to use Baidu Netdisk app How to use Baidu Netdisk app Mar 27, 2024 pm 06:46 PM

Cloud storage has become an indispensable part of our daily life and work nowadays. As one of the leading cloud storage services in China, Baidu Netdisk has won the favor of a large number of users with its powerful storage functions, efficient transmission speed and convenient operation experience. And whether you want to back up important files, share information, watch videos online, or listen to music, Baidu Cloud Disk can meet your needs. However, many users may not understand the specific use method of Baidu Netdisk app, so this tutorial will introduce in detail how to use Baidu Netdisk app. Users who are still confused can follow this article to learn more. ! How to use Baidu Cloud Network Disk: 1. Installation First, when downloading and installing Baidu Cloud software, please select the custom installation option.

BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? Apr 26, 2024 am 09:40 AM

MetaMask (also called Little Fox Wallet in Chinese) is a free and well-received encryption wallet software. Currently, BTCC supports binding to the MetaMask wallet. After binding, you can use the MetaMask wallet to quickly log in, store value, buy coins, etc., and you can also get 20 USDT trial bonus for the first time binding. In the BTCCMetaMask wallet tutorial, we will introduce in detail how to register and use MetaMask, and how to bind and use the Little Fox wallet in BTCC. What is MetaMask wallet? With over 30 million users, MetaMask Little Fox Wallet is one of the most popular cryptocurrency wallets today. It is free to use and can be installed on the network as an extension

Teach you how to use the new advanced features of iOS 17.4 'Stolen Device Protection' Teach you how to use the new advanced features of iOS 17.4 'Stolen Device Protection' Mar 10, 2024 pm 04:34 PM

Apple rolled out the iOS 17.4 update on Tuesday, bringing a slew of new features and fixes to iPhones. The update includes new emojis, and EU users will also be able to download them from other app stores. In addition, the update also strengthens the control of iPhone security and introduces more "Stolen Device Protection" setting options to provide users with more choices and protection. "iOS17.3 introduces the "Stolen Device Protection" function for the first time, adding extra security to users' sensitive information. When the user is away from home and other familiar places, this function requires the user to enter biometric information for the first time, and after one hour You must enter information again to access and change certain data, such as changing your Apple ID password or turning off stolen device protection.

Which AI programmer is the best? Explore the potential of Devin, Tongyi Lingma and SWE-agent Which AI programmer is the best? Explore the potential of Devin, Tongyi Lingma and SWE-agent Apr 07, 2024 am 09:10 AM

On March 3, 2022, less than a month after the birth of the world's first AI programmer Devin, the NLP team of Princeton University developed an open source AI programmer SWE-agent. It leverages the GPT-4 model to automatically resolve issues in GitHub repositories. SWE-agent's performance on the SWE-bench test set is similar to Devin, taking an average of 93 seconds and solving 12.29% of the problems. By interacting with a dedicated terminal, SWE-agent can open and search file contents, use automatic syntax checking, edit specific lines, and write and execute tests. (Note: The above content is a slight adjustment of the original content, but the key information in the original text is retained and does not exceed the specified word limit.) SWE-A

See all articles