0

Perhaps I'm misunderstanding COALESCE, but in essence, what I'm trying to do is run a select query that if it returns NULL instead of an int, instead return 0 for the purposes of ExecuteScalar().

SQL Server query:

SELECT TOP 1 COALESCE(SeqNo,0) 
FROM tblProjectChangeOrder 
WHERE ProjectID = XXXXX 
ORDER BY SeqNo DESC

If the supplied ProjectID exists in the Change Order table, it returns the expected highest SeqNo. However, if the supplied ProjectID has no existing Change Orders (thus returns NULL for SeqNo), rather than the COALESCE returning 0, I am still getting NULL.

Am I just getting the syntax wrong or is what I want to do possible with COALESCE? The other option I see is to have my ExecuteScalar() pass to a nullable int, then follow that with a ?? to coalesce in my C# codebehind.

Jeff Cox
  • 333
  • 4
  • 14

3 Answers3

5

As john has mentioned in the comments, COALESCE operates at row level. If a table contains no rows, or a statement returns no rows, then no rows will be returned. Take the simple example below:

CREATE TABLE #Sample (ID int);

SELECT COALESCE(ID, 0)
FROM #Sample;

DROP TABLE #Sample;

Notice that nothing is returned.

Instead, one method is to use a subquery. For your query, that would result in:

SELECT COALESCE(SELECT TOP 1 SeqNo 
                FROM tblProjectChangeOrder 
                WHERE ProjectID = XXXXX 
                ORDER BY SeqNo DESC),0) AS SeqNo;

This also assumes that Seqno has a data type of int; otherwise you're likely to get a conversion error.

Thom A
  • 88,727
  • 11
  • 45
  • 75
0

My guess is that the null reference exception occures on the code and has nothing to do with the sql query. It might just be that your code is not handling that you return no rows (or no scalar in your case) but you might be trying to access it somewhere in c#.

Show us the line of code that is throwing this exception in c# so we might be able to confirm this.

regards

Edit : From this similar topic

In your c# code you might want to try ("cmd" being your "SqlCommand" object):

int result = 0;
int.TryParse(cmd.ExecuteScalar(), out result);

or in one line

int.TryParse(cmd.ExecuteScalar(), out int result);

I don't know if it is the most suitable solution for you but I hope it is a start.

Nerevar
  • 303
  • 1
  • 9
0

As covered null and no row are not the same.
This sample covers it.

set nocount on;
select isnull(1, 0) 
where 1 = 1;
select isnull(1, 0) 
where 1 = 2;
select isnull(null, 0) 
where 1 = 1;
select isnull(null, 0) 
where 1 = 2;

-----------
1


-----------


-----------
0


-----------

this should work

select top 1 isnull(seq, 0) 
from (select null as seq 
      union all   
      select max(seq) from tblProjectChangeOrder where ProjectID = XXXXX 
     ) tt
order by seq desc
paparazzo
  • 44,497
  • 23
  • 105
  • 176