IMG-LOGO

How to use a parameter in Select TOP statement in SQL Server?

andy - 10 Feb, 2014 3384 Views 0 Comment

Many of you may wonder why the parameter that you try to pass does not work when you try to use Select Top Statement.

See below sample stored procedure that will accept a parameter for @NoOfRecords to retrieve the first top 10 records.

CREATE PROCEDURE GetProducts
     @NoOfRecords INT
AS
      SELECT TOP @NoOfRecords  * FROM Products
GO

Alternative you can use an inline sql string, where you pass the parameter as integer and convert them into the string. Below is another alternative, but it is NOT RECOMMENDED

CREATE PROCEDURE GetProducts
     @NoOfRecords INT
AS
      EXEC ('SELECT TOP '  + CONVERT(nvarchar,@NoOfRecords) +  '  * FROM Products ')
GO

Another clean solution is pretty simple, in order to fix the above issue, you can simply add a bracket surrounding the parameter. This method will avoid you to use inline SQL string that required CONVERT or CAST Method

Comments

There are no comments available.

Write Comment
0 characters entered. Maximum characters allowed are 1000 characters.

Related Articles

How to restore database using SQL query in TSQL?

If you have a database backup bak file extension and want to restore it using SQL query You can use the built in RESTORE DATABASE function Remember in order to be able to restore a database successfully You need to ...

How to get all table sizes in TSQL?

To get the information about how much space or size used by tables You can retrieve the size information by linking multiple tables in sys tables There are two tables that hold this information The first one is the sys ...