代码之家  ›  专栏  ›  技术社区  ›  Ejrr1085

如何在C中从Npgsql 4.1.5.0执行匿名块PL/pgSQL(PostgreSQL 13)#

  •  1
  • Ejrr1085  · 技术社区  · 5 年前

    我有一个匿名块PL/pgSQL:

    DO
    $$
    DECLARE secuencial INT;
    BEGIN   
        SELECT MAX("CodigoFactura") + 1 INTO secuencial FROM "Factura";
        IF secuencial IS NULL THEN
            secuencial := 1;
        END IF;
        RAISE NOTICE '%', secuencial;
    END;
    $$
    

    匿名块PL/pgSQL从Npgsql执行,如下所示:

    NpgsqlConnection npgsqlConnection = new NpgsqlConnection("Server=127.0.0.1;Port=5432;Database=myBase;User Id=user;Password=password;");
    npgsqlConnection.Open();
    string sentencialSQL = "DO $$ BEGIN SELECT MAX(\"CodigoFactura\") + 1 INTO :v_secuencial FROM \"Factura\"; IF :v_secuencial is NULL THEN :v_secuencial := 1; END IF; END; $$";
    NpgsqlCommand npgsqlCommand = new NpgsqlCommand(sentencialSQL, npgsqlConnection);
    // ===============================
    NpgsqlParameter npgsqlParameter1 = new NpgsqlParameter();
    npgsqlParameter1.ParameterName = ":v_secuencial";
    npgsqlParameter1.Value = 0;
    npgsqlParameter1.NpgsqlDbType = NpgsqlTypes.NpgsqlDbType.Integer;
    npgsqlParameter1.Direction = ParameterDirection.Output;
    npgsqlCommand.Parameters.Add(npgsqlParameter1);
    // ===============================
    npgsqlCommand.CommandType = CommandType.Text;
    npgsqlCommand.ExecuteNonQuery();
    npgsqlConnection.Close();
    

    我有一个错误:

    42601:或附近出现语法错误<<:>>

    0 回复  |  直到 5 年前
        1
  •  2
  •   Pavel Stehule    5 年前

    声明 DO 是不支持参数化的服务器端语句。不能将任何参数传递给 直接封锁。在这种情况下,您应该编写一个函数,或者只使用 COALESCE 功能:

    SELECT COALESCE(MAX("CodigoFactura") + 1, 1) INTO secuencial FROM "Factura";
    

    注意——在SQL中使用区分大小写的标识符是非常糟糕的模式(非常不切实际)。

        2
  •  0
  •   Ejrr1085    5 年前

    根据@Pavel Stehule的说法,这就是解决方案(如果有人需要完整的解决方案):

    NpgsqlConnection npgsqlConnection = new NpgsqlConnection("Server=127.0.0.1;Port=5432;Database=myBase;User Id=user;Password=password;");
    npgsqlConnection.Open();
    string sentencialSQL = "SELECT COALESCE(MAX(\"CodigoFactura\") + 1, 1) FROM \"Factura\";";
    NpgsqlCommand npgsqlCommand = new NpgsqlCommand(sentencialSQL, npgsqlConnection);
    // ===============================
    npgsqlCommand.CommandType = CommandType.Text;
    object secuencial = npgsqlCommand.ExecuteScalar();
    npgsqlConnection.Close();
    
    推荐文章