1

So I have a simple query as follows;

SELECT Name FROM Contact WHERE Age > @age

My question is, I want this query to always return a value. If there are no results the SQL query is suppose to return ' ' (blank space).

I have added a UNION SELECT at the end;

SELECT Name FROM Contact WHERE Age > @age UNION SELECT ' '

However this also adds the blank record when there is a result.

2 Answers 2

2
IF NOT EXISTS(SELECT Name FROM Contact WHERE Age > @age)
BEGIN 
SELECT '' AS age
END
ELSE 
BEGIN 
SELECT Name FROM Contact WHERE Age > @age
END

This will check if a result set will return and if nothing will, select a blank space and name the field age.

Sign up to request clarification or add additional context in comments.

6 Comments

Your suggestion works thank you ! Do you think there might be a way without using if else statements ?
@0014 What other restrictions do you have?
What do you mean by other restrictions ? There are no other restrictions.
So your only restriction is that you can't use if/else?
Yeah there is, but this is the cleanest way. The other ways I can think of would be very muddy.
|
2

I would do this all in a single query:

select name
from contacts
where age > @age
union all
select v.name
from (values ('')) v.name
where not exists (select 1 from contacts where age > @age);

Or using a CTE:

with t as (
      select name
      from contacts
      where age > @age
     )
select t.*
from t
union all
select v.name
from (values ('')) v(name)
where not exists (select 1 from t);

Or, the fun way using a left join:

select coalesce(c.name, v.name) as name
from (values ('')) v(name) left join
     contacts c
     on c.age > @age;

3 Comments

Perfect answer! This was what I was actually looking for.
@0014 . . . If this is your preferred answer, then you should accept it.
I haven't specified that I was looking for a single query in my question. So the answer that I selected deserved to be selected. But only because he was faster than you to answer the question...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.