Problems with IDENTITY_INSERT Set to OFF? :-/

后端 未结 6 826
情深已故
情深已故 2020-12-14 13:49

I\'m trying to insert order details into my DB, and it keeps saying:

Cannot insert explicit value for identity column in table \'Orders\' when IDENTIT

6条回答
  •  抹茶落季
    2020-12-14 14:18

    Generally you would not want to insert an integer into a primary key column. You would usually set the column's "Identity" flag to true only where you wanted to have SQL Server set an auto-incrementing integer into this column on insert.

    As with Marc Gravell's answer, you can enable identity insert using

    SET IDENTITY_INSERT [ database. [ owner. ] ] { table } { ON | OFF }
    

    But doing this in regular application code is really unhealthy -- you'll end up with concurrency issues and quite likely duplicate identities. Better, don't insert the Order's ID -- let the DB do it for you automatically, and then simply query for the new ID using @@IDENTITY (or better, SCOPE_IDENTITY()).

    If for some reason you definitely need to store the user's session id, make this a separate column on the order table, or better still, on a separate User table, with the UserId being a foreign key.

提交回复
热议问题