首页 文章

如果在Where子句SQL中

提问于
浏览
0

我遇到了SQL查询的问题 . 我有一张10个字段的table . 我需要创建一个查询,它通过字段ProductionYear(int)在2个变量@startDate(int)和@endDate(int)之间获取日期 . 这两个变量都是不必要的 . 我需要在以下条件下构建sql查询:

If(@endDate = 0)
Select Id from MyTable where ProductionYear > @startDate
else
Select Id from MyTable where ProductionYear BETWEEN @startDate and @endDate.

如何使用以下条件构建查询?

2 回答

  • 2

    你可以尝试使用case

    Select Id from MyTable 
        where ProductionYear BETWEEN (case when @startDate>@endDate then @endDate
     else @startDate  end) and 
    (case when @startDate>@endDate then @startDate else @endDate end)
    
  • 0

    您可以将其合并到一个查询中:

    Select Id
    from MyTable
    where ProductionYear >= @startDate and
          (ProductionYear <= @endDate or @endDate = 0);
    

    您的两个查询在是否包含 @startDate 方面不一致 . BETWEEN 包含比较值,但 > 不包含 .

    如果你想 @startDate 也是可选的:

    Select Id
    from MyTable
    where (ProductionYear >= @startDate or @startDate = 0) and
          (ProductionYear <= @endDate or @endDate = 0);
    

    一些额外的评论 . 调用"year" a "date"令人困惑 . 您的参数可能应该被称为 @startYear@endYear .

    这些查询将导致对表进行全表扫描 . 这可能不是什么大问题,因为粒度是按年计算的 . 如果粒度更精确,您可能希望使用索引 . 在这种情况下,也许最好的方法是动态SQL .

相关问题