Answered by:
how to assign value 0 for DB Null

Question
-
User-1327394822 posted
sql = "Select Sum(TotalAmount) from Cart where CheckedOut = 1 and OrderDate between @0 and @1"; var orderRevenue = db.QueryValue(sql, fromDate, toDate);
if orderrevenue is Null... I want to assign 0...
I tried if(orderRevenue == null) ----- doesnt work
I tried if(orderRevenue == DBNull.Value) --- doesnt work if sum exists..
Noted: TotalAmount is "money" in sqlce
Monday, April 18, 2016 3:57 PM
Answers
-
User2015887388 posted
People have suggested more or less the correct answer.
sql = "Select Sum(TotalAmount) from Cart where CheckedOut = 1 and OrderDate between @0 and @1"; object result = db.QueryValue(sql, fromDate, toDate); var total = result == DBNull.Value ? 0.0 : (decimal)result;
You will need to swap decimal for whatever value total amount is. If you are using SQL Sever I'd assume it was decimal and if it was SQLCE then I'd assume it was money but you may be using int if you are just learning.
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Monday, April 18, 2016 8:35 PM
All replies
-
User379720387 posted
TotalAmount = 0;
db query here...
var ttlamount = db.QuerySingle( your query)
if (ttlamount != null) { TotalAmount = ttlamount; }
Monday, April 18, 2016 5:56 PM -
User-1327394822 posted
@wavemaster
Cannot implicitly convert type 'System.DBNull' to 'int'
Monday, April 18, 2016 7:23 PM -
User2015887388 posted
People have suggested more or less the correct answer.
sql = "Select Sum(TotalAmount) from Cart where CheckedOut = 1 and OrderDate between @0 and @1"; object result = db.QueryValue(sql, fromDate, toDate); var total = result == DBNull.Value ? 0.0 : (decimal)result;
You will need to swap decimal for whatever value total amount is. If you are using SQL Sever I'd assume it was decimal and if it was SQLCE then I'd assume it was money but you may be using int if you are just learning.
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Monday, April 18, 2016 8:35 PM -
User379720387 posted
if ((object)ttlamount != System.DBNull.Value) { TotalAmount = ttlamount; }
Tuesday, April 19, 2016 12:50 AM -
User-1780421697 posted
Why not use
// Set y to the value of x if x is NOT null; otherwise,
// if x = null, set y to -1.int y = x ?? 0;
Tuesday, April 19, 2016 11:16 AM -
User-1327394822 posted
var total = result == DBNull.Value ? 0.0 : (decimal)result;it should be 0m
var orderRevenue = result == DBNull.Value ? 0m : (decimal)result;
Wednesday, April 20, 2016 8:56 AM