我有个很简单的存储过程,要取符合条件的前n条记录, n作为参数传入,也就是@tops
ALTER PROCEDURE [dbo].[getNewsByCategory] 
@categoryID smallint, @tops int
AS
select top @tops * from News where categoryID=@CategoryID 可总是提示错误,我把@tops换成实际的数字就可以,到底怎么回事?

解决方案 »

  1.   

    ALTER PROCEDURE [dbo].[getNewsByCategory] 
    @categoryID smallint, @tops int 
    AS 
    exec('select top '+ltrim(@tops)+' * from News where categoryID='+ltrim(@CategoryID ))
      

  2.   

    --SQL 2000 Top不可以用变量。
    ALTER PROCEDURE [dbo].[getNewsByCategory]
    @categoryID smallint, @tops int
    AS
    exec('select top '+rtrim(@tops)+' * from News where categoryID='+@CategoryID )
      

  3.   

    ALTER PROCEDURE [dbo].[getNewsByCategory] 
    @categoryID smallint, @tops int 
    AS 
    declare @s varchar(8000)
    set @s = 'select top '+ltrim(@tops)+' * from News where categoryID='+ltrim(@CategoryID )
    exec(@s)
     
      

  4.   

    select top (@tops) * from News where categoryID=@CategoryID
    或者用动态sql
    exec('select top  '+ltrim( @tops)  ' * from News where categoryID= '+ltrim( @CategoryID) ) 
      

  5.   

    ALTER PROCEDURE [dbo].[getNewsByCategory] 
    @categoryID smallint, @tops int 
    AS 
      declare @sql varchar(8000);
      set @sql='select top '+ltrim(@tops)+' * from News where categoryID='+ltrim(@CategoryID );
      exec (@sql)
    go
      

  6.   

    select top @tops * from News where categoryID=@CategoryID 
    只能用动态SQL执行,
      

  7.   

    改成sql2005就可以了,top后面可以用变量,sql2000用exec执行;
      

  8.   

    set rowcount @tops
    select top * from News where categoryID=@CategoryID