Sqlserver
 SQL >> Database >  >> RDS >> Sqlserver

IDENT_CURRENT vs @@IDENTITY vs SCOPE_IDENTITY: test basato su trigger

Quando serve il valore appena generato per una colonna identity, ci sono tre candidate. Sembrano simili, ma rispondono a domande diverse.

  • IDENT_CURRENT() restituisce l’ultimo valore identity inserito in una tabella specifica.
  • SCOPE_IDENTITY() restituisce l’ultimo valore identity inserito in qualsiasi tabella nella sessione e nell’ambito correnti.
  • @@IDENTITY restituisce l’ultimo valore identity inserito in qualsiasi tabella nella sessione corrente, indipendentemente dall’ambito.

Dimostrazione con un trigger

I trigger hanno un proprio ambito, quindi sono perfetti per evidenziare le differenze.

CREATE TABLE t1(id int IDENTITY(1,1));
CREATE TABLE t2(id int IDENTITY(150,10));

CREATE TRIGGER t1_insert_trigger ON t1
FOR INSERT AS
BEGIN
    INSERT t2 DEFAULT VALUES
END;

Inserimento e lettura:

INSERT t1 DEFAULT VALUES;
SELECT id AS t1 FROM t1;
SELECT id AS t2 FROM t2;

Risultato:

+------+
| t1 |
|------|
| 1 |
+------+
+------+
| t2 |
|------|
| 150 |
+------+

La riga in t1 arriva dal batch, quella in t2 dal trigger.

SELECT @@IDENTITY AS [@@IDENTITY],
       SCOPE_IDENTITY() AS [SCOPE_IDENTITY()],
       IDENT_CURRENT('t1') AS [IDENT_CURRENT('t1')],
       IDENT_CURRENT('t2') AS [IDENT_CURRENT('t2')];

Risultato:

+--------------+--------------------+-----------------------+-----------------------+
| @@IDENTITY | SCOPE_IDENTITY() | IDENT_CURRENT('t1') | IDENT_CURRENT('t2') |
|--------------+--------------------+-----------------------+-----------------------|
| 150 | 1 | 1 | 150 |
+--------------+--------------------+-----------------------+-----------------------+

@@IDENTITY ignora l’ambito e riporta 150, valore creato dal trigger. SCOPE_IDENTITY() riporta 1 perché il trigger è fuori dall’ambito corrente. IDENT_CURRENT() dipende solo dalla tabella.

Nuova sessione

Riconnettendosi e rieseguendo la query, le funzioni legate alla sessione restituiscono NULL, mentre IDENT_CURRENT() resta invariato.