Checking SQL MAX() Function returning null

泄露秘密 提交于 2019-12-11 03:11:54

问题


My problem is if my table is empty or the column on which I am using max function does not have the value I have specified, then why is sqlDataReader.hasRows TRUE?

It is giving a null record...how do I solve this problem??

Thanks in advance.


回答1:


An aggregate function like MAX() will always return one row per group. In your case, your group is the whole table. Therefore you get a one row resultset with the MAX value. Since you don't have data in your table, the MAX value is undefined, therefore NULL.

For better understanding try to replace MAX with COUNT. This will also return one row but with value 0. I think this is more intuitive and will help you better to understand what is happening.




回答2:


Make your query into a derived table and filter out null values in the main query.

select T.MaxValue
from (
     -- Your query goes here
     select max(Value) as MaxValue
     from YourTable
     where SomeCol > 10
     ) as T
where T.MaxValue is not null



回答3:


Or, use the HAVING clause because HAVING can be used with aggregate functions:

select max(Value) from YourTable where SomeCol > 10
HAVING max(Value) is not null



回答4:


you can use:

select top(select COUNT(*) from tbl) max(field) from tbl



来源:https://stackoverflow.com/questions/24266148/checking-sql-max-function-returning-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!