访问参数化的IN()查询

时间:2017-10-02 18:54:32

标签: c# sql ms-access parameters parameter-passing

我正在尝试运行此查询:

SELECT * FROM Tabela1 WHERE Pole1 IN (@parameter)

当窗口带"选择值"我出现了:" 10,50"我收到0行(应该是2行)。

当我只放" 10"或者只是" 50"它可以工作并为每个查询返回1行。

我正在使用Access 2013 - 我做错了什么?

using (DbConnection connection = new T())
            {
                connection.ConnectionString = query.DatabaseConnection.ConnectionString;
                using (DbCommand command = connection.CreateCommand())
                {
                    command.CommandText = query.QuerySql.Sql;
                    command.CommandType = CommandType.Text;
                    command.CommandTimeout = query.QuerySql.CommandTimeout;

                    if (query.QuerySql.Parameters != null)
                    {
                        foreach (var parameter in query.QuerySql.Parameters)
                        {
                            var commandParameter = command.CreateParameter();
                            commandParameter.ParameterName = $"@{parameter.Name}";
                            commandParameter.Value = parameter.Value;
                            command.Parameters.Add(commandParameter);
                        }
                    }

我创建了这样的查询:

QuerySql sql = new QuerySql("SELECT * FROM Tabela1 WHERE Pole1 IN(@parameter)", new List<ISqlParameter>()
        {
            new SqlMultiNumberParameter("parameter", new List<string>() { "10", "50" }, "Test parameter")
        });

parameter.Value返回类似的字符串:&#34; 10,50&#34;

祝你好运

迈克尔

1 个答案:

答案 0 :(得分:1)

您不能使用单个参数来表示要传递给IN子句的值列表。有一些ORM(例如Dapper)允许您传递值列表并为您构建正确的IN子句。

如果你想做同样的事情,你需要像这种方法

public OleDbCommand GetPoles(List<int> polesID)
{
    // Base text of the query
    string cmdText = @"SELECT * FROM TABLE1 WHERE Pole1 IN(";

    // where we store the 'name' of the parameters. (OleDb doesn't care)
    List<string> inClause = new List<string>();

    // where we store the parameters and their values
    List<OleDbParameter> parameters = new List<OleDbParameter>();
    foreach(int id in polesID)
    {
        // Add a placeholder for the parameter
        inClause.Add("?");

        // Build the parameter and store it away
        OleDbParameter p = new OleDbParameter("p" + id.ToString(), OleDbType.Integer);
        p.Value = id;
        parameters.Add(p);
    }

    OleDbCommand cmd = new OleDbCommand();

    // Build the command text: IN(?,?,?). A ? placeholder for each parameter
    cmd.CommandText = cmdText + string.Join(",", inClause.ToArray()) + ")";

    // pass all the parameters to the command and return it
    cmd.Parameters.AddRange(parameters.ToArray());
    return cmd;
}

现在您只需设置连接即可执行命令

相关问题