什么时候应该使用 SET IDENTITY_INSERT <tablename> OFF 函数?

When should I use SET IDENTITY_INSERT <tablename> OFF function?

要手动将值插入标识列,我使用:

SET identity_insert product ON

INSERT INTO product (PID, ProdName, Qty, Unitprice) 
VALUES (10, 'soap', 5400, 22)

首先我删除了第 10 个 row/record,然后我使用此命令插入标识值并手动记录。 此命令正在插入记录。还好

我应该在哪里写命令SET identity_insert product OFFSET identity_insert product OFF命令有什么用?

来自 https://docs.microsoft.com/en-us/sql/t-sql/statements/set-identity-insert-transact-sql?view=sql-server-ver15

At any time, only one table in a session can have the IDENTITY_INSERT property set to ON. If a table already has this property set to ON, and a SET IDENTITY_INSERT ON statement is issued for another table, SQL Server returns an error message that states SET IDENTITY_INSERT is already ON and reports the table it is set ON for.

所以您应该先将其关闭,然后再将其设置为会话中的另一个 table。

来自the documentation

At any time, only one table in a session can have the IDENTITY_INSERT property set to ON.

因此,如果您在批处理中想要覆盖 两个不同 表上的自动生成的标识值,您可以将第一个设置为 OFF 在将第二个设置为 ON.

之前

(另外,就像很多事情一样,如果您更改了默认设置,将其改回绝非坏主意。)