Sqlserver
 sql >> Teknologi Basis Data >  >> RDS >> Sqlserver

Bagaimana cara memperbarui Kolom Identitas di SQL Server?

Anda tidak dapat memperbarui kolom identitas.

SQL Server tidak mengizinkan untuk memperbarui kolom identitas tidak seperti yang dapat Anda lakukan dengan kolom lain dengan pernyataan pembaruan.

Meskipun ada beberapa alternatif untuk mencapai persyaratan serupa.

  • Saat nilai kolom Identitas perlu diperbarui untuk catatan baru

Gunakan DBCC CHECKIDENT yang memeriksa nilai identitas saat ini untuk tabel dan jika diperlukan, mengubah nilai identitas.

DBCC CHECKIDENT('tableName', RESEED, NEW_RESEED_VALUE)
  • Saat nilai kolom Identitas perlu diperbarui untuk catatan yang ada

Gunakan IDENTITY_INSERT yang memungkinkan nilai eksplisit dimasukkan ke dalam kolom identitas tabel.

SET IDENTITY_INSERT YourTable {ON|OFF}

Contoh:

-- Set Identity insert on so that value can be inserted into this column
SET IDENTITY_INSERT YourTable ON
GO
-- Insert the record which you want to update with new value in the identity column
INSERT INTO YourTable(IdentityCol, otherCol) VALUES(13,'myValue')
GO
-- Delete the old row of which you have inserted a copy (above) (make sure about FK's)
DELETE FROM YourTable WHERE ID=3
GO
--Now set the idenetity_insert OFF to back to the previous track
SET IDENTITY_INSERT YourTable OFF


  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Semua yang harus Anda ketahui tentang SQL Server BERGABUNG

  2. Tips untuk Memindahkan Database SQL Server dari Satu Server ke Server Lain - Tutorial SQL oleh Rajan Singh

  3. SQL Server - mengendus parameter

  4. DATETIME2FROMPARTS() Contoh di SQL Server (T-SQL)

  5. 5 Manfaat Pemantauan Kinerja Basis Data Proaktif