To Get The Current Identity Value From A Table

Let’s first create our two simple tables
CREATE TABLE TestOne (id INT identity,SomeDate DATETIME)
CREATE TABLE TestTwo (id INT identity,TestOneID INT,SomeDate DATETIME)

–Let’s insert 4 rows into the table
INSERT TestOne VALUES(GETDATE())
INSERT TestOne VALUES(GETDATE())
INSERT TestOne VALUES(GETDATE())
INSERT TestOne VALUES(GETDATE())

Here are diffrent ways to check for the current value

–1 @@IDENTITY
SELECT @@IDENTITY
–this returns 4

–2 DBCC CHECKIDENT
DBCC CHECKIDENT (TestOne, NORESEED)
after running DBCC CHECKIDENT the message returned is
Checking identity information: current identity value ’4′, current column value ’4′.
DBCC execution completed. If DBCC printed error messages, contact your system administrator.

–3 MAX function
SELECT MAX(id)
FROM TestOne
you can also check with the MAX function but this is not recommended becuase you might get some other identity value that is not yours but from a different user

–4 TOP 1 and ORDER BY DESC
SELECT TOP 1 id
FROM TestOne
ORDER BY id DESC
–The same applies here as for the max function, this is not recommended

–5 IDENT_CURRENT
SELECT IDENT_CURRENT(‘TestOne’)
–IDENT_CURRENT is another way to check

–6 SCOPE_IDENTITY
SELECT SCOPE_IDENTITY()
–This one is very similar to @@IDENTITY with one BIG difference (shown later)


출처 : http://sqlservercodebook.blogspot.com/2008/03/to-get-current-identity-value-from.html

Related posts:

  1. MS SQL Server Tips INF: How to Shrink the SQL Server 7.0 Transaction LogDBCC...
  2. [MS Sql] 여러 레코드를 하나의 문자열로 합치기 특정쿼리의 결과 레코드를 하나의 문자열, 특히 CSV(Comma Separaed Value) 형태로...
  3. Registry Explorer – 드래그 & 드랍 지원 무료 레지스트리 에디터 About Registry Explorer Registry Explorer is a freeware program that...