如果没有SELECT语句的结果,是否可以使用CASE返回某个字符串?
例:
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
以上不起作用,因为如果我正在搜索的帐号不存在于我的日志表中,那么将不会有任何结果,并且消息“我们没有为该客户记录”将永远不会实现.
我可以使用PRINT命令使用纯T-sql来实现,但是我正在使用第三方应用程序,结果必须以表格形式(因此只有SELECT语句).
解决方法
您可以使用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';