@@identity, SCOPE_IDENTITY, IDENT_CURRENT 비교

  • Post author:
  • Post category:
  • Post comments:2 Comments
  • Post last modified:August 28, 2005

내가 MSSQL 사용자 모임에 썼던 글.

예전의 ‘택’님께서 올리신 글에도 나온 내용이지만, 온라인 북에 좀더 자세한 설명과 예제가 있길래 가져왔습니다.

IDENT_CURRENT는 Microsoft® SQL Server™ 2000 ID 함수인 SCOPE_IDENTITY와 @@IDENTITY와 유사합니다. 이 세 함수 모두 최근에 생성된 ID 값을 반환합니다. 그러나 각 함수에서 ‘최근’이 정의되는 범위와 세션은 각기 다릅니다.

  • IDENT_CURRENT는 임의의 세션과 범위에 있는 특정 테이블에 대해 생성된 마지막 ID 값을 반환합니다.
  • @@IDENTITY는 전체 범위에 걸쳐 현재 세션에 있는 임의의 테이블에 대해 생성된 마지막 ID 값을 반환합니다.
  • SCOPE_IDENTITY는 현재 세션과 현재 범위에 있는 임의의 테이블에 대해 만들어진 마지막 ID 값을 반환합니다.

예제
다음은 IDENT_CURRENT, @@IDENTITY, SCOPE_IDENTITY에 의해 반환되는 서로 다른 ID 값을 설명하는 예제입니다.

USE pubs
DROP TABLE t6
DROP TABLE t7
GO
CREATE TABLE t6(id int IDENTITY)
CREATE TABLE t7(id int IDENTITY(100,1))
GO
CREATE TRIGGER t6ins ON t6 FOR INSERT
AS
BEGIN
  INSERT t7 DEFAULT VALUES
END
GO
—end of trigger definition

SELECT   * FROM t6
—id is empty.

SELECT   * FROM t7
—id is empty.

—Do the following in Session 1
INSERT t6 DEFAULT VALUES
SELECT @@IDENTITY    
/*Returns the value 100, which was inserted by the trigger.*/

SELECT SCOPE_IDENTITY() 
/* Returns the value 1, which was inserted by the
INSERT stmt 2 statements before this query.*/

SELECT IDENT_CURRENT(‘t7’)
/* Returns value inserted into t7, i.e. in the trigger.*/

SELECT IDENT_CURRENT(‘t6’)
/* Returns value inserted into t6, which was the INSERT statement 4 stmts before this query.*/

—Do the following in Session 2
SELECT @@IDENTITY
/* Returns NULL since there has been no INSERT action
so far in this session.*/

SELECT SCOPE_IDENTITY()
/* Returns NULL since there has been no INSERT action
so far in this scope in this session.*/

SELECT IDENT_CURRENT(‘t7’)
/* Returns the last value inserted into t7.*/

Author Details
Kubernetes, DevSecOps, AWS, 클라우드 보안, 클라우드 비용관리, SaaS 의 활용과 내재화 등 소프트웨어 개발 전반에 도움이 필요하다면 도움을 요청하세요. 지인이라면 가볍게 도와드리겠습니다. 전문적인 도움이 필요하다면 저의 현업에 방해가 되지 않는 선에서 협의가능합니다.
0 0 votes
Article Rating
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
ChoSeongWoo
ChoSeongWoo
14 years ago

퍼가여 좋은정보 감사합니다.

최재훈
14 years ago

도움이 됐다니 다행이네요. 정신이 없어서 답글이 늦었습니다.