如何在 C# 中从 Npgsql 4.1.5.0 执行匿名块 PL/pgSQL (PostgreSQL 13) [英] How to execute Anonymous Block PL/pgSQL (PostgreSQL 13) from Npgsql 4.1.5.0 in C#

查看:76
本文介绍了如何在 C# 中从 Npgsql 4.1.5.0 执行匿名块 PL/pgSQL (PostgreSQL 13)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个匿名块 PL/pgSQL:

I have this anonymous block 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 执行如下:

The anonymous block PL/pgSQL execute from Npgsql like this:

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:在 <<:>>

42601: syntax error at or near <<:>>

推荐答案

语句 DO 是不支持参数化的服务器端语句.您不能直接将任何参数传递给 DO 块.对于这种情况,您应该编写一个函数或仅使用 COALESCE 函数:

The statement DO is server side statement that doesn't support parametrisation. You cannot pass any parameters to DO block directly. For this case you should to write a function or just use a COALESCE function:

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

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

Attention - using case sensitive identifiers in SQL is pretty bad pattern (very impractical).

这篇关于如何在 C# 中从 Npgsql 4.1.5.0 执行匿名块 PL/pgSQL (PostgreSQL 13)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