[英]IN Operator in OLEDB
I am using OLEDB connection to read data from excel files. 我正在使用OLEDB连接从Excel文件读取数据。 I am facing issues while using IN operator in the Select query.
在Select查询中使用IN运算符时遇到问题。 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; 第二行针对3个数值测试
someval
; the first line tests someval
against a single string value that happens to contain numbers and commas (but those numbers and commas are irrelevant). 第一行针对碰巧包含数字和逗号的单个字符串值测试
someval
(但这些数字和逗号无关)。
You cannot do what you want without (one of): 没有以下一项,您将无法做自己想做的事情:
in (?,?,?,?)
in (?,?,?,?)
STRING_SPLIT
in recent versions of SQL Server (this will be very backend specific); STRING_SPLIT
(这将非常特定于后端); 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. IN
运算符需要一个值列表 ,但是您提供的一个值恰好包含一个列表。 You should create a different parameter for each value in the EmployeeIds list. 您应该为EmployeeIds列表中的每个值创建一个不同的参数。
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
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.