Always select a row sql
I have a case
statment (see below) but I always want to return a value even if nothing matches the WHERE
clase. Is that possible? Thanks
SELECT
CASE
WHEN COUNT(*) > 10 THEN 1
ELSE 0
END
FROM
fldt_QueryDSLAM lastDay
WHERE AccountID = @acc
AND lastDay.DSL 开发者_StackOverflow中文版= @dsl
GROUP BY lastDay.DSL
If the WHERE clause returns one row (or one group more precisely), remove the GROUP BY. Then you'll always have one row in the output.
I assume it will (return one group) because you have GROUP BY on a filter column, and AccountID isn't mentioned in either SELECT or GROOUP BY
SELECT
CASE
WHEN COUNT(*) > 10 THEN 1
ELSE 0
END
FROM
fldt_QueryDSLAM lastDay
WHERE
AccountID = @acc AND lastDay.DSL = @dsl
For why, see this: Does COUNT(*) always return a result?
You can wrap the select within an isnull;
SELECT ISNULL((
SELECT
CASE
WHEN COUNT(*) > 10 THEN 1
ELSE 0
END
FROM
fldt_QueryDSLAM lastDay
WHERE AccountID = @acc
AND lastDay.DSL = @dsl
GROUP BY lastDay.DSL
), -99 /*no match*/)
精彩评论