我希望在C#中对access数据库中的多个列执行搜索。数据是按行构建的,每一列都包含相关数据或作为通配符的"*“。
因此,作为一个粗略的例子:
如果我有福特,嘉年华,*,1998年的数据,那么如果我有一个值.
福特,嘉年华,汽油,1998年
它将查找并显示这一行数据。
目前,我正在努力:
string sql = "SELECT * FROM [mydatabase]
WHERE Manufacturer ='" + textBox1.Text +
"' OR Manufacturer='*' AND Model ='" + textBox2.Text +
"' OR Model='*' AND Fuel ='" + textBox3.Text +
"' OR Fuel='*' AND Year='" + textBox4.Text + "' OR Year='*'";但这将带来所有的价值,而不是将它们过滤掉。是否有一种在查询中使用and / OR而不是OR的方法?
发布于 2015-05-18 10:48:36
如果你想用外卡,我就把它排除在where条款之外。
另外,如果要将所有列作为一个字符串搜索,可以将它们全部添加到select列表中的新列中。
例如:
public void GetCars(string manufacturer, string model, string fuel, DateTime? year, string searchString)
{
string query = @"
SELECT *,
ISNULL([Manufacturer],'') + ' ' + ISNULL([Model],'') + ' ' ISNULL([Fuel],'') + ' ' ISNULL('Year', '') AS [SearchString]
FROM [MyDatabase]
WHERE [Manufacturer]=@Manufacturer ";
if (!String.IsNullOrEmpty(model))
query += @"AND [Model]=@Model ";
if (!String.IsNullOrEmpty(fuel))
query += "AND [Fuel]=@Fuel ";
if (year.HasValue)
query += "AND [Year]=@Year ";
if (!String.IsNullOrEmpty(searchString))
query += @"AND [SearchString] Like '%@SearchString%' ";
using (SqlCommand sqlCommand = new SqlCommand(query))
{
sqlCommand.Parameters.AddWithValue("@Manufacturer", manufacturer);
if (!String.IsNullOrEmpty(model))
sqlCommand.Parameters.AddWithValue("@Model", model);
if (!String.IsNullOrEmpty(fuel))
sqlCommand.Parameters.AddWithValue("@Fuel", fuel);
if (year.HasValue)
sqlCommand.Parameters.AddWithValue("@Year", year.Value);
if (!String.IsNullOrEmpty(searchString))
sqlCommand.Parameters.AddWithValue("@SearchString", searchString);
//Execute to data table etc
}
}发布于 2015-05-18 10:10:32
而不是Manufacturer ='" + textBox1.Text + "' OR Manufacturer='*',您可以使用coalesce,这是一种if/else
string sql = "... Manufacturer = coalesce('" + textBox1.Text + "', '*') ...";这样,您只需要ands,而不是与or混合。这可能是现在出现的问题,因为or会导致and不被评估。
您还可以在and周围添加括号,因此or将仅在括号内应用:
string sql = "... where (Manufacturer ='" + textBox1.Text + "' OR Manufacturer='*') and ...";注意,您应该使用 参数化查询,这样您就可以得到如下内容:
command.CommandText = "select * from ... where Manufacturer = coalesce(@mgr, '*') and ...";
command.Parameters.Add(new SqlParameter("mgr", textBox1.Text));https://stackoverflow.com/questions/30300301
复制相似问题