18 July 2007

Please Give me the solution,

Today I had a requirement that I have to get missing number form table and start new ID form that missing value...

Ex. I have a customer table.

ID Name
1 Vijay
2 Rajesh
3 Nitin
5 Manish
6 Bipin
8 Jalpesh

Here, 4 and 7 number are missing, some one have deleted that record. and now suppose user click on add new button he want to generate that missing number.

Here a I have create a small cursor to get that value:


DECLARE @lastID int,
@crrID int

SET @crrID=1;

DECLARE curJob CURSOR FORWARD_ONLY READ_ONLY LOCAL
FOR
SELECT ID FROM Customer ORDER BY ID

OPEN curJob

FETCH NEXT FROM curJob INTO @lastID

WHILE @@FETCH_STATUS = 0 AND @crrID=@lastID
BEGIN
SET @crrID=@crrID+1
FETCH NEXT FROM curJob INTO @lastID
END

CLOSE curJob
DEALLOCATE curJob

SELECT @crrID;


Done. This SQL satisfied my requirement.

But Its now a good idea where thousands of records in a table, I think that there should be some in built functions of SQL Server 2005, who can get me those missing values without any coding and quickly also.

Do you know any other solution?

0 comments :

Post a Comment