Why does one have to specify columns when IDENTITY_INSERT ON?

450 Views Asked by At

The following script failed to execute

SET IDENTITY_INSERT dbo.MyTable ON

-- the table only has three columns, so there's no ambiguity
INSERT INTO dbo.MyTable
VALUES (1, 2, 3)

SET IDENTITY_INSERT OFF

Which throws the following warning:

An explicit value for the identity column in table 'dbo.MyTable' can only be specified when a column list is used and IDENTITY_INSERT is ON.

The script executes as expected when columns are explicit.

SET IDENTITY_INSERT dbo.MyTable ON

INSERT INTO dbo.MyTable (ColA, ColB, ColC)
VALUES (1, 2, 3)

SET IDENTITY_INSERT OFF

Why must a column list be used?

1

There are 1 best solutions below

4
Carlos Alves Jorge On

Security. This way it ensures that you do specify the id column otherwise if, by mistake, you have IDENTITY_INSERT ON you can mess up your tables big time.