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

问题描述 投票:0回答:1
select name, designation, salary 
from employee 
where employeeID = 123

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

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

数据库:SQL Server

sql sql-server
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.