0

I'm trying to solve the following problem:

I would like to make a select, when the result is empty it should be replaced with 'empty' Else the result should be there. That is my try:

select case (count*) 
       when 0 then 'empty'
       ELSE
       THEVALUEOFTHECOLUM
END AS RESULT

from Database.table where CarID = 12;

Thanks for every comment.

1

4 Answers 4

2

This should work, but you might have to convert the second occurrence of COUNT(*) to VARCHAR depending on the database used:

SELECT
  CASE WHEN COUNT(*) = 0
    THEN 'empty'
    ELSE COUNT(*) -- CONVERT, TO_CHAR, ...
  END AS result
FROM Database.table where CarID = 12;
Sign up to request clarification or add additional context in comments.

2 Comments

That will only return the count, if you want the column you need replace the second count with MAX(collname), but that will only return one entry.
MAX is needed because Else want's to return one result. You can use any aggregate function
0
SELECT 
CASE
    WHEN Q.countvalue = 0 THEN 'Empty' 
    ELSE CONVERT(NVARCHAR(10), Q.countvalue) 
END AS RESULT
FROM 
    (
    SELECT COUNT(*) AS countvalue
    FROM   Database.table WHERE CarID = 12
    ) AS Q

Comments

0

This feels hacky to me, but it will return the column data. It is not one query, but it's still setwise.

declare @tmp table (id int)
declare @cnt int
insert into @tmp select col from table
select @cnt = count(*) from @tmp
if(@cnt = 0)
begin
    select 'empty'
end
else
begin
    select * from @tmp
end

2 Comments

I want all colums, how can I make your code work? Is there a procedure needed?
@John I don't understand the question. Where do you want all columns?
0

Is it possible to code it with one query? If there are no results -> no result found else Show all results, not only one

declare @tmp table (id int) 
declare @cnt int 
insert into @tmp select col from table 
select @cnt = count(*) from @tmp 
if(@cnt = 0) 
begin     
select 'empty' 
end 
else 
begin     
select * from @tmp 
end 

Comments

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.