create proc P
(
  @num int
)
asbegin 
  select top @num * from tb;
end这样写报错
我现在只能写成 exec('select top ' + @num + '* from tc');请问还有别的实现办法么?exec是大家说的动态执行么?效率会不会低?以前做asp.net开发,现在开始兼顾数据库这块,麻烦大伙给指点一下吧.多谢!

解决方案 »

  1.   

    /*
    在TOP后面使用变量
    (爱新觉罗.毓华(十八年风雨,守得冰山雪莲花开)  2008-01-02  广东深圳)
    */--SQL SERVER 2005 的写法
    use adventureworks
    goDECLARE @Percentage int
    SET @Percentage = 1
    SELECT TOP (@Percentage) PERCENT
    Name
    FROM Production.Product
    ORDER BY Name/*
    Name
    ----------------------
    Adjustable Race
    All-Purpose Bike Stand
    AWC Logo Cap
    BB Ball Bearing
    Bearing Ball
    Bike Wash - Dissolver(6 行受影响)
    */-----------------------------------
    --SQL SERVER 2000 的写法
    create table a([id] [int])
    insert into a(id) values(1)
    insert into a(id) values(2)
    insert into a(id) values(3)
    insert into a(id) values(4)
    insert into a(id) values(5)declare @num as int
    declare @sql as varchar(2000)
    set @num = 2
    set @sql = 'select top ' + cast(@num as char) + ' * from a'
    exec(@sql)drop table a
    /*
    id          
    ----------- 
    1
    2
    */
      

  2.   

    set rowcount @num
    select * from tb
    set rowcount 0
      

  3.   

    create proc P 

      @num int 

    as 
    declare @S1 VARCHAR(4000)
    begin 
      SET @S1='select top '''+@num+''' * from tb '
      EXEC(@S1)
    end 
      

  4.   

    create proc P 

      @num int 

    as begin 
      select top (@num) * from tb; 
    end 
      

  5.   

    --sql2005或者以上版本试用top