0

我希望使用三个参数从三列中进行选择,每列一个。如果列的所有参数都存在,那么它将返回第四列。但是,如果在表中没有找到三个参数中的任何一个,则它应该返回一条消息,通知用户哪个参数不正确。

我尝试了以下方法:

    SELECT RESULTS, "[status]" =
case
    when CostCenterNo <> '800' then 'CentreNotFound'
    when EmpNo <> '2' then 'EmpNotFound'
    when Surname <> 'sonny' then 'SurnameNotFound'
    else null
end 
from CostCentres
where 
CostCenterNo = 
case CostCenterno when 
    '800' then '800'
    else ''
end 
and 
EmpNo =
case EmpNo when 
    '2' then '2'
    else ''
end 
and 
Surname =
case Surname when 
    'sonny' then 'sonny'
    else ''
end 

当所有参数都正确时,这会检索正确的信息,但是当在表中找不到相应的参数时,我需要它说 CentreNotFound、EmpNotFound、SurnameNotFound。我已经尝试查找下面的链接,但仍然没有运气。 SQL Server where 子句中的 IF 语句

在 TSQL 中使用 EXISTS 作为列

SQL:WHERE 子句中的 IF 子句

我还尝试了以下代码:

        select  results =
    case when CostCenterNo = '800' then
        case when EmpNo = '2' then
          case when Surname = 'sonny' then

         (select results from bcse 
         where CostCenterNo = 'BW800'
        and EmpNo like '2'
        and Surname = 'sonny')

        else 'surname not found' end
        else 'Emp not found' end
    else 'center no not found' end

from CostCentres
where (CostCenterno = 'bw800' or CostCenterNo = '%')
and (EmpNo = '2' or EmpNo = '%' )
and (surname = 'sonny' or surname = '%')

以上适用于正确的参数,但是当在表中找不到相应的参数时,我再次需要它返回 CentreNotFound、EmpNotFound、SurnameNotFound。

4

1 回答 1

0

WHERE 条件应该是

where (CostCenterno = 'bw800' or CostCenterNo = '%')
and (EmpNo = '2' or EmpNo like '%' )
and (surname = 'sonny' or surname like '%')

此外,如果您使用参数,它应该是

where (CostCenterno = @CostCenterno or @CostCenterNo = '')
and (EmpNo = @EmpNo  or @EmpNo ='' )
and (surname = @surname or @surname ='')

编辑:您可能需要使用类似下面的东西

declare @error varchar(100)
set @error=
case 
when not exists(select * from CostCentres where CostCenterno = @CostCenterno) then
    'CenterNotFound'
when not exists(select * from CostCentres where EmpNo = @EmpNo) then
    'EmpnoNotFound'
when not exists(select * from CostCentres where surname = @surname) then
    'surnameNotFound'
end
select CostCenterno, EmpNo,surname , @error as status
from CostCentres
where
    CostCenterno = @CostCenterno 
and EmpNo = @EmpNo  
and surname = @surname 
于 2013-11-06T13:07:29.297 回答