Identity Column in SQL Server

If a column is marked as an identity column, then the values for this column are automatically generated, when you insert a new row into the table. The following, create table statement marks PersonId as an identity column with seed = 1 and Identity Increment = 1. Seed and Increment values are optional. If you don't specify the identity and seed they both default to 1.

Create Table tblPerson
(
PersonId int Identity(1,1) Primary Key,
Name nvarchar(20)
)

In the following 2 insert statements, we only supply values for Name column and not for PersonId column. 

Insert into tblPerson values ('Sam')
Insert into tblPerson values ('Sara')

If you select all the rows from tblPerson table, you will see that, 'Sam' and 'Sara' rows have got 1 and 2 as PersonId.

Now, if I try to execute the following query, I get an error stating - An explicit value for the identity column in table 'tblPerson' can only be specified when a column list is used and IDENTITY_INSERT is ON.

Insert into tblPerson values (1,'Todd')

So if you mark a column as an Identity column, you dont have to explicitly supply a value for that column when you insert a new row. The value is automatically calculated and provided by SQL server. So, to insert a row into tblPerson table, just provide value for Name column.

Insert into tblPerson values ('Todd')

Delete the row, that you have just inserted and insert another row. You see that the value for PersonId is 2. Now if you insert another row, PersonId is 3. A record with PersonId = 1, does not exist, and I want to fill this gap. To do this, we should be able to explicitly supply the value for identity column. To explicitly supply a value for identity column

1. First turn on identity insert - SET Identity_Insert tblPerson ON
2. In the insert query specify the column list

Insert into tblPerson(PersonId, Name) values(2, 'John')

As long as the Identity_Insert is turned on for a table, you need to explicitly provide the value for that column. If you don't provide the value, you get an error - Explicit value must be specified for identity column in table 'tblPerson1' either when IDENTITY_INSERT is set to ON or when a replication user is inserting into a NOT FOR REPLICATION identity column.

After, you have the gaps in the identity column filled, and if you wish SQL server to calculate the value, turn off Identity_Insert.
SET Identity_Insert tblPerson OFF

If you have deleted all the rows in a table, and you want to reset the identity column value, use DBCC CHECKIDENT command. This command will reset PersonId identity column.
DBCC CHECKIDENT(tblPerson, RESEED, 0)

How to get the last generated identity column value in SQL Server

There are several ways in sql server, to retrieve the last identity value that is generated. The most common way is to use SCOPE_IDENTITY() built in function. 
Apart, from using SCOPE_IDENTITY(), you also have @@IDENTITY and IDENT_CURRENT('TableName') function.

Example queries for getting the last generated identity value

Select SCOPE_IDENTITY()
Select @@IDENTITY
Select IDENT_CURRENT('tblPerson')

Let's now understand the difference between, these 3 approaches.

SCOPE_IDENTITY() returns the last identity value that is created in the same session (Connection) and in the same scope (in the same Stored procedure, function, trigger). Let's say, I have 2 tables tblPerson1 and tblPerson2, and I have a trigger on tblPerson1 table, which will insert a record into tblPerson2 table. Now, when you insert a record into tblPerson1 table,  SCOPE_IDENTITY() returns the idetentity value that is generated in tblPerson1 table, where as @@IDENTITY returns, the value that is generated in tblPerson2 table. So, @@IDENTITY returns the last identity value that is created in the same session without any consideration to the scope. IDENT_CURRENT('tblPerson') returns the last identity value created for a specific table across any session and any scope.

In brief:
SCOPE_IDENTITY() - returns the last identity value that is created in the same session and in the same scope.
@@IDENTITY - returns the last identity value that is created in the same session and across any scope.
IDENT_CURRENT('TableName') - returns the last identity value that is created for a specific table across any session and any scope.

