简体   繁体   中英

IN Operator in OLEDB

I am using OLEDB connection to read data from excel files. I am facing issues while using IN operator in the Select query. Below is my query,

string EmployeeIds = "'1231','1232','1233'";
SELECT [Employee Number],[Employee Name],[First In Time],[Last Out Time],[Total Work Hours] 
FROM [Sheet0$A2:J] 
WHERE  [Employee Number] IN (?);

 comm.Parameters.AddWithValue("?",EmployeeIds);

I am getting empty results but if I give only single value then I am getting result. Please help.

where someval in ('123,456,789')

is very different to:

where someval in (123,456,789)

The second line tests someval against 3 numeric values; the first line tests someval against a single string value that happens to contain numbers and commas (but those numbers and commas are irrelevant).

You cannot do what you want without (one of):

  • writing the SQL dynamically to have one parameter per value, ie in (?,?,?,?)
  • making use of some feature of the backend to do the split - for example STRING_SPLIT in recent versions of SQL Server (this will be very backend specific); I do not know enough about Excel to advise on whether such a feature exists

This is a very common mistake.
The IN operator expect a list of values , but you are supplying a single value that happens to contain a list. You should create a different parameter for each value in the EmployeeIds list.

Here is one way to do it:

string EmployeeIds = "'1231','1232','1233'";
var values = EmployeeIds.Split(',');

using(var command = new OleDbCommand())
{
    var sql = "SELECT [Employee Number], [Employee Name], [First In Time], [Last Out Time], [Total Work Hours] "+
              "FROM [Sheet0$A2:J] "+
              "WHERE [Employee Number] IN (";

    for(int i=0; i < values.Length; i++) 
    {
        // Please note that string interpolation will work only with c# 6 or later.
        // If you are working with vs 2013 or earlier, use string.Format instead.
        sql = $"{sql} @{i},";
        command.Parameters.Add($"@{i}", OleDbType.Int).Value = values[i].Trim(new char[] {'}); // You don't need the ' anymore since you are working with parameters now...
    }

    command.CommandText = sql.TrimEnd(',') +");";
    command.Connection = con;
    using(var reader = Command.ExecuteReader())
    {
        while(reader.Read())
        {
            // do your stuff with the data
        }

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM