Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return the result of a postgresql function in c#? Console output empty

I have the problem that i have a function in postgresql that calculates two integer and should return the result to the c# (npgsql) conosle and i don't know where my mistake is, because the debugger doesn't say anything to me which is helpful.

so first of all the code of c# and of the function.

                ...
            cmd.Parameters["x"].Value = 20;
            cmd.Parameters["y"].Value = 22;
            connection.Open();

            if (connection.State == System.Data.ConnectionState.Open) {
                //Console.WriteLine(cmd.Parameters["x"].Value);
                command.ExecuteNonQuery();
                Console.WriteLine(cmd.Parameters["sum"].Value);

            }

and now the code of the DB:

CREATE OR REPLACE FUNCTION t2(
    IN x integer,
    IN y integer,
    OUT sum integer)
  RETURNS integer AS
$BODY$BEGIN
    sum := x + y;
    INSERT INTO  t2 (x, y, sum) values (x, y, sum);
END

So when i try to run it,

Console.WriteLine(cmd.Parameters["sum"].Value);

will be empty and the ["sum"].Value is NULL. What am I doing wrong? Am I right, that when I say that "sum" is an OUT variable, I do not need a return?

Please help.

SOLVED, thank you to all! @Patrick gave me the right answer: use ExecuteScalar() instead of ExecuteNonQuery()

like image 798
Spedo De La Rossa Avatar asked Jul 06 '15 08:07

Spedo De La Rossa


People also ask

Can a PostgreSQL function return a table?

PostgreSQL returns a table with one column that holds the array of films. In practice, you often process each individual row before appending it in the function's result set. The following example illustrates the idea.

Can procedure return a value in PostgreSQL?

In case you want to return a value from a stored procedure, you can use output parameters. The final values of the output parameters will be returned to the caller.

Can PostgreSQL stored procedure return resultset?

You can call a PostgreSQL stored procedure and process a result set in a . NET application, for example, in C# application using Npgsql . NET data provider. Note that you do not need to know the name of the cursor to process the result set.


2 Answers

Instead of

command.ExecuteNonQuery();

you should call

Object res = command.ExecuteScalar();
Console.WriteLine(res);
like image 130
Patrick Avatar answered Oct 28 '22 11:10

Patrick


Did you try to run this code, for example, command.ExecuteNonQuery() ? Because you're reading a value without actually executing the query.

connection.Open();
command.ExecuteNonQuery();
int result = (int) cmd.Parameters["sum"].Value;
Console.WriteLine(result);
like image 41
Alex Zhukovskiy Avatar answered Oct 28 '22 10:10

Alex Zhukovskiy