1

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

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 条件中添加 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
4

3 回答 3

5

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

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

另请注意,您的代码&searchtextwhere子句中引用,但这应该@searchtext按照这个答案(即前缀@not &)。

于 2013-04-04T14:31:06.767 回答
1

@RB 是正确的,您不需要案例,但您可以使用带有此技巧的案例,这在其他情况下也很有用:

 Where deleted = case @status when 4 then deleted else 0 end 
于 2013-04-04T14:32:34.680 回答
-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
于 2013-04-04T14:40:40.220 回答