【问题标题】:Optional query parameters in SQL ServerSQL Server 中的可选查询参数
【发布时间】:2013-05-13 23:59:42
【问题描述】:

我想使用下拉列表中的值从 SQL Server 数据库中获取数据。

我的查询是

select  Age,City,State,Caste,IncomeMin,IncomeMax from Ruser
where (Age between '" + drplistagemin.SelectedItem + "' and '" + drplistagemax.SelectedItem + "') 
and (Religion= '" + drplistreligion.SelectedItem + "')  ");

我需要了解的是,如果 Religion 下拉列表的值是可选的而不是强制的,如何构建此查询?

【问题讨论】:

  • SQL Injection alert - 您应该将您的 SQL 语句连接在一起 - 使用 参数化查询 来避免 SQL 注入

标签: sql sql-server drop-down-menu optional-parameters


【解决方案1】:

在@Pratik 的符号中:

SELECT Age,City,State,Caste,IncomeMin,IncomeMax
FROM Ruser
WHERE age BETWEEN @minAge AND @maxAge
AND religion = coalesce(@religion, religion);

【讨论】:

    【解决方案2】:

    一种方法是对宗教使用NULL 值,并将其转换为% 以在SQL Server 中进行LIKE 比较。

    另外 - 我总是将 UI 代码(事件处理程序等)与实际的数据库访问代码分开 - 所以在单独的 DataAccess 类中执行类似的操作(而不是将其直接粘贴到页面代码隐藏中) :

    public List<RuserResults> GetRuserResults(int minAge, int maxAge, string religion)
    {
        string selectStmt = "SELECT Age, City, State, Caste, IncomeMin, IncomeMax FROM Ruser " +
                            "WHERE Age BETWEEN @MinAge AND @MaxAge " + 
                            "AND Religion LIKE @religion";
    
        // set up your connection and command objects
        using(SqlConnection conn = new SqlConnection("--your-connection-string-here--"))
        using(SqlCommand cmd = new SqlCommand(selectStmt, conn))
        {
            // define the parameters
            cmd.Parameters.Add("@MinAge", SqlDbType.Int).Value = minAge;
            cmd.Parameters.Add("@MaxAge", SqlDbType.Int).Value = maxAge;
            cmd.Parameters.Add("@Religion", SqlDbType.VarChar, 100);
    
            // if you passed a value for the method parameter - use that value
            if(!string.IsNullOrEmpty(religion))
            {
               cmd.Parameters["@Religion"].Value = religion + "%";
            }
            else  // if no value was passed - just search for all religions
            {
               cmd.Parameters["@Religion"].Value = "%";
            }
    
            List<RuserResult> results = new List<RuserResult>();
    
            // open connection, run query, close connection
            conn.Open();
    
            using(SqlDataReader reader = cmd.ExecuteReader())
            {
               while(reader.Read())
               {
                   // read the values, convert to a "RuserResults", and pass it back
                   results.Add(ConvertReaderToRuserResult(reader));
               }
            }
    
            conn.Close();
    
            // return the results
            return results;
        }
    }
    

    然后从您的 ASP.NET 页面中,您可以调用它

    int minAge = Convert.ToInt32(drplistagemin.SelectedItem);
    int maxAge = Convert.ToInt32(drplistagemax.SelectedItem);
    string religion = drplistreligion.SelectedItem;
    
    List<RuserResult> results = GetRuserResults(minAge, maxAge, religion);
    
    // do something with the results returned here....
    

    【讨论】:

      【解决方案3】:

      我从不建议使用直接命令方法,但您可以尝试以下查询:

      SELECT Age,City,State,Caste,IncomeMin,IncomeMax
      FROM Ruser
      WHERE age BETWEEN @minAge AND @maxAge
      AND religion LIKE CASE WHEN @religonVal IS NULL THEN '%' ELSE @religonVal END;
      

      请注意:您可以对存储过程中的变量使用适当的值。让我知道它是否如您所愿。

      【讨论】:

      • 如果我只是从年龄下拉列表中选择年龄,那么它不起作用,
      • 只有当我同时选择下拉列表年龄和宗教时才有效
      • 你需要在前端c#,asp.net中调整参数选择,其中使用if else条件超过选择。在您的情况下,将NULL 作为宗教的默认值。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-15
      • 1970-01-01
      • 2011-04-08
      • 1970-01-01
      • 2012-06-21
      • 2010-09-24
      • 2011-08-13
      相关资源
      最近更新 更多