使用可选参数搜索范围

时间:2019-01-03 22:25:33

标签: sql-server case

我正在从具有多个参数的SQL Server检索数据。在此示例中,名字,姓氏和年龄。我需要在一定年龄范围内进行搜索。例如,我需要按名字搜索,并且FromAge为> = 5,ToAge为<=20。我似乎无法弄清楚如何使用case语句搜索范围。

这是我尝试过的:

SELECT *
FROM MyTable
WHERE (FirstName = CASE WHEN @FirstName = '' THEN FirstName ELSE @FirstName 
END)
AND (LastName = CASE WHEN @LastName = '' THEN LastName ELSE @LastName END)
AND (AGE = CASE WHEN @AgeFrom = '' AND @AgeTo = '' THEN AGE ELSE AGE >= 
@AgeFrom AND AGE <= @AgeTo END)

我应该能够按范围搜索“年龄”字段,或者,如果没有提供有关年龄的数据,则不要按年龄搜索。

3 个答案:

答案 0 :(得分:0)

case语句只能返回一个值,而不是条件。因此,您必须照此构建自己的逻辑。但是,对于您而言,我认为简单的and/or逻辑就能完成您所追求的目标:

select *
from MyTable
where (coalesce(@FirstName,'') = '' or FirstName = @FirstName)
AND (coalesce(@LastName,'') = '' or LastName = @LastName)
AND (
  coalesce(@AgeFrom,'') = ''
  or coalesce(@AgeTo,'') = ''
  or (AGE >= @AgeFrom and AGE <= @AgeTo)
)

答案 1 :(得分:0)

您是否正在尝试做类似的事情

SELECT *
FROM MyTable
WHERE (LEN(@FirstName) = 0 OR FirstName = @FirstName)
       AND
      (
        (@AgeFrom IS NULL AND @AgeTo IS NULL)
        OR
        (Age BETWEEN @AgeFrom AND @AgeTo)
      )

使用字符串作为日期不是一个好主意,而是使用DATE数据类型并检查NULLDATE可以是NULL或具有日期,因此,如果将''分配给日期,则结果不是'',而是01/01/1900

答案 2 :(得分:0)

这将允许您指定最小年龄而不指定最大年龄,反之亦然:

SELECT *
FROM MyTable
WHERE 
    (nullif(@FirstName, '') is null or FirstName = @FirstName)
AND (nullif(@LastName, '') is null or LastName = @LastName)
AND (nullif(@AgeFrom, '') is null or AGE >= @AgeFrom)
AND (nullif(@AgeTo, '') is null or AGE <= @AgeTo)

或者,一个更紧凑的版本:

SELECT *
FROM MyTable
WHERE FirstName = isnull(nullif(@FirstName, ''), FirstName) -- might not perform as well as first example
AND LastName = isnull(nullif(@LastName, ''), LastName)      
AND AGE between isnull(nullif(@AgeFrom, ''), AGE)           -- performance hit will be less or even negligible if Age is a numeric type
            AND isnull(nullif(@AgeTo, ''), AGE)     

您的“年龄”列以及2个“年龄”参数实际上应该是数字类型。