因此,OLE DB .NET Provider不支持命名参数,是否有更好或更快速的方法来搜索多列?就像只使用一个参数一样?
cmd = new OleDbCommand("SELECT * FROM Table1 WHERE Column1 LIKE ? OR Column2 LIKE ? OR Column3 LIKE ? OR Column4 LIKE ? OR Column5 LIKE ? OR Column6 LIKE ? OR Column7 LIKE ? OR Column8 LIKE ? OR Column9 LIKE ? OR Column10 LIKE ? ", con);
cmd.Parameters.AddWithValue("@Column1", "%" + txtSearch.Text + "%");
cmd.Parameters.AddWithValue("@Column2", "%" + txtSearch.Text + "%");
cmd.Parameters.AddWithValue("@Column3", "%" + txtSearch.Text + "%");
cmd.Parameters.AddWithValue("@Column4", "%" + txtSearch.Text + "%");
cmd.Parameters.AddWithValue("@Column5", "%" + txtSearch.Text + "%");
cmd.Parameters.AddWithValue("@Column6", "%" + txtSearch.Text + "%");
cmd.Parameters.AddWithValue("@Column7", "%" + txtSearch.Text + "%");
cmd.Parameters.AddWithValue("@Column8", "%" + txtSearch.Text + "%");
cmd.Parameters.AddWithValue("@Column9", "%" + txtSearch.Text + "%");
cmd.Parameters.AddWithValue("@Column10", "%" + txtSearch.Text + "%");
如果我仅使用单个参数,则找不到第二个参数的值
答案 0 :(得分:0)
仅发送一次参数的一种方法是使用cross apply
:
// proper indentation makes for a more readable code
var sql = @"SELECT *
FROM Table1
CROSS APPLY
(
SELECT '%'+ ? +'%' As searchParam
) As s
WHERE Column1 LIKE searchParam
OR Column2 LIKE searchParam
OR Column3 LIKE searchParam
OR Column4 LIKE searchParam
OR Column5 LIKE searchParam
OR Column6 LIKE searchParam
OR Column7 LIKE searchParam
OR Column8 LIKE searchParam
OR Column9 LIKE searchParam
OR Column10 LIKE searchParam";
// OleDbCommand implements the IDisposable interface...
using (var cmd = new OleDbCommand(sql, con))
{
// use Add instead of AddWithValue
cmd.Parameters.Add("@searchParam", OleDbType.VarWChar).Value = txtSearch.Text;
con.Open();
// Execute command here
}
请阅读Can we stop using AddWithValue() already?,以了解为什么AddWithValue
是一个糟糕的主意。
请注意,这仍在使用非SARGable谓词搜索多个列,因此SQL Server不能在此处使用任何条件的索引查找。