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).
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';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With