What is the SQL equivalent of the .Skip()
method in LINQ?
For example: I would like to select rows 1000-1100 from a specific database table.
Is this possible with just SQL? Or do I need to select the entire table, then find the rows in memory? I'd ideally like to avoid this, if possible, since the table can be quite large.
7条答案
按热度按时间z9ju0rcb1#
SQL Server 2012 and above have added this syntax:
gfttwv5a2#
In SQL Server 2005 and above you can use ROW_NUMBER function. eg.
euoag5mw3#
LINQ to SQL does this by using a ROW_NUMBER windowing function:
This works, but the need to manufacture the row_number from the ORDER BY may result in your query being sorted on the server side and cause performance problems. Even when an index can satisfy the ORDER BY requirement, the query still has to count 1000 rows before startting to return results. All too often developers forget this and just throw a pagination control over a 5 mil rows table and wonder why the first page is returned so much faster than the last one...
None the less, using ROW_NUMBER() is probably the best balance between ease of use and good performance, provided you make sure you avoid the sort (the ORDER BY condition can be satisified by an index).
vdgimpew4#
Try this one:
Example:
rwqw0loc5#
Do this:
Run .Skip(1000).Take(100) on a LINQ to SQL datacontext and look at the SQL output. It will generate a SQL statement for you that does what you're describing.
It won't be as elegant but it gets the job done.
b4qexyjb6#
No, but you could emulate MySQL's LIMIT clause (Stack Overflow link) to achieve the same result.
vwhgwdsa7#
Linqpad also has a SQL view you could use to get the SQL: