Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot user "Select TOP @Count ..."

I am creating a procedure something like below. it works fine when there is no "TOP @Count", or it works fine when i put a concrete vaule "TOP 100" .

So why i cannot pass the value there??? how can i walk around it???

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE MyProcedure    
    @Count int = 100
AS
BEGIN

  SELECT TOP @Count 
         t1.id AS ID, 
         t1.name AS Name, 
         t2.type AS TYPE    
    FROM sampleTable1 as t1 with (noloack), 
         sampleTable2 as t2 with (noloack)          
   WHERE (t1.t2Id = t2.Id)     
ORDER BY t1.name asc

END
GO
like image 902
jojo Avatar asked Sep 16 '10 02:09

jojo


1 Answers

Assuming 2005+, you need to use brackets:

  SELECT TOP (@Count) 
         t1.id AS ID, 
         t1.name AS Name, 
         t2.type AS TYPE
    FROM sampleTable1 as t1 with (noloack)
    JOIN sampleTable2 as t2 with (noloack) ON t2.id = t1.t2.id
ORDER BY t1.name

My understanding is the bracket support was added in v2005 in order to not require dynamic SQL.

like image 57
OMG Ponies Avatar answered Sep 25 '22 14:09

OMG Ponies