天若有情.NET

  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 :: 管理 ::

Finding & Using Unused IDs

Finding & Using Unused IDs
If you want to fill in the gaps in IDENTITY columns left by SQL Server when you delete rows from a table, you can quickly get a list of unused identities using the following piece of simple code. Assuming your table is called Customers and the IDENTITY column CustomerID...

DECLARE @LastID BIGINT
SET @LastID = (SELECT TOP 1 CustomerID FROM Customers ORDER BY CustomerID DESC)
WHILE @LastID > 0
BEGIN
   IF (SELECT COUNT(*) FROM Customers WHERE CustomerID = @LastID) = 0
      PRINT @LastID
   SET @LastID = @LastID - 1
END
To insert a specific value into an identiy column, temporarily turn the IDENTITY INSERT property on for that table of the database (you can only have it on for one table at a time).

SET IDENTITY_INSERT Customers ON
INSERT INTO Customers (
      CustomerID,
      CustomerName
   )
   VALUES (
      27,
      'Somebody'
   )
SET IDENTITY_INSERT Customers OFF
© Copyright Quantum Software Solutions 2003, All rights reserved.

posted on 2005-01-27 13:06  pathik  阅读(350)  评论(0)    收藏  举报