我的存储过程中有输入参数。例如,
DECLARE @fromDate DateTime = NULL
DECLARE @toDate DateTime = NULL
DECLARE @Id int = NULL
我想在where子句中写一个条件,如...如果提供了fromDate,则必须在@fromDate上进行搜索。如果没有提供@fromDate,那么检查@Id变量,如果这不是null,则检查基于@Id ......
像...一样的东西。
where
CASE
when @fromDate is not null
THEN (@FromDate is null or ([Created] between @FromDate and @ToDate))
ELSE (@requestId is null or Id=@requestId)
以下解决方案存在一个问题...如果提供了@fromDate和@Id,那么这将完成它们的交叉并且没有任何返回.....条件应该是...如果@fromDate被给出即使提供了@Id,优先级也会给@fromDate,结果不能依赖于@Id参数....
答案 0 :(得分:1)
因为您依赖于这两个参数,所以两者在条件:
中使用它们where
(@FromDate is null or ([Created] between @FromDate and @ToDate))
or
((@requestId is null or Id=@requestId)
and @FromDate is null) ----mix @requestId & @FromDate
答案 1 :(得分:0)
WHERE [Created] BETWEEN
(CASE WHEN @FromDate IS NOT NULL THEN @FromDate ELSE [Created] END) AND
(CASE WHEN @ToDate IS NOT NULL THEN @ToDate ELSE [Created] END) AND
Id=(CASE WHEN @requestId IS NOT NULL THEN @requestId ELSE Id END)