1

我有九个字符串,它们要么是 SQL 查询,要么只是空的 (""),具体取决于几个复选框的状态。我需要将它们组合在另一个字符串中,例如

string OP = "AND";
string query = "select * from table where " + string1 + OP + string2 + OP + string3 + OP + ... + " order by ID;"

问题是,在字符串之间,我需要一个AND或一个OR. 但如果任何字符串为空,它会给我一个 SQL 错误。SQL不理解类似的东西

select * from table where AND a = "adsf" AND AND AND z = "fghj" AND order by ID;

它必须看起来像这样:

select * from table where a = "adsf" AND z = "fghj" order by ID;
4

3 回答 3

1
字符串查询 =
   “从表中选择 *”
   + 字符串 1
   + String.IsNullOrEmpty(string2) ?" " : (OP + string2)
   + String.IsNullOrEmpty(string3) ?" " : (OP + string3)
   + ...
   + " 按 ID 排序;"
于 2012-09-15T16:38:11.080 回答
1

测试空

string query = "select * from table where " + 
String.IsNullOrEmpty(string1) ? "" : (string1+OP) + 
String.IsNullOrEmpty(string2) ? "" : (string2+OP) + 
...+
String.IsNullOrEmpty(string9) ? "" : string9;


//in case your string ends with AND which will if `string9` is empty
if (query.EndsWith("AND"))
{
    int andIndex = query.LastIndexOf("AND");
    query = query.Substring(0, andIndex);
}

query = query + " order by ID;"
于 2012-09-15T16:39:03.020 回答
1

您可以将字符串放入数组中,删除空字符串,然后使用以下方法组合它们Join

string[] conditions = new string[] {
  string1,
  string2,
  string3,
  string4
};

string op = " and ";
string query =
  "select * from table where " +
  String.Join(op, conditions.Where(c => c.Length > 0)) +
  "select * from table where ";

对于框架 3.5 更改为:

  String.Join(op, conditions.Where(c => c.Length > 0).ToArray()) +
于 2012-09-15T16:44:12.087 回答