就个人而言,我倾向于使用Lasse V. Karlsen的方法,尽管我有一个应用程序,我使用动态 SQL 根据用户想要做的事情生成更有效的查询(即,尽可能减少连接侥幸逃脱)。如果您真的对动态 SQL 有心,您可以使用三元运算符进行更好的查询:
string search = Request("search").IsEmpty() ? "" : Request("search");
decimal price = Request("price").IsEmpty() ? "" : Request("price");
string param3 = Request("param3").IsEmpty() ? "" : Request("param3");
string param4 = Request("param4").IsEmpty() ? "" : Request("param4");
string param5 = Request("param5").IsEmpty() ? "" : Request("param5");
string param6 = Request("param6").IsEmpty() ? "" : Request("param6");
string whereClause = "";
whereClause += whereClause.length > 0 & search.length > 0 ? " AND item_name LIKE '%' + @search + '%'" : "WHERE item_name LIKE '%' + @search + '%'";
whereClause += whereClause.length > 0 & search.length > 0 ? " AND item_price < @price" : "WHERE item_price < @price";
whereClause += whereClause.length > 0 & search.length > 0 ? " AND param3 = @param3" : "WHERE param3 = @param3";
whereClause += whereClause.length > 0 & search.length > 0 ? " AND param4 = @param4" : "WHERE param4 = @param4";
whereClause += whereClause.length > 0 & search.length > 0 ? " AND param5 = @param5" : "WHERE param5 = @param5";
whereClause += whereClause.length > 0 & search.length > 0 ? " AND param6 = @param6" : "WHERE param6 = @param6";
string sql = "SELECT * from Items " + whereClause;
SqlConnection conn = new SqlConnection("your connection string");
SqlCommand cmd = new SqlCommand(sql, conn);
// fill in all parameters (even ones that may not exist)
cmd.Parameters.Add("search", SqlDbType.VarChar, 50).Value = search;
cmd.Parameters.Add("price", SqlDbType.Float).Value = price;
cmd.Parameters.Add("param3", SqlDbType.VarChar, 50).Value = param3;
cmd.Parameters.Add("param4", SqlDbType.VarChar, 50).Value = param4;
cmd.Parameters.Add("param5", SqlDbType.VarChar, 50).Value = param5;
cmd.Parameters.Add("param6", SqlDbType.VarChar, 50).Value = param6;