使用动态值搜索多个参数

时间:2016-01-19 08:54:25

标签: c# asp.net sql-server

我正在搜索4个参数而没有必填字段 参数是

  1. 婚姻状况
  2. 性别
  3. 根据选择,我得到像这样的SQL查询

    select * from UserTable 
    where Gender='Male' AND City='' AND MaritalStatus='Single' AND Groups =''
    

    它返回0行,因为参数City=''Groups =''与标准不匹配。

    有没有办法实现这一点,而无需在多个组合中检查null。我使用MSSQL2012作为我的数据库和Asp.Net C#

    我的方法如下

    private void GetSearchResults(string city, string MaritalStatus, string Gender, string Groups)
    {
        var qry="select * from UserTable 
        where Gender='"+Gender+"' AND City='"+city+"' AND MaritalStatus='"+MaritalStatus+"' AND Groups ='"+Groups+"'";
    }
    

    我的选择组=''意味着我不想在Group

    上进行任何过滤

2 个答案:

答案 0 :(得分:1)

select * from UserTable where Gender='Male' AND City IS NULL AND MaritalStatus='Single' AND Groups IS NULL

答案 1 :(得分:1)

假设您有以下参数

@Gender = 'Male',
@City = '',
@MaritalStatus = 'Married'
@Groups = ''

你的sql看起来像。

select * from UserTable 
where 
(Gender = @Gender OR ISNULL (@Gender, '') = '')
AND (City = @City OR ISNULL (@City, '') = '')
AND (MaritalStatus = @MaritalStatus OR ISNULL (@MaritalStatus, '') = '')
AND (Groups = @Groups OR ISNULL (@Groups, '') = '')