Part 4 Identity Column in SQL Server的更多相关文章

  1. Microsoft SQL Server Version List [sqlserver 7.0-------sql server 2016]

    http://sqlserverbuilds.blogspot.jp/   What version of SQL Server do I have? This unofficial build ch ...

  2. Microsoft SQL Server Version List(SQL Server 版本)

    原帖地址 What version of SQL Server do I have? This unofficial build chart lists all of the known Servic ...

  3. 如何转换SQL Server 2008数据库到SQL Server 2005

        背景介绍: 公司一套系统使用的是SQL SERVER 2008数据库,突然一天收到邮件,需要将这套系统部署到各个不同地方(海外)的工厂,需要在各个工厂部署该数据库,等我将准备工作做好,整理文档 ...

  4. SQL Server解惑——标识列的限制和跳号现象

      1:每个表只能创建一个标识列. 如下测试所示,如果表中有一个标识列,新增一个标识列就会遇到错误"Multiple identity columns specified for table ...

  5. 数据库开发基础-SQl Server 聚合函数、数学函数、字符串函数、时间日期函数

    SQL 拥有很多可用于计数和计算的内建函数. 函数的语法 内建 SQL 函数的语法是: SELECT function(列) FROM 表 函数的类型 在 SQL 中,基本的函数类型和种类有若干种.函 ...

  6. oracle 、mysql、 sql server使用记录

    oracle .mysql. sql server使用记录 mysql常用命令: mysqld --启动mysql数据库 show databases; -- 查看数据库 use database; ...

  7. Reset Identity Column Value in SQL Server (Identity Reset)

    前言:今天在群里看到有人在问SQL Server自增值重置问题(sqlserver identiy column value reset ) 闲话少说,直接上代码: 正文: --create tabl ...

  8. sql server alter column identity

    上网找 alter column identity 语句,将表中的一个字段调整成自动新增.发现没有. 跟踪了一下sql server 执行这一动作的语句,发现是新建了新表,将字段修改成自动新增,然后将 ...

  9. SQL Server 合并复制遇到identity range check报错的解决

        最近帮一个客户搭建跨洋的合并复制,由于数据库非常大,跨洋网络条件不稳定,因此只能通过备份初始化,在初始化完成后向海外订阅端插入数据时发现报出如下错误: Msg 548, Level 16, S ...

随机推荐

  1. Delphi ThreadPool 线程池(Delphi2009以上版本适用)

    http://blog.sina.com.cn/s/blog_6250a9df0101kref.html 在网上查找Delphi线程池,结果发现寥寥无几. 看了半天源代码,弄得一头雾水,觉得不容易理解 ...

  2. C++ Bit Fields

    http://msdn.microsoft.com/en-us/library/ewwyfdbe%28v=vs.71%29.aspx Note An unnamed bit field of widt ...

  3. SCCM符合性设置

    符合性设置--可以针对注册表值.脚本.文件系统.补丁更新情况进行符合性检查,除了在报表中查看结果外,还可以在CCM客户端 的 配置 中查看符合性评估结果,适合排错1.配置项目---新建针对 注册表值. ...

  4. c++训练营--重载

    // demo1.cpp : 定义控制台应用程序的入口点. //通过此例程了解重载 #include "stdafx.h" #include <iostream> us ...

  5. jquery 之validate 笔记

    默认分类 2010-04-04 20:35:01 阅读123 评论0 字号:大中小 jquery.validate是jquery旗下的一个验证框架,借助jquery的优势,我们可以迅速验证一些常见的输 ...

  6. SGU 538. Emoticons 水题

    538. Emoticons 题目连接: http://acm.sgu.ru/problem.php?contest=0&problem=538 Description A berland n ...

  7. Linux内核探讨-- 第七章

    本文是个人分析<Linux内核设计与实现>而写的总结,欢迎转载,请注明出处: http://blog.csdn.net/dlutbrucezhang/article/details/136 ...

  8. 次表面散射(SubSurface Scattering) Shader 【转】

    原文 http://www.azure.com.cn/article.asp?id=231 用深度值近似模拟物体的厚度,厚度越小处透光越多. varying vec4 position;varying ...

  9. MySQL执行SHOW STATUS查询服务器状态状态之Handler_read_* 详解

    在MySQL里,我们一般使用SHOW STATUS查询服务器状态,语法一般来说如下: SHOW [GLOBAL | SESSION] STATUS [LIKE ‘pattern’ | WHERE ex ...

  10. 如何使用strace+pstack利器分析程序性能

    http://www.cnblogs.com/bangerlee/archive/2012/04/30/2476190.html