我正在尝试查询现有的访问数据库,并允许用户为WHERE子句选择多个值.我一直在使用此网站上的代码由用户Mark Brackett提供:
string[] tags = new string[] { "ruby","rails","scruffy","rubyonrails" }; string cmdText = "SELECT * FROM Tags WHERE Name IN ({0})"; string[] paramNames = tags.Select( (s,i) => "@tag" + i.ToString() ).ToArray(); string inClause = string.Join(",",paramNames); using (sqlCommand cmd = new sqlCommand(string.Format(cmdText,inClause))) { for(int i = 0; i < paramNames.Length; i++) { cmd.Parameters.AddWithValue(paramNames[i],tags[i]); } }
这给了这个:
cmd.CommandText = "SELECT * FROM Tags WHERE Name IN (@tag0,@tag1,@tag2,@tag3)" cmd.Parameters["@tag0"] = "ruby" cmd.Parameters["@tag1"] = "rails" cmd.Parameters["@tag2"] = "scruffy" cmd.Parameters["@tag3"] = "rubyonrails"
这非常有效,但我也想要以下功能.如果用户决定不输入任何值(在此示例中,如果tags数组为空),则我希望返回所有结果.实际上只是一个SELECT * FROM标签.
解决方法
怎么样的
string[] tags = new string[] { "ruby","rubyonrails" }; string cmdText = "SELECT * FROM Tags {0}"; string[] paramNames = tags.Select( (s,i) => "@tag" + i.ToString() ).ToArray(); string cmdWhere = paramNames.Length > 0 ? String.Format("WHERE Name IN ({0})",string.Join(",paramNames)) : ""; using (sqlCommand cmd = new sqlCommand(string.Format(cmdText,cmdWhere))) { for (int i = 0; i < paramNames.Length; i++) { cmd.Parameters.AddWithValue(paramNames[i],tags[i]); } }
因此,如果没有参数,则最后不添加where子句.