I have a column in a SQL Server database table, there is a column containing integer values and I would like to get the max value unless there is a gap in the series, then I would like to get the first missing value.
For example from the below table, I am looking to get value 4
1
2
null
3
The above is simple, however if the table contains data like below, how can I find which id I am missing, in this case it would be 8
1
3
2
4
null
5
7
6
null
10
9
//////////////////
Edit:
I Initially implemented @podiluska's answer and was going to accept it however when I tested with a table with over 10K rows it was quite slow, so I have taken @vmvadivel's answer and changed it slightly as shown below and it works quite fast, but still not 100% what I wanted:
SELECT Number
FROM
(
SELECT ROW_NUMBER() OVER(ORDER BY iValue) AS Number
FROM tblNumbers WHERE iValue IS NOT NULL
) temp
WHERE Number NOT IN
(
SELECT iValue FROM tblNumbers WHERE iValue IS NOT NULL
)
This works quite well however if all the iValue
fields are null then I don't get anything back, but I want it to return 1 as it will be the first value in series, obviously I can handle this in the C# code but I am sure there must be a way of returning 1 if the above query does not return a row?
I have changed the top level Select Number
with SELECT Coalesce(Number, 1)
but it did not work, any ideas how to solve this?
Thanks