SQL with unknown purpose
I have to change some SQL queries (SQL Server 2005) done by another person and in that code I see often the following construction:
SELECT fieldA, SUM(CASE fieldB WHEN null THEN 0 ELSE fieldB END) as AliasName FROM ...
I don't understand the case statement because as far as I know, null can not be checked within a case and therefore I t开发者_如何学Pythonhink that the above code does the same as:
SELECT fieldA, SUM(fieldB) as AliasName FROM ...
I have also done some tests and have not seen any differences in the result. Am I missing something, or can I replace the upper statement through the short one?
UPDATE
Only for completeness because it's not mentioned in the answers: The upper code returns the same result as the lower. The used case
construction does not replace null's through zero's and therefore it can be ommited. If the purpose of the original sql was to make sure that never null will be returned, the coalesce
or the isnull
-operator can be used (as stated in the answers).
The output of your second statement will contain nulls
(when aggregating records that only have null
values for fieldB
). If you don't mind that, you're ok.
If you want zeros in your output rather than null
values, use this:
select fieldA, sum(isnull(fieldB, 0)) as AliasName from ...
You would achieve this more readably with
SELECT fieldA, COALESCE(fieldB, 0) as AliasName
精彩评论