Transact-SQL リファレンス


Transact-SQL リファレンス
IDENT_CURRENT

任意のセッションと有効範囲内の特定のテーブルに対して生成された ID 値を返します。

構文

IDENT_CURRENT('table_name')

引数

table_name

ID 値が返されるテーブルの名前です。table_namevarchar であり、既定値はありません。

戻り値の型

sql_variant

解説

IDENT_CURRENT は、Microsoft® SQL Server™ 2000 の ID 関数である SCOPE_IDENTITY と @@IDENTITY に似ています。3 つの関数とも、最後に生成された 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.*/

関連項目

@@IDENTITY

SCOPE_IDENTITY

Page view tracker