1

コード:

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;
}

問題は:

をrowsAffected = 0 111 222 rowsAffected = 1`111, 222として使用している場合。つまり、値が 1 つしかない場合は更新に成功しますが、複数の値を更新しようとすると失敗します。sqlParam.Value', but if I'm using onlyor


予期されるクエリ:

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

上記のコードで何が欠けていますか?

4

1 に答える 1

2

あなたが直面している問題は、パラメータ値「111,222」がデータベース エンジンによって 2 つの異なる値ではなく 1 つとして認識されるという事実によるものです。
データベースは ID = "111,222" のレコードを検索しますが、要求に一致するレコードは見つかりません。
ストアド プロシージャを使用して、PostgreSQL で必要な構文に従って動的 SQLを実行してみてください。

于 2012-10-29T15:16:26.393 に答える