Tuesday, September 20, 2016

New T-SQL features in SQL Server 2012 – OFFSET and FETCH clause

The OFFSET-FETCH clause provides you with an option to fetch only a window or page of results from the result set.

Note:OFFSET-FETCH can be used only with the ORDER BY clause.

Syntax:  
    
syntax for exclude n number of row from the result set:

                SELECT column_names 
                FROM table_name
               ORDER BY column_names
               OFFSET n ROWS

Syntax for exclude first n records and return only the next m records:

                 SELECT column_names 
                FROM table_name
               ORDER BY column_names
               OFFSET n ROWS
               FETCH NEXT m ROWS ONLY

For examples: use emp table to excluded first 2 sorted employee number getting remaining row 

             SELECT * FROM EMP
             ORDER BY empno
             OFFSET 2 ROWS 

example 2: exclude first 2 records and return only the next 3 records

             SELECT * FROM EMP
             ORDER BY empno
             OFFSET 2 ROWS 
             FETCH NEXT 3 ROWS ONLY


No comments:

Post a Comment