0

I have following query used by c# program:

var names = string.Join(",", activeNames.Select(n => string.Format("'{0}'", n)).ToArray());

var query = @"SELECT * FROM TableA WHERE NOT Name IN (" + names + ")";

The above query works as long as there is value in names like if name = 'Ken', 'John' this works. But if name is empty query looks like this:

SELECT * FROM TableA WHERE NOT Name IN () 

which is invalid syntax how can i make this query work?

I can use two seperate queries like: SELECT * FROM TableA //if name is empty

or above query if name has values. But is this right way to approch this?

4

4 回答 4

1

If Name is never empty, you could add an empty value to the IN clause:

@"SELECT * FROM TableA WHERE NOT Name IN (''," + names + ")";
于 2013-01-29T21:29:33.990 回答
1

Sure that'll work.

var query = @"SELECT * FROM TableA"
if(activeNames.length > 0)
  query += " WHERE NOT Name IN (" + names + ")";
于 2013-01-29T21:33:01.867 回答
0

You can just add validation for the value of the names variable.

string query = string.empty;

if (string.IsNullOrEmpty(names))
{
 query = "SELECT * FROM TableA";
}
else
{
 query = "SELECT * FROM TableA WHERE NOT Name IN ("....
}
于 2013-01-29T21:29:48.717 回答
0

Just use separate queries. Based on your information, there is no need to hack the WHERE-clause.

var query = @"SELECT * FROM TableA";
if (activeNames.Any()){
    var names = string.Join(",", activeNames
                                    .Select(n => string.Format("'{0}'", n))
                                    .ToArray());

    query += " WHERE NOT Name IN (" + names + ")";
}

But please, use parameterized queries! See this question on how to do this.

于 2013-01-29T21:36:47.187 回答