连接可变数量的字符串

时间:2013-08-12 14:34:48

标签: c# sql string concatenation

这是我的疑问:

"select cli.FANTASIA, dbsmp.VEICULO_PLACA, dbsmp.DTINICIOPREV, dbsmp.DTFIMPREV," +
                                                    " dbsmp.DTINICIOREAL, dbsmp.DTFIMREAL,dbsmp.CIDADE_DES,dbsmp.CIDADE_ORI, work.STATUS," +
                                                    " dbsmp.REF1 FROM dbsmp_work work inner join dbsmp "+ 
                                                    " on work.ID_SMP = dbsmp.ID_SMP inner join dbcliente cli "+
                                                    " on dbsmp.ID_CLIENTE = cli.ID_CLIENTE inner join dbSMP_MOTORISTA mot "+
                                                    " on dbsmp.ID_SMP = mot.ID_SMP where dbsmp.ID_CLIENTE = @IDCLIENTE "+
                                                    " and work.STATUS in('F') and work.tipo in ({0})";

{0}点,我想插入由,分隔的字符串列表。

有没有办法使用某种方法传递此列表,或类似的东西,或者我必须手动创建另一个字符串,例如。在列表中循环?

3 个答案:

答案 0 :(得分:3)

试试这个:

string.Format(sql, "'" + string.Join("', '", arrOfStrings) + "'")

答案 1 :(得分:2)

var resultQuery = string.Format(query, 
                  string.Join(",", stringList.Select(x => 
                                     string.Format("'{0}'", x))));

答案 2 :(得分:1)

不幸的是,.NET DB库不允许您将单个参数绑定到SQL的IN列表。

如果绑定到IN列表的字符串总是来自程序内部,而不是来自用户输入,则可以直接构建列表,如下所示:

string query = String.Format(
    @"... AND work.tipo in (null, {0})"
,   string.Join(", ", tipiDiLavoro.Select(t => string.Format("'{0}'", t)))
);

这将生成一个如下所示的字符串:

AND work.tipo in (null, 'a', 'b', 'c')

但是,如果字符串'a', 'b', 'c'来自用户,则需要参数化查询以避免SQL注入攻击,如下所示:

string query = String.Format(
    @"... AND work.tipo in (null, {0})"
,   string.Join(", ", tipiDiLavoro.Select((t,i) => string.Format("@param{0}", i)))
);

用于如下所示的查询:

AND work.tipo in (null, @param0, @param1, @param2)

并在单独的循环中单独绑定IN列表参数:

int pos = 0;
foreach (var code in tipiDiLavoro) {
    cmd.SetParamValue("@param"+pos, code);
    pos++;
}

请注意在查询中使用NULL。它们永远不会匹配任何内容,即使work.tipo包含一些NULL s。但是,在列表中添加NULL可以避免在工作类型列表为空时出现语法错误:这样的查询是有效的,并且不会返回任何内容:

... AND work.tipo IN (NULL) -- expanded from an empty list

另一方面,此查询会触发语法错误:

... AND work.tipo IN ()