declare @n int
set @n=10
exec('select top '+cast(@n as int)+' from yourtable order by id desc')

解决方案 »

  1.   

    cast是什么意思呢?我想把它写成存储过程
      

  2.   

    use Northwind
    go
    declare @n int
    set @n=10
    SET ROWCOUNT @n
    select * from orders
    order by orderID desc
    SET ROWCOUNT 0
      

  3.   

    不好意思,错了点,应该是把整型转换为字符型:
    declare @n int
    set @n=10
    exec('select top '+cast(@n as varchar(10))+' from yourtable order by id desc')
    --cast是字符转换函数,具体的看连机帮助吧!
      

  4.   

    use Northwind
    go
    --建立存储过程
    create procedure SelectLastN
    @n int
    as
    SET ROWCOUNT @n
    select * from orders
    order by orderID desc
    SET ROWCOUNT 0--执行
    exec SelectLastN @n=10
    --建立存储过程
    alter procedure SelectN
    @n int
    as
    declare @sql varchar(4000)
    set @sql='select top '+cast(@n as varchar(10))+' * from orders order by orderID desc'
    print @sql
    exec(@sql)
    go--执行
    exec SelectN @n=10