본문 바로가기

▣ DB ▣/◈ MS-SQL ◈

MSSQL에서 시퀀스 트랜젝션 (@@IDENTITY ,IDENT_CURRENT,SCOPE_IDENTITY) MSSQL

 

 

 

1. IDENT_CURRENT

Returns the last identity value generated for a specified table in any session and any scope.

Syntax

IDENT_CURRENT('table_name')

Arguments

table_name

Is the name of the table whose identity value will be returned. table_name is varchar, with no default.

Return Types

sql_variant

Remarks

IDENT_CURRENT is similar to the Microsoft® SQL Server™ 2000 identity functions SCOPE_IDENTITY and @@IDENTITY.

All three functions return last-generated identity values.

However, the scope and session on which 'last' is defined in each of these functions differ

IDENT_CURRENT returns the last identity value generated for a specific table in any session and any scope.
@@IDENTITY returns the last identity value generated for any table in the current session, across all scopes.
SCOPE_IDENTITY returns the last identity value generated for any table in the current session and the current scope

 

 

 


 

2. 종류
SELECT IDENT_CURRENT('table_name')
/* Returns value inserted into t6, which was the INSERT statement 4 stmts before this query.*/
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.*/

 

 

 

 

3. IDENT_CURRENT('T1') 과 @@IDENTITY 의 차이점

@@IDENTITY는 반드시 입력(INSERT)을 한 후에 정확한 값을 알수 있습니다.

IDENT_CURRENT('T1') 는 입력 하기 전에 알수 가 있습니다.

따라서 @@IDENTITY 는 입력을 한후에 다른 테이블에 똑같은 값을 입력 하기 위해서 사용 하면 됩니다.

트랜 젝션이 많은 서비스에서 이용 가능 하다고 봅니다.

IDENT_CURRENT('T1') 는 전세션에서 접근이 가능 합니다.

그러나 문제는 입력을 하기전에 알수 있기는 하지만 입력을 하기전에 값을 읽어 오고

그값으로 테이블에 입력을 하는경우 문제가 있습니다.

읽고 나서 입력을 하는 사이의 시간에 다른 트렌 젝션이 들어오면 중첩될 확률이 높다는 것입니다.

따라서 트랜 젝션이 많은 서비스에서 이용이 불가능 하다고 봅니다.

 

 

 

 

 

4. 결론

@@IDENTITY 나 SCOPE_IDENTITY() 를 이용하며 입력을 먼저 하고 그 값으로 다른 작업을 하는 것이 적절합니다.

오라클도 마찬 가지고 MYSQL도 마찬가지 가 되겠지요 .

 

 

 

 

 

 

 

 

 

오라클은 returning

INSERT INTO emp (empno, ename) VALUES (:empno,:ename)
RETURNING ROWID INTO :rid

mysql은

INSERT INTO person VALUES (NULL, 'Antonio Paz');
INSERT INTO shirt VALUES
(NULL, 'polo', 'blue', LAST_INSERT_ID()), (NULL, 'dress', 'white', LAST_INSERT_ID());

% 사용 용례 ( 두개의 세션을 열고 아래와 같이 작업 해보았다)