Wednesday, 8 January 2014

How to use TOP Clause with variable in SQL Server




In SQL Server, if we try to use variable with TOP Clause, it does not work. In order to overcome this issue, we would require using variable in bracket with TOP Clause.

Find below the simple code and example.

Example Code

CREATE PROCEDURE GET_STUDENT_LIST
     @No_Of_Records INT
AS
      SELECT TOP (@No_Of_Records)  * FROM [Student Master]
GO

Execution Result

EXEC GET_STUDENT_LIST 10