简体   繁体   中英

How to get a total number of rows in database table along with some rows using PostgreSQL function (to select with Dapper)?

I need to get a filtered set of rows from the PostgreSQL table along with a total number of records there. Previously I was writing raw SQL queries and all flow looked like this (taken from another answer):

var sql = @"SELECT COUNT(*) FROM books;
            SELECT * FROM books ORDER BY bookID OFFSET 1000 ROWS FETCH NEXT 10 ROWS ONLY";

using(var multi = connection.QueryMultiple(sql))
{
    var count = multi.Read<int>().Single();
    var results = multi.Read<YourObject>().ToList();
}

But we switched to PostgreSQL functions and now I need to get the same result with them. How is it possible?

  1. Should I just make another procedure and query it to get total values (seems inefficient)?
  2. Should I put multiple SELECT statements inside one function (but I don't need the same total value for each row of the results table)?

Are there other options?

UPDATE

Code above is an example of how I was working with this stuff. Now I have this function:

CREATE OR REPLACE FUNCTION get_books(offset_value integer, fetch_value integer)
RETURNS TABLE("BookId" uuid, "BookName" varchar)
 LANGUAGE sql
AS $function$
SELECT 
  id AS BookId,
  book_name AS BookName
FROM books
OFFSET offset_value ROWS FETCH NEXT fetch_value ROWS ONLY;
$function$
;

And C# code:

var result = await connection.QueryAsync<BookDto>("get_books", parameters, commandType: CommandType.StoredProcedure);

It works but I also need a total number of rows in my books table.

I honestly don't know that there would be any advantage of this, performance or otherwise, but you could combine the two into one query using the count analytic function:

select
  count (*) over (partition by 1), *
from books
limit 10

Your object would have to account for the additional field, and it would repeat on every record. For small datasets, who cares, but if you are storing a million list items then that's storing the same value one extra million times.

I actually think your original approach is preferred, as it retains the count in a scalar, but offering this as an idea.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM