Thursday, 6 November 2014

Skip and Take record from 'N' to 'M' in SQL Sever

Hi Guys! In last weekend I was thinking let's write something on SQL Server database. So I was just thinking which topics should I covered or on which topics should I write...... thinking......thinking...., suddenly I got an idea lets write on some common questions or something which will more efficient during ours interviews or related to our project. So I've decided let's write on  "How to skip N to M records during table record selection?", I think this is very common question., So let's see how to do that in SQL Server database. 

Scenario: Suppose that, I've a table ABC and this table having following records,

Table: ABC
Id          Name       Address
1           Peter          XYZ
2           John           PQR
3           Scott B'u     CBT
4          Allen           123-TPO
5          Belly           986-PYT


So here question is Do we select 2 rows starting from 3rd row?

Solution:  I think the most elegant is to use the ROW_NUMBER function to resolve this problem.

WITH NumberedMyTable AS
(
    SELECT
        Id,
        Value,
        ROW_NUMBER() OVER (ORDER BY Id) AS RowNumber
    FROM
        MyTable
)
SELECT
    Id,
    Value
FROM
    NumberedMyTable
WHERE
    RowNumber BETWEEN @From AND @To
So in this way you can resolve this problem. Please feel free comment for 
any assistance or query.

No comments:

Post a Comment