Case statement to determine if I should union
You could use an ugly hack something like this, but I think Tim's answer is better:
SELECT age, nameFROM usersUNION ALLSELECT 25, 'Betty'WHERE (SELECT COUNT(*) FROM users) > 1;
If it's in a stored-procedure you could use If...Else
:
IF (SELECT COUNT(*) FROM users) < 2 BEGIN SELECT age, name FROM users ENDELSE SELECT age, name FROM users UNION ALL SELECT 25 AS age, 'Betty' AS name
Otherwise you could try something like this:
SELECT age, name FROM users UNION ALL SELECT TOP 1 25 AS age, 'Betty' AS name FROM users WHERE (SELECT COUNT(*) FROM users) >= 2
Note that i've used UNION ALL
since it doesn't seem that you want to eliminate duplicates.
Played around here: http://sqlfiddle.com/#!6/a7540/2323/0
Edit: Instead of my second approach i prefer Zohar's. So if you can use If....Else
prefer that otherwise WHERE (SELECT COUNT(*) FROM users) > 1
without a table.
Something like the following should work:
SELECT age, nameFROM usersUNION ALLSELECT age, nameFROM (SELECT 25 AS age, 'Betty' AS name) xCROSS APPLY (SELECT COUNT(*) FROM users) y(cnt)WHERE y.cnt >= 2
Second part of UNION ALL
will be NULL
in case users
table has less than 2 records.