I have a SQL query which uses the TOTAL()
aggregate function:
SELECT
c.Id,
c.Name,
...
b.BatchNumber,
TOTAL(d.OrderedAmount) as TotalOrderedAmount
FROM OrderProducts a
LEFT JOIN WarehouseProducts b ON a.WarehouseProductId = b.Id
...
WHERE a.OrderId = @OrderId
AND (e.Status = @OrderedStatus OR e.Status IS NULL)
(Extraneous rows removed for clarity)
This query returns at least one row even when no results are found, causing every column to be DBNull (I assume). When I try to load the results of this query into a DataTable, I get an ConstraintException because of the null values.
If I substitute the TOTAL()
row with 0 as TotalOrderedAmount
, the number of rows returned is 0 and everything works fine.
I've tried using WHERE a.Id IS NOT NULL
but whatever I try, there always seems to be at least one row returned.
How can I modify this query so that when no products are found, the number of rows returned is 0, even with the aggregate function?