简体   繁体   中英

SQL check if next row doesn't exist

I have an MsSQL server and what I am doing is selecting rows from the table. Currently I have two rows so I was wondering how would I check if there are no other rows after second one without making another query?

For example

table users

id    name    pass

1     joe     123

2     bob     abc

How would I check if there is no row after 2 with just a query? I am willing to combining it with my current query, which just selects the data.

You can return the number of rows in your query as another column:

SELECT id, name, pass, count(*) over () as rows
FROM users

Keep in mind that this is telling you the number of rows returned by the query, not the number of rows in the table. However, if you specify a "TOP n" in your select, the rows column will give you the number of rows that would have been returned if you didn't have "Top n"

If you're trying to paginate the trick is to query one more record than you actually need for the current page. By counting the result ( mysql_num_rows ) and comparing that to your page size, you can then decide if there is a 'next page'.

If you were using mysql you could also use SQL_CALC_FOUND_ROWS() in your query, which calculates the number of rows that would be returned without the LIMIT clause. Maybe there is an equivalent for that in MsSQL?

I assume that you are inserting manually the first 2 rows of your table.

According to that, my idea is to just do a select where the id is more than 2 like this:

SELECT * FROM users WHERE id > 2;

I also assume that you are using PHP so mysql_num_rows will return you 0 if no data is found, otherwise it will return you the number of rows from your query and now you know that you need to do a while or some loop to retrieve the data after id number 2.

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