【发布时间】:2023-03-07 06:29:01
【问题描述】:
是否可以在变量处分配从 exec 存储过程返回的值?
类似
DECLARE @count int
SET @count = Execute dbo.usp_GetCount @Id=123
【问题讨论】:
-
Yopur 问题询问
exec @sql,但您给出的示例调用了存储过程。你需要什么?
标签: sql-server-2008 exec
是否可以在变量处分配从 exec 存储过程返回的值?
类似
DECLARE @count int
SET @count = Execute dbo.usp_GetCount @Id=123
【问题讨论】:
exec @sql,但您给出的示例调用了存储过程。你需要什么?
标签: sql-server-2008 exec
如果你在 proc 中使用 RETURN
DECLARE @count int
EXECUTE @count = dbo.usp_GetCount @Id=123
输出参数
DECLARE @count int
EXECUTE dbo.usp_GetCount @Id=123, @count OUTPUT
将结果重定向到临时表/表变量
DECLARE @count int
DECLARE @cache TABLE (CountCol int NOT NULL)
INSERT @cache EXECUTE dbo.usp_GetCount @Id=123
SELECT @count = CountCol FROM @cache
您不能将存储过程中的记录集直接分配给标量变量
【讨论】:
您可以使用sp_executesql 而不是exec 分配给标量输出参数
DECLARE @out int
EXEC sp_executesql N'select @out_param=10',
N'@out_param int OUTPUT',
@out_param=@out OUTPUT
SELECT @out
对于exec,我只知道如何使用表变量来实现
declare @out table
(
out int
)
insert into @out
exec('select 10')
select *
from @out
对于存储过程,您还可以使用output 参数或返回码。后者只能返回一个整数,通常首选返回错误代码而不是数据。下面演示了这两种技术。
create proc #foo
@out int output
as
set @out = 100
return 99
go
declare @out int, @return int
exec @return = #foo @out output
select @return as [@return], @out as [@out]
drop proc #foo
【讨论】:
SELECT @out = XmlResult.value 将其分配给标量变量。
SELECt @out 即可
像往常一样有很多方法可以做到这一点,但最简单的是:
DECLARE @count int
Execute @count = dbo.usp_GetCount @Id=123
【讨论】: