use*_*540 2 sql t-sql sql-server stored-procedures
我有一个无法更改的存储过程。它返回一个选择值(整数)。
它插入一些值并返回新的 id - 存储过程的最后一行:
SELECT @newID
Run Code Online (Sandbox Code Playgroud)
我正在使用新的 ID,但我不想在运行存储过程时显示该值。
所以我使用以下内容:
DECLARE @test INT
EXEC @test = Pr_My_Procedure 'NewGroupName'
SELECT @test
Run Code Online (Sandbox Code Playgroud)
这执行成功,但当存储过程创建和返回的实际值是实际 ID 号时,我的变量 @test 始终 = 0。
为什么我的变量没有被分配?
我有一个解决方法(这不是我真正想要的,但它有效:
1 DECLARE @NewGroupID INT
2 EXEC Pr_My_Procedure 'NewGroupName'
3 SET @NewGroupID = (SELECT GroupID FROM DB..Groups WHERE GroupName = 'NewGroupName')
Run Code Online (Sandbox Code Playgroud)
这可行,但在运行存储过程时,我仍然得到生成的 GroupID 返回结果(第 2 行)。我不想看到那个。
是否有可能不从过程中返回该选择结果?
谢谢大家的建议!
当你这样做时
exec @p = StoredProc
Run Code Online (Sandbox Code Playgroud)
...您正在处理过程的返回值,而不是过程的结果集。过程的默认返回值为零,因此如果您不在过程中执行显式 RETURN,它将返回 0。
您可以更改过程以返回您的 ID,或添加输出参数。
-- Procedure which RETURNS the ID
create procedure StoredProc_WithReturn
as
return 10;
go
-- Procedure which uses output parameter instead.
create procedure StoredProc_WithOutput
@p int output
as
select @p = 12;
go
-- Now test both ways of returning a value
declare @p int = 0,
@po int = 0;
exec @p = StoredProc_WithReturn;
select @p;
exec StoredProc_WithOutput @po output;
select @po;
Run Code Online (Sandbox Code Playgroud)
由于您无法更改过程,因此可以将过程的结果集插入到表、临时表或表变量中,如下所示
create procedure StoredProc_WithSelect
as
select 10;
go
declare @pt table (a int);
insert @pt
exec StoredProc_WithSelect;
select a from @pt;
Run Code Online (Sandbox Code Playgroud)