Statement of situation to determine if I should team up

Currently I want to make some kind of conditional union. In the following example:

SELECT age, name FROM users UNION SELECT 25 AS age, 'Betty' AS name 

Let's say I just wanted to connect the second operator if the number of users was> = 2, otherwise do not combine them.

In conclusion, I want to add a table with a row if the table has only 2 or more values.

+5
source share
4 answers

You can use an ugly hack something like this, but I think Tim's answer is better:

 SELECT age, name FROM users UNION ALL SELECT 25 AS age, 'Betty' AS name WHERE (SELECT COUNT(*) FROM users) > 1 
+10
source

If in a stored procedure you can use If...Else :

 IF (SELECT COUNT(*) FROM users) < 2 BEGIN SELECT age, name FROM users END ELSE SELECT age, name FROM users UNION ALL SELECT 25 AS age, 'Betty' AS name 

Otherwise, you can 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 

Please note that I used UNION ALL , since it does not seem like you want to remove duplicates.

It is played here: http://sqlfiddle.com/#!6/a7540/2323/0

Change Instead of my second approach, I prefer Zohar . Therefore, if you can use If....Else , you would prefer that otherwise WHERE (SELECT COUNT(*) FROM users) > 1 without a table.

+6
source

Something like the following should work:

 SELECT age, name FROM users UNION ALL SELECT age, name FROM (SELECT 25 AS age, 'Betty' AS name) x CROSS APPLY (SELECT COUNT(*) FROM users) y(cnt) WHERE y.cnt >= 2 

The second part of UNION ALL will be NULL if the users table has less than 2 entries.

+5
source
 SELECT age , name FROM users UNION SELECT 25 As age , 'Betty' As name WHERE EXISTS ( SELECT Count(*) FROM users HAVING Count(*) >= 2 ) ; 
+1
source

All Articles