从另一个过程调用时将参数值传递给存储过程
passing parameter values to stored procedure when calling from another procedure
我有一个存储过程 sp1,它接受参数@id int、@type int、@orderno int
现在,我正在尝试从 sp2 调用 sp1
alter proc sp2
/insert into @temp_tbl exec sp1 1,2,3
set @select = 'select * from @temp_tbl' --@select is already declared
exec (@select)
现在,当我尝试调用我的 sp2 时
exec sp2
我收到错误:过程或函数 'sp1' 需要参数 @id,但未提供。那么,我该如何传递参数呢??
很简单,例如:
insert into @temp_tbl exec sp1 @id=1, @type=2, @orderno=3
但您显然需要传递值(可能来自其他参数等)。
DECLARE @OrderNoSource INT = 33;
insert into @temp_tbl exec sp1 @id=1, @type=2, @orderno=@OrderNoSource;
那么,一个更完整的例子:
BEGIN TRANSACTION
GO -- necessary to define the fake sp1 for this script
create procedure sp1 @id int, @type int, @orderno int as SELECT @id, @type, @orderno ;
GO
declare @temp_tbl TABLE (id int, [type] int, orderno int);
insert into @temp_tbl EXEC sp1 1,2,3
SELECT * FROM @temp_tbl; -- this works, no EXEC() needed!
DECLARE @select VARCHAR(MAX);
SET @select = 'SELECT * FROM @temp_tbl;'
EXEC (@select); -- FAILS: @temp_tbl is a VARIABLE and NOT IN SCOPE!;
SELECT * INTO #temp_tbl FROM @temp_tbl ; -- copy local TABLE VAR to TEMP Table (stored in temp db, private)
SET @select = 'SELECT * FROM #temp_tbl;' -- note @ changed to #
EXEC (@select); -- This also works, because temp table are in scope
ROLLBACK -- cleanup this test
我有一个存储过程 sp1,它接受参数@id int、@type int、@orderno int
现在,我正在尝试从 sp2 调用 sp1
alter proc sp2
/insert into @temp_tbl exec sp1 1,2,3
set @select = 'select * from @temp_tbl' --@select is already declared
exec (@select)
现在,当我尝试调用我的 sp2 时
exec sp2
我收到错误:过程或函数 'sp1' 需要参数 @id,但未提供。那么,我该如何传递参数呢??
很简单,例如:
insert into @temp_tbl exec sp1 @id=1, @type=2, @orderno=3
但您显然需要传递值(可能来自其他参数等)。
DECLARE @OrderNoSource INT = 33;
insert into @temp_tbl exec sp1 @id=1, @type=2, @orderno=@OrderNoSource;
那么,一个更完整的例子:
BEGIN TRANSACTION
GO -- necessary to define the fake sp1 for this script
create procedure sp1 @id int, @type int, @orderno int as SELECT @id, @type, @orderno ;
GO
declare @temp_tbl TABLE (id int, [type] int, orderno int);
insert into @temp_tbl EXEC sp1 1,2,3
SELECT * FROM @temp_tbl; -- this works, no EXEC() needed!
DECLARE @select VARCHAR(MAX);
SET @select = 'SELECT * FROM @temp_tbl;'
EXEC (@select); -- FAILS: @temp_tbl is a VARIABLE and NOT IN SCOPE!;
SELECT * INTO #temp_tbl FROM @temp_tbl ; -- copy local TABLE VAR to TEMP Table (stored in temp db, private)
SET @select = 'SELECT * FROM #temp_tbl;' -- note @ changed to #
EXEC (@select); -- This also works, because temp table are in scope
ROLLBACK -- cleanup this test