1

这是我的查询:

"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}分隔的字符串列表,

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

4

3 回答 3

3

尝试这个:

string.Format(sql, "'" + string.Join("', '", arrOfStrings) + "'")
于 2013-08-12T14:38:38.053 回答
2
var resultQuery = string.Format(query, 
                  string.Join(",", stringList.Select(x => 
                                     string.Format("'{0}'", x))));
于 2013-08-12T14:41:22.873 回答
1

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

如果绑定到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包含一些NULLs。但是,NULL当工作类型列表为空时,将 a 添加到列表中可以避免语法错误:这样的查询是有效的,并且它不会返回任何内容:

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

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

... AND work.tipo IN ()
于 2013-08-12T14:45:23.033 回答