1

This is my query:

"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})";

In {0} point, I want to insert a list of strings separated by ,.

is there a way to pass this list using some method, or something like that, or i'll have to create another string manually, eg. looping in a list?

Keng
  • 52,011
  • 32
  • 81
  • 111
guisantogui
  • 4,017
  • 9
  • 49
  • 93

3 Answers3

3

try this:

string.Format(sql, "'" + string.Join("', '", arrOfStrings) + "'")
kpull1
  • 1,623
  • 15
  • 19
2
var resultQuery = string.Format(query, 
                  string.Join(",", stringList.Select(x => 
                                     string.Format("'{0}'", x))));
Damith
  • 62,401
  • 13
  • 102
  • 153
1

Unfortunately, .NET DB libraries do not let you bind a single parameter to SQL's IN list.

If the strings that you bind to the IN list always come from inside your program and never from the user input, you can build the list directly, like this:

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

This would produce a string that looks like this:

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

However, if the strings 'a', 'b', 'c' come from the user, you need to parameterize your query to avoid SQL injection attacks, like this:

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

for the query that looks like this:

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

and bind the IN list parameters individually in a separate loop:

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

Note the use of NULL in the queries. They will never match anything, even in case work.tipo contains some NULLs. However, adding a NULL to the list lets you avoid syntax errors when the list of work types is empty: a query like this is valid, and it does not return anything:

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

This query, on the other hand, would trigger a syntax error:

... AND work.tipo IN ()
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523