set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
ALTER proc [dbo].[proc_new]
@id int=0,
@num int=100,
@returnid    int output
as
select top (@num) * from employee where id>@id
select @returnid = max([ID]) from (select top (@num) id from employee where id>@id ) as tmpTable
declare @id intexec proc_new 2, 3, @id output
print @id  --这个打印的是数据库 employee表中最大的ID  而不是我想要的top (@num)中最大的ID。。
=================================================================================================
select @returnid = max([ID]) from (select top (@num) id from employee where id>@id ) as tmpTable这条有问题吗?
为什么我执行的时候他就给我打印数据库里边最大的ID  而不是在top(@num)里面找到最大的呢?

解决方案 »

  1.   

    select top (@num) * from employee where id>@id在后面加上个order by 试试.例如:select top (@num) * from employee where id>@id order by id
      

  2.   


    select max(id) from (select top 10 ID from employee where id>100) as t
    --这样的话也是输出表中最大的ID  而不是我查询10条中最大的ID
      

  3.   


    CREATE proc [dbo].[proc_new]
    @id int=0,
    @num int=100,
    @returnid    int output
    as
    select top (@num) * from employee where id>@idselect top (@num) @returnid  = id from employee where id>@idgo
    --这是别人给的另一种方法..select top (@num) @returnid  = id from employee where id>@id这句什么意思啊 。。看不懂..
    加了top不是取得很多条数据吗?为什么结果就返回了一条呢
      

  4.   

    select top (@num) @returnid  = id from employee where id>@id这句什么意思啊 。。看不懂..
    加了top不是取得很多条数据吗?为什么结果就返回了一条呢赋值语句只取一个值,多个值无效.而且这种写法不推荐.
      

  5.   


    USE HOSPITAL
    GO
    CREATE PROCEDURE PROC_OUTPUTDEMO
    @num int 10,
    @id int 0,
    @returnid int output
    as
    select top (@num) * from employee e inner join hospital h on e.hptid=h.hptid where e.id>@id order by e.id
    select @returnid=max(id) from (select top (@num) * from employee e inner join hospital h on e.hptid=h.hptid where e.id>@id order by e.id) as tab
    =================================================================================================消息 102,级别 15,状态 1,过程 PROC_OUTPUTDEMO,第 2 行
    '10' 附近有语法错误。
    消息 137,级别 15,状态 2,过程 PROC_OUTPUTDEMO,第 6 行
    必须声明标量变量 "@num"。
    消息 137,级别 15,状态 1,过程 PROC_OUTPUTDEMO,第 7 行
    必须声明标量变量 "@returnid"。
    消息 137,级别 15,状态 2,过程 PROC_OUTPUTDEMO,第 7 行
    必须声明标量变量 "@num"。

    =================================================================================================---哪错了?????