在SQL Server中按多列搜索

时间:2017-02-06 06:38:51

标签: sql sql-server stored-procedures

假设我有下表:

enter image description here

我的期望是:

  1. 如果我什么都不搜索,它将返回表格的所有行。

  2. 如果我搜索---' sr' ' m',' ap',' null' ---它只返回第一行

  3. 如果我搜索---' null',' m',' ap',' null' ---它只返回前两行

  4. 如果我搜索---' null',' m',' null',' null' ---它只返回前三行

  5. 如果我搜索---' null',' m',' TN''零' ---它只返回第三行

  6. 请帮助

2 个答案:

答案 0 :(得分:1)

尝试以下查询:

DECLARE @name VARCHAR(100) = 'Sree',
        @city VARCHAR(100),
        @state VARCHAR(100)

;WITH test_table([name], city, state, country) AS
(
    SELECT 'Sree','mm','ap','ind' UNION ALL
    SELECT 'xxx','mm','ap','ind' UNION ALL
    SELECT 'abcd','mm','tn','ind' UNION ALL
    SELECT 'wer','dd','ap','ind' 
)
SELECT * 
FROM test_table AS t
WHERE t.name = ISNULL(NULLIF(@name, ''), t.name)
  AND t.city = ISNULL(NULLIF(@city, ''), t.city)
  AND t.state = ISNULL(NULLIF(@state, ''), t.state)

答案 1 :(得分:0)

假设你的输入是变量p_name,p_city和p_state,你可以用case来做条件过滤

Select *
From t
Where
Name = case when @p_name = '' then name else @p_name end
And city = case when @p_city = '' then city else @p_city end
And state = case when @p_state = '' then name else @p_state end;

要在变量中处理null,您可以使用:

Nullif(@var, '') is null