How to use MAX() function when NULL is returned

  • My intention is to pick up the highest sequence number incremented by '1' from the column SequenceNo where ObjectId is equal to provided @ObjectId. When there are rows that satisfy this condition, I do not have any problem. Problem is when there is no any row that satisfies condition WHERE ObjectId = @ObjectId. I would like my variable @SequenceNo to be filled with ‘1’ in such a case. At the moment it is being filled with NULL and I cannot figure out how to get ‘1’ instead.

    DECLARE @SequenceNo int

    SET @SequenceNo = 0

    SELECT @SequenceNo = max(SequenceNo) + 1

    FROM SomeTable

    WHERE ObjectId = @ObjectId

  • Add ISNULL to your select statement and set the value to 0 or 1 as required in your select statement.

    Here is the solution.

    DECLARE @SequenceNo int

    SET @SequenceNo = 0

    SELECT @SequenceNo = ISNULL(max(SequenceNo), 0) + 1

    FROM SomeTable

    WHERE ObjectId = @ObjectId

  • Thank you athiraviam,

    That is the solution to my problem.

    I did try the same thing before I posted this problem and it did not work. Most probably I was mistyping something. Thanks again!

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply