当行不存在时,SQL返回预定义的字符串

时间:2018-10-22 10:04:13

标签: sql sql-server

select name, designation, salary 
from employee 
where employeeID = 123

如果employeeID 123不存在,则sql应返回“ EmployeeID无效”。

我尝试了Union和case语句,但没有得到所需的结果。

数据库:SQL Server

1 个答案:

答案 0 :(得分:1)

这实际上必须在应用程序级别而不是SQL上完成,但是您可以使用NOT EXISTS进行验证:

IF NOT EXISTS (SELECT 1 FROM employee WHERE employeeID = 123)
   BEGIN
         PRINT 'EmployeeID is not valid' --- OR USE RETURN
         -- SELECT 'EmployeeID is not valid' --- OR SELECT statement with message
   END
   ELSE
   BEGIN
         SELECT name, designation, salary 
         FROM employee 
         WHERE employeeID = 123
   END