在sql中where子句条件的case语句

时间:2013-04-04 14:25:46

标签: sql sql-server tsql

我有一个这样的存储过程:

ALTER PROCEDURE [dbo].[hr_SearchVacanciesAdmin]
    @SearchText NVARCHAR(50) = NULL,
    @CompanyName NVARCHAR(100) = NULL,
    @DutyStationID INT = NULL,
    @VacancyCategoryIDs VARCHAR(1000) = NULL,
    @Status INT,
    @Language INT = 1

BEGIN

SELECT * from table
where 
  deleted = 0
  and status = @status
  and catname  = &searchtext

..
..
..
END

我想在where where条件中添加case语句,这样如果@status = 4则不检查delete =。我试过以下但没有工作

WHERE 
  1 = CASE 
        WHEN @Status = 4 
        THEN @status

        WHEN dbo.hr_Vacancies.Deleted = 0 
             --Search Criteria
             AND dbo.hr_Vacancies.Status = @Status 
        THEN @Status
      END

3 个答案:

答案 0 :(得分:5)

您不需要CASE语句来实现此功能。以下情况会很好:

SELECT * 
from   table
where  (deleted = 0 OR @status=4)
and    status = @status
and    catname = @searchtext

另请注意,您的代码在&searchtext子句中引用了where,但根据此答案,这应该是@searchtext(即@的前缀不是{{1} }})。

答案 1 :(得分:1)

@RB是正确的你不需要一个案例,但你可以使用这个技巧的案例,这在其他场景中也很有用:

 Where deleted = case @status when 4 then deleted else 0 end 

答案 2 :(得分:-1)

您可以使用此构造来开始SELECT查询:

Select * from table
WHERE
((1 = CASE WHEN @Status = 4 THEN 1 ELSE 0 END)
OR
dbo.hr_Vacancies.Deleted = 0)
AND
dbo.hr_Vacancies.Status = @Status