SQL-How to Insert Row Without Auto incrementing a ID Column?

后端 未结 4 676
长发绾君心
长发绾君心 2020-12-24 12:17

I have a table that has a forced auto increment column and this column is a very valuable ID that is retained through out the entire app. Sorry to say it was poor developme

相关标签:
4条回答
  • 2020-12-24 12:42

    If you are in Microsoft SQL Server, you can "turn off" the autoIncrementing feature by issuing the statement Set Identity_Insert [TableName] On, as in:

      Set Identity_Insert [TableName] On
      -- --------------------------------------------
      Insert TableName (pkCol, [OtherColumns])
      Values(pkValue, [OtherValues])
      -- ---- Don't forget to turn it back off ------
      Set Identity_Insert [TableName] Off
    
    0 讨论(0)
  • 2020-12-24 12:42
    bulk insert tablename from 'C:\test.csv' with (rowterminator = '\n',fieldterminator = ',',KEEPIDENTITY)
    
    0 讨论(0)
  • 2020-12-24 12:46

    In addition to Charles' answer (which is now 100% correct :-) and which preserves the current value of the IDENTITY on the table), you might also want to check the current value of an IDENTITY on a table - you can do this with this command here:

    DBCC CHECKIDENT('YourTableName')
    

    If you ever need to actually change it, you can do so by using this command here:

    DBCC CHECKIDENT ('YourTableName', RESEED, (new value for IDENTITY) )
    
    0 讨论(0)
  • 2020-12-24 12:55

    Actually, the code above for INDENTITY_INSERT is correct - turning it ON tells the server you want to insert the values yourself. It allows you to insert values into an IDENTITY column. You then want to turn it back off (allowing the server to generate and insert the values) when you are done.

    0 讨论(0)
提交回复
热议问题