Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

next available number in a field

Status
Not open for further replies.

blar9

Programmer
Mar 12, 2007
39
US
Field1
1
2
4
5
6

Is there a way for me to return the first available number ie 3?
 
Try one of these two. Adapted from

Code:
SELECT TOP 1 T1.Field1+1 AS FirstAvailableNumber
FROM   @TheTable AS T1 JOIN @TheTable AS T2
       ON T2.Field1 > T1.Field1
GROUP BY T1.Field1
HAVING 	MIN(T2.Field1)-T1.Field1 > 1

SELECT  TOP 1 T1.Field1+1 FirstAvailableNumber
FROM    @TheTable AS T1 LEFT JOIN @TheTable AS T2
        ON T2.Field1 = T1.Field1+1
WHERE	T2.Field1 IS NULL
 
You mean, is there a SQL Server function, stored procedure, or system variable which gives that value, right?

I dont know but how about this
Code:
SELECT MIN(a.Field1) + 1
FROM MyTable a
LEFT JOIN MyTable b ON b.Field1 = a.Field1 + 1
WHERE b.Field1 IS NULL

 
blar9,
Do you mind if I ask why you are filling in missing values? Is this field the PK of the table? As a general best practice rule you should re-use pk values.

- Paul
10qkyfp.gif

- If at first you don't succeed, find out if the loser gets anything.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top