Cannot "Select TOP @Count ..."

I am creating a procedure as shown below. it works fine when there is no "TOP @Count", or it works fine when I put the specific vaule "TOP 100".

So why can't I pass the value there? how can i walk around him

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
+3
source share
1 answer

Assuming 2005+, you need to use parentheses:

  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 support in v2005 so as not to require dynamic SQL .

+2
source

Source: https://habr.com/ru/post/1765013/


All Articles