SQL Server SUM返回null,它应该返回0

时间:2018-09-15 11:10:53

标签: sql

如果列为空,我的查询将返回null。它应该返回0,以便我可以在自己的代码中对其进行计算。

我已在网上搜索并找到“ COALESCE”和“ ISNULL”。我正在使用SQL Server 2012,我应该使用什么?我尝试了ISNULL并且它在我的查询中不起作用。这是我的代码。

 SqlCommand cmd2 = new SqlCommand("SELECT ISNULL(SUM (Male) as Male, SUM(Female) as Female ,SUM(Pax) as Pax,SUM(Single) as Single,SUM(Married) as Married,SUM(Students) as Students,SUM(Elementary) as Elementary,SUM(Highschool) as Highschool,SUM(College) as College,SUM(PWD) as PWD, SUM([AR Users]) as ARUsers,SUM([12 Below]) as age1,SUM([13-21]) as age2,SUM([22-35]) as age3,SUM([36-50]) as age4,SUM([51-65]) as age5,SUM([65 Above]) as age6 ,0) FROM  [tbl_ForeignVisit] where [Date Added] >= '"
            + dateTimePicker1.Value.Date.ToShortDateString() + "' AND  [Date Added] <='" + dateTimePicker2.Value.Date.ToShortDateString() + "'  ;", connection);

2 个答案:

答案 0 :(得分:1)

我认为您需要为每个ISNULL组使用COALESCESUM而不是一个。

您的SQL查询字符串存在SQL注入问题,请使用参数代替Connect SQL语法

string sqlQuery = @"SELECT 
    ISNULL(SUM(Male),0) as Male, 
    ISNULL(SUM(Female),0)  as Female ,
    ISNULL(SUM(Pax),0)  as Pax,
    ISNULL(SUM(Single),0)  as Single,
    ISNULL(SUM(Married),0)  as Married,
    ISNULL(SUM(Students),0)  as Students,
    ISNULL(SUM(Elementary),0)  as Elementary,
    ISNULL(SUM(Highschool),0)  as Highschool,
    ISNULL(SUM(College),0)  as College,
    ISNULL(SUM(PWD),0)  as PWD, 
    ISNULL(SUM([AR Users]),0)  as ARUsers,
    ISNULL(SUM([12 Below]),0)  as age1,
    ISNULL(SUM([13-21]),0)  as age2,
    ISNULL(SUM([22-35]),0)  as age3,
    ISNULL(SUM([36-50]),0)  as age4,
    ISNULL(SUM([51-65]),0)  as age5,
    ISNULL(SUM([65 Above]),0)  as age6
FROM  [tbl_ForeignVisit] 
where [Date Added] >= @DateAdded"

SqlCommand cmd2 = new SqlCommand(sqlQuery);
cmd2.Parameters.Add("@DateAdded", SqlDbType.Date);
cmd2.Parameters["@DateAdded"].Value = dateTimePicker1.Value.Date;

注意

如果要通过比较date类型获取数据。我将在参数中设置SqlDbType.Date,以确保可以比较date类型。

答案 1 :(得分:0)

您需要为每个SUM列使用 ISNULL

例如ISNULL(SUM(Male),0) as Male

返回:0