SET IDENTITY_INSERT (Transact-SQL)
Consente l'inserimento di valori espliciti nella colonna Identity di una tabella.
La proprietà IDENTITY_INSERT può essere impostata su ON per una sola tabella di una sessione. Se in una tabella tale proprietà è già impostata su ON e viene eseguita un'istruzione SET IDENTITY_INSERT ON per un'altra tabella, SQL Server visualizza un messaggio di errore per segnalare che la proprietà SET IDENTITY_INSERT è già impostata su ON e indicata la tabella per la quale l'opzione è impostata.
Se il valore immesso è maggiore del valore Identity corrente per la tabella, il nuovo valore viene utilizzato automaticamente da SQL Server come valore Identity corrente.
L'opzione SET IDENTITY_INSERT viene impostata in fase di esecuzione, non in fase di analisi.
Nell'esempio seguente viene creata una tabella contenente una colonna Identity e viene illustrato come tramite l'impostazione di SET IDENTITY_INSERT sia possibile completare un'interruzione nella sequenza di valori Identity generata da un'istruzione DELETE.
USE AdventureWorks;
GO
-- Create tool table.
CREATE TABLE dbo.Tool(
ID INT IDENTITY NOT NULL PRIMARY KEY,
Name VARCHAR(40) NOT NULL
)
GO
-- Inserting values into products table.
INSERT INTO dbo.Tool(Name) VALUES ('Screwdriver')
INSERT INTO dbo.Tool(Name) VALUES ('Hammer')
INSERT INTO dbo.Tool(Name) VALUES ('Saw')
INSERT INTO dbo.Tool(Name) VALUES ('Shovel')
GO
-- Create a gap in the identity values.
DELETE dbo.Tool
WHERE Name = 'Saw'
GO
SELECT *
FROM dbo.Tool
GO
-- Try to insert an explicit ID value of 3;
-- should return a warning.
INSERT INTO dbo.Tool (ID, Name) VALUES (3, 'Garden shovel')
GO
-- SET IDENTITY_INSERT to ON.
SET IDENTITY_INSERT dbo.Tool ON
GO
-- Try to insert an explicit ID value of 3.
INSERT INTO dbo.Tool (ID, Name) VALUES (3, 'Garden shovel')
GO
SELECT *
FROM dbo.Tool
GO
-- Drop products table.
DROP TABLE dbo.Tool
GO
