无法用户“选择TOP @Count ......”

时间:2010-09-16 02:57:10

标签: sql sql-server tsql stored-procedures

我正在创建一个类似下面的程序。当没有“TOP @Count”时它可以正常工作,或者当我把一个具体的vaule“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

1 个答案:

答案 0 :(得分:3)

假设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

我的理解是bracket support was added in v2005,以便不需要dynamic SQL