Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using CASE to Return a String If No Results From SELECT Statement

Is it possible to use CASE to return a certain string if there are no results from my SELECT statement?

Example:

DECLARE @accountnumber AS VARCHAR(10)

SET @accountnumber = 'account number to search'

SELECT 
    CASE
    WHEN account IS NOT NULL
    THEN 'We Have Records of this Customer'
    WHEN account IS NULL
    THEN 'We Do Not Have Records For This Customer'
    END AS 'result'
FROM call_records
WHERE account = @accountnumber
GROUP BY account

The above does not work since if the account number I am searching for isn't present in my logs table then there would be no results and the message 'We Do Not Have Records For This Customer' would never materialize.
I can do what I am trying to achieve using pure T-SQL with a PRINT command, but I am working with a 3rd party app and the results must be in table form (so SELECT statements only).

like image 831
Lloyd Banks Avatar asked Feb 18 '13 16:02

Lloyd Banks


1 Answers

You can use EXISTS:

SELECT 
    CASE
    WHEN EXISTS(
        SELECT 1 FROM call_records
        WHERE account = @accountnumber
    ) 
    THEN  'We Have Records of this Customer'
    ELSE  'We Do Not Have Records For This Customer'
    END AS 'result';
like image 200
Tim Schmelter Avatar answered Oct 02 '22 23:10

Tim Schmelter