NpgsqlParameter - 多个值

时间:2012-10-29 15:04:39

标签: c#-4.0 npgsql

代码:

string sqlCommand = @"UPDATE table SET active = 0 WHERE id IN (@CommaSeparatedId)";
string sqlParamName = "CommaSeparatedId";
string sqlParamValue = "111, 222";

try
{
    using (NpgsqlConnection connection = new NpgsqlConnection())
    {
        // Get connection string from Web.config
        connection.ConnectionString = _connectionString;
        connection.Open();
        Int32 rowsAffected;

        using (NpgsqlCommand command = new NpgsqlCommand(sqlCommand, connection))
        {
            NpgsqlParameter sqlParam = new NpgsqlParameter(sqlParamName, NpgsqlTypes.NpgsqlDbType.Varchar);
            // Code below no exception occur, and active not updated to 0
            // sqlParam.Value = sqlParamValue;

            // This code works for only one value
            sqlParam.Value = "111";

            command.Parameters.Add(sqlParam);
            rowsAffected = command.ExecuteNonQuery();
        }
    }
}
catch (NpgsqlException pgEx)
{
    throw pgEx;
}

问题是:

如果我使用111, 222作为sqlParam.Value' rowsAffected = 0 , but if I'm using only 111 or 222 rowsAffected = 1`。这意味着只有1个值才能成功更新,但如果尝试更新超过1个值则会失败。


预期查询:

UPDATE table
    SET active = 0
WHERE id IN ('111', '222');

我在上面的代码中缺少什么?

1 个答案:

答案 0 :(得分:2)

您遇到的问题是由于数据库引擎将看到参数值“111,222”而不是两个不同的值,而是一个。
数据库搜索ID =“111,222”的记录,找不到与请求匹配的内容 您应该尝试使用存储过程并根据PostgreSQL

所需的语法执行Dynamic SQL