请教一个简单的问题 马上散分
请问 如何在存储过程1得到存储过程2中返回值,该如何写?
我的写法大致是 :
存储过程2中:
declare @sum1 as numeric(12,2)
declare @sum2 as numeric(12,2)
....
set @sum1 = XXX
set @sum2 =xxx
然后:
存储过程1循环体中执行
exec 存储过程2@p1,@p2
请问这里该如何写 马上获取存储过程1中的变量值@sum1,@sum2
------解决方案--------------------create table test(id int identity(1,1),code varchar(8))
insert into test select 'aaaa ' union select 'bbbb '
go
create procedure sp_test2
@id int output,
@code varchar(8) output
as
begin
select @id=id,@code=code from test where code= 'aaaa '
return
end
go
create procedure sp_test1
as
begin
declare @id int,@code varchar(8)
exec sp_test2 @id out,@code out
select @id as nid,@code as ncode
end
go
exec sp_test1
go
/*
nid ncode
----------- --------
1 aaaa
*/
drop procedure sp_test1,sp_test2
drop table test
go
------解决方案--------------------1.在需要返回值的存储过程中声明返回变量
Create Proc Proc1
@ReCode varchar(20) Output
As
..................................
2.在另一存储过程中执行上一存储过程,并取得返回值
Create Proc Proc2
参数定义省略.....
AS
Declare @Code varchar(20)
Select @Code= ' '
Exec Proc1 @Code OutPut --此处除有参数变量外,必须增加OutPut,否则虽能执行存储过程,但无法获取返回值
Select @Code --此处可以将获取的值显示出来,也可以参与其他的操作
------解决方案--------------------create proc pc2
@sum1 numeric(12,2) output,
@sum2 numeric(12,2) output
as
set @sum1=10
set @sum2=20
create proc pc1
as
declare @sum1 numeric(12, 2), @sum2 numeric(12, 2)
exec pc2 @sum1 output, @sum2 output
select sum1=@sum1, sum2=@sum2
exec pc1
------解决方案--------------------if object_id( 'pro1 ') is not null
drop proc pro1
if object_id( 'pro2 ') is not null
drop proc pro2
if object_id( 'tbtest ') is not null
drop table tbtest
GO
create table tbtest(id int identity(1,1),name varchar(20))
insert tbtest(name)
select 'x ' union all
select 'myname ' union all
select 'myname ' union all
select 'yourname ' union all
select 'myname '
select * from tbtest
GO
----创建存储过程1
create proc pro1 @a varchar(16) = null,@returnvalue int=null output
as
select @returnvalue = max(id) from tbtest where name = @a
GO
----创建存储过程2(在该存储过程中调用存储过程1)
create proc pro2 @cmd nvarchar(4000)
as
declare @r int
set @r = 0
exec sp_executesql @cmd,N '@r int output ',@r output
select @r
GO
----调用存储过程2
declare @cmd Nvarchar(4000)
--set @cmd = 'exec pro1 ' 'myname ' ',@r output '
set @cmd = 'exec pro1 @a= ' 'myname ' ',@returnvalue=@r output '--效果同上一条语句
exec pro2 @cmd
----清除测试环境
drop proc pro1,pro2
drop table tbtest
需要注意的地方是@cmd声明成nvarchar(4000)
--再举一例
if object_id( 'prc11 ') is not null
drop proc prc11
go
CREATE PROC PRC11(
@a varchar(16)=null,