如何使用另一个过程中的过程返回值

时间:2013-03-22 13:33:26

标签: sql-server-2008

我是数据库和sql-server 2008的新手。我有一个类似于

的程序
CREATE PROCEDURE P @myint as int
AS
BEGIN

CREATE TABLE #temp (Quantity smallint, Timing smallint)

INSERT INTO #temp

SELECT 
    Order.quantity as 'Quantity',
    Order.ValidUntil - Order.ValidFrom / X

FROM
    Order

WHERE 
    Order.id = 123

SELECT * FROM #temp

DROP TABLE #temp

END

现在问题出现在第二列的上述select语句中,其中我提到了'X'。对于这个X,我应该在执行另一个返回表的过程之后有一个值,并且我想使用该表的某个列的值。

所以,而不是X我想写类似

的东西
create table #tmp (col1 nvarchar(512), col2 smalldatetime, col3 smalldatetime, col4 int, col5 float)
Insert into #tmp EXEC ProcedureHere 6, '20130101', '20131231', 0, 400
select col4 from #tmp

1 个答案:

答案 0 :(得分:1)

在您的过程中,您必须将参数与输出属性放在一起,当您将参数定义为OUT / OUTPUT时,该值将在过程执行完成后可用。

--first declare all variables with the same type as table #tmp fields     
--remember: It's a better design put the declare block in the top of the procedure
declare @p1 nvarchar(512), 
        @p2 smalldatetime, 
        @p3 smalldatetime,
        @p4 int,
        @p5 float

--create the table  
create table #tmp (col1 nvarchar(512), col2 smalldatetime, col3 smalldatetime, col4 int, col5 float)

--call the procedure
EXEC ProcedureHere @p1, @p2, @p3, @p4, @p5             

--insert data into temporary table
Insert into #tmp 
  select @p1, @p2, @p3, @p4, @p5

--read col4 
select col4 from #tmp 
--or 
select @p4

程序DDL:

if another parameters is required, you simply add then in the mark (*):
Create Procedure ProcedureHere(
        @p1 nvarchar(512) output, 
        @p2 smalldatetime output, 
        @p3 smalldatetime output,
        @p4 int output,
        @p5 float output,
        *) as
begin
  .
  DoStuff
  .
  --define @p1 result value
  select @p1 = select something from somewhere
  --so on for the others parameters      
  .
end
go
相关问题