从存储过程返回VariableTable到另一个

时间:2013-10-20 12:57:13

标签: sql sql-server-2008 stored-procedures

这不是一个我想分享可能有助于开发人员的想法的问题

此示例模拟如何将变量表从过程返回到另一个过程

示例程序

Create Proc [dbo].[ReturnVariableTable] (
    @_PersonID uniqueidentifier, @_fromdate date , @_Todate date 
    @obj_cursor cursor varying output
) as
Begin Try
    Begin Tran
DECLARE @PersonSalaryOverYear Table(_Salary Float  ,PersonID uniqueidentifier ,Month Int )
declare @tempdate = @_fromdate 
while ( @tempdate <= @_Todate )
BEGIN

declare @_Salary FLOAT = (select Salary from Person where ID = @_PersonID AND Month(@tempdate) = MonthNumber   ) 
insert into @PersonSalaryOverYear values(@_Salary, @_PersonID,Month(@tempdate) )
select  @tempdate = DATEADD(Month,1,@tempdate)

END 


    Set @obj_cursor = cursor forward_only static for
        select @_Salary as Salary, @_PersonID as PersonID ,Month(@tempdate) as Month 

    Open @obj_cursor

    Commit
End Try

如何致电

Declare @cur Cursor
Declare @_Salary Float
Declare @_PersonID uniqueidentifier 
Declare @Month int
Exec ReturnMultipleData 
    @_PersonID = '2121ad51-fa84-4da4-a9e6-c22e259d549e',@_fromdate='10-01-2013' ,       @_Todate='10-31-2013'
    @obj_cursor = @cur OUTPUT 

Fetch Next From @cur into @_Salary,  @_PersonID,@Month
While @@fetch_status = 0
Begin
   print @_Salary
   print @_PersonID
   print @Month

   Fetch Next From cur into  @_Salary,  @_PersonID,@Month
End
Close @cur
Deallocate @cur

1 个答案:

答案 0 :(得分:2)

除非你在游标中有多行,否则这更简单:

Create Proc dbo.ReturnMultipleData 
    @PersonID uniqueidentifier,
    @Salary decimal(10, 2) out,
    @Att uniqueidentifier out
As

Select
    @Salary = p.Salary,
    @Att = a.AttendanceID
From
    Person p
        Left Outer Join
    VPerson_AttendanceNumber a
        On p.ID = a.PersonID
Where
    p.ID = @PersonID