Case
Currently I'm working on database seeding script, executed with sqlcmd
. For example this script sample:
IF (SELECT COUNT(*) FROM Genders)=0
BEGIN
PRINT N'Seeding table Genders...'
SET IDENTITY_INSERT Genders ON
GO
INSERT INTO Genders (GenderId, Description) VALUES (0, 'Onbekend');
INSERT INTO Genders (GenderId, Description) VALUES (1, 'Vrouw');
INSERT INTO Genders (GenderId, Description) VALUES (2, 'Man');
INSERT INTO Genders (GenderId, Description) VALUES (3, 'Onzijdig');
INSERT INTO Genders (GenderId, Description) VALUES (4, 'Vrouwman');
INSERT INTO Genders (GenderId, Description) VALUES (5, 'Manvrouw');
SET IDENTITY_INSERT Genders OFF
END
GO
Problem
However, if I execute it with sqlcmd
mode in SQL Server Management Studio, it gives me this errors:
Msg 102, Level 15, State 1, Line 5 Incorrect syntax near 'ON'.
Msg 102, Level 15, State 1, Line 10 Incorrect syntax near 'END'.
Googled some, but can't figure out what I'm doing wrong. Without the IF/BEGIN/END if does work, but I like to perform the check first.
Questions:
Thanks in advance!!
IDENTITY_INSERT off in SQL Server Once you have turned the IDENTITY_INSERT option OFF, you cannot insert explicit values in the identity column of the table. Also, the value will be set automatically by increment in the identity column if you try to insert a new record.
Answers. In a given session , you can have only one table's IDENTITY_INSERT property set to ON. You can use set IDENTITY_INSERT state (on/off) only at excute or run time.
IDENTITY_INSERT is a table property that allows you to insert explicit values into the column of table identifiers, i.e. into the column with IDENTITY. The value of the inserted identifier can be either less than the current value or more, for example, to skip a certain interval of values.
You cannot have GO
within BEGIN
and END
. Try following
SET IDENTITY_INSERT Genders ON
IF (SELECT COUNT(*) FROM Genders)=0
BEGIN
PRINT N'Seeding table Genders...'
INSERT INTO Genders ...
END
SET IDENTITY_INSERT Genders OFF
GO
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With