不能使用“选择 TOP @Count ...”

joj*_*ojo 5 sql t-sql sql-server stored-procedures

我正在创建一个类似于下面的程序。当没有“TOP @Count”时它工作正常,或者当我放置一个具体的值“TOP 100”时它工作正常。

那么为什么我不能在那里传递价值???我怎么能绕着它走???

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
Run Code Online (Sandbox Code Playgroud)

OMG*_*ies 5

假设 2005+,您需要使用括号:

  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
Run Code Online (Sandbox Code Playgroud)

我的理解是在 v2005添加括号支持,以便不需要动态 SQL