With Shay's help, I figured out how we can fetch cursor in v3.x after removal of "dereferenced" feature.
I think there are not much of good example on this, I hope this might help people save time to search example.
You can do this in npgsql ver3.x
1. CommandType.StoredProcedure (cursor name not defined)
conn.Open();
NpgsqlTransaction tran = conn.BeginTransaction();
NpgsqlCommand command = new NpgsqlCommand("show_cities", conn);
command.CommandType = CommandType.StoredProcedure;
command.ExecuteNonQuery();
command.CommandText = "fetch all in "<unnamed portal 1>"";
command.CommandType = CommandType.Text;
NpgsqlDataReader dr = command.ExecuteReader();
while (dr.Read())
{
// do what you want with data, convert this to json or...
Console.WriteLine(dr[0]);
}
dr.Close();
tran.Commit();
conn.Close();
2. CommandType.StoredProcedure (cursor name defined)
conn.Open();
NpgsqlTransaction tran = conn.BeginTransaction();
NpgsqlCommand command = new NpgsqlCommand("select show_cities(@ref)", conn);
command.CommandType = CommandType.Text;
NpgsqlParameter p = new NpgsqlParameter();
p.ParameterName = "@ref";
p.NpgsqlDbType = NpgsqlTypes.NpgsqlDbType.Refcursor;
p.Direction = ParameterDirection.InputOutput;
p.Value = "ref";
command.Parameters.Add(p);
command.ExecuteNonQuery();
command.CommandText = "fetch all in "ref"";
command.CommandType = CommandType.Text;
NpgsqlDataReader dr = command.ExecuteReader();
while (dr.Read())
{
// do what you want with data, convert this to json or...
Console.WriteLine(dr[0]);
}
dr.Close();
tran.Commit();
conn.Close();
3. CommandType.Text (cursor name defined)
conn.Open();
NpgsqlTransaction tran = conn.BeginTransaction();
NpgsqlCommand command = new NpgsqlCommand("select show_cities(@ref)", conn);
command.CommandType = CommandType.Text;
NpgsqlParameter p = new NpgsqlParameter();
p.ParameterName = "@ref";
p.NpgsqlDbType = NpgsqlTypes.NpgsqlDbType.Refcursor;
p.Direction = ParameterDirection.InputOutput;
p.Value = "ref";
command.Parameters.Add(p);
command.ExecuteNonQuery();
command.CommandText = "fetch all in "ref"";
command.CommandType = CommandType.Text;
NpgsqlDataReader dr = command.ExecuteReader();
while (dr.Read())
{
// do what you want with data, convert this to json or...
Console.WriteLine(dr[0]);
}
dr.Close();
tran.Commit();
conn.Close();
(reference for v2.x) http://www.sqlines.com/postgresql/npgsql_cs_result_sets
This is example for easy understanding, so if you want your function to return single result set, then instead of returning cursor
, please consider it to return table
as @Shay suggested or create a view
not a function
as @CeOnSql suggested.
Thanks !
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…