2

I have a stored procedure that select top X from Table,

declare @i int ;
set @i = 10 ;
select top @i from tableNam

Incorrect syntax near '@i'.

What should i do ?

suppose that the @i comes from parameters in my storedProcedure

Moolerian
  • 534
  • 6
  • 18

3 Answers3

2

Following syntax will work

declare @i int ;
set @i = 10 ;
select top (@i) * from sys.tables
Eralper
  • 6,461
  • 2
  • 21
  • 27
2

You have to enclose the variable in parenthesis to make it work.

declare @i int ;
set @i = 10 ;
select top (@i) * from tableNam

If you take the cursor to the error line you will find the reason as to why you need the parenthesis like this:

enter image description here

So the value should be a integer. Also if you see the TOP keyword from MSDN then it says to use the parenthesis. The syntax said by MSDN is:

[ 
    TOP (expression) [PERCENT]
    [ WITH TIES ]
]
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
0

You can use dynamic query to get the result:

declare @i int ;
set @i = 10;

DECLARE @SqlQury VARCHAR(500) = '';
SET @SqlQury = 'SELECT TOP ' + CAST(@i AS VARCHAR) + ' * FROM tablename';
-- PRINT @SqlQury
EXEC (@SqlQury)
Arulkumar
  • 12,966
  • 14
  • 47
  • 68
  • Forgetting that this is overkill and a lot more complicated than it needs to be, it will also run into errors for higher numbers. You should cast to `VARCHAR(10)`. If you cast `10000000` to `VARCHAR(5)` the result is `*`, meaning the query you end up with is `SELECT * * FROM tablename`, which won't work. – GarethD May 18 '16 at 11:57