Saturday, February 25, 2012

Capturing results from SPROC

I need to execute a SPROC from another SPROC that returns 1 row with three fields. How do I capture the data out of those?

Have sproc #1 create a #Temp table,

then have sproc #2 populate that #Temp table.

The data will then be available in sproc #1.

|||If the stored procedure will always return 1 or less rows another good alternative is to have the stored procedure return three OUTPUT parameters instead of a row with three columns.|||

Here you can use either Insert Into ...Exec or OUTPUT param.

Code Snippet

--Option 1: If you are not autorized to change the Procedure code.

Create Proc #TestProc1

as

Select 1 Col1, 'Test data' Col2, Getdate() Col3

Go

Create Table #TempData (

Col1 int,

Col2 Varchar(100),

Col3 Datetime

)

Insert Into #TempData

Exec #TestProc1

Select * from #TempData

Code Snippet

--Option 2: Best Fit

Create Proc #TestProc2(

@.Col1 as Int OUTPUT,

@.Col2 as Varchar(100) OUTPUT,

@.Col3 as DateTime OUTPUT

)

as

Select

@.Col1 = 1

,@.Col2 = 'Test data'

,@.Col3 = Getdate()

Go

Declare @.Col1 as Int,

@.Col2 as Varchar(100) ,

@.Col3 as DateTime

Exec #TestProc2 @.Col1 OUTPUT, @.Col2 OUTPUT, @.Col3 OUTPUT

Select @.Col1, @.Col2, @.Col3

No comments:

Post a Comment