2011-03-25 40 views
12

是否可以在变量中分配从exec存储过程返回的值?set @var = exec stored_procedure

喜欢的东西

DECLARE @count int 
SET @count = Execute dbo.usp_GetCount @Id=123 
+0

Yopur问题询问'EXEC @ sql'但例如你给调用存储的过程。你需要什么? – 2011-03-25 23:06:40

回答

24

您可以使用sp_executesql代替exec分配给标量输出参数

DECLARE @out int 

EXEC sp_executesql N'select @out_param=10', 
        N'@out_param int OUTPUT', 
        @[email protected] OUTPUT 

SELECT @out 

对于exec我只知道如何使用可变

表做
declare @out table 
(
out int 
) 

insert into @out 
exec('select 10') 

select * 
from @out 

对于存储的pro也可以使用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 
+0

谢谢。我想在我的SP中做这样的事情;使用XMLNAMESPACES(DEFAULT'http://abc.com')SET @out =(SELECT XmlResult.value('count(// subjects/subject)','int') FROM @XmlTable)但是我得到语法错误。这让我疯狂 – BumbleBee 2011-03-25 23:40:15

+0

使用'SELECT @out = XmlResult.value'将它分配给一个标量变量。 – 2011-03-25 23:44:34

+0

谢谢。我看到消息(1行受影响),但没有SELECt @out = xmlResult.Value的结果...我怎样才能看到结果? – BumbleBee 2011-03-25 23:53:43

23

如果您在proc使用RETURN

DECLARE @count int 
EXECUTE @count = dbo.usp_GetCount @Id=123 

OUTPUT参数

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 

你不能从存储的proc分配一个记录集直接一个标量变量

10

像往常一样,很多方法可以做到这一点,但最简单的就是:

DECLARE @count int 

Execute @count = dbo.usp_GetCount @Id=123 
+1

是的,这是可行的,但如果你不想输入计数值并使用它。这不起作用。 – Abe 2016-02-29 10:30:26

相关问题