【问题标题】:set @var = exec stored_procedure设置 @var = exec 存储过程
【发布时间】: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


【解决方案1】:

如果你在 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

您不能将存储过程中的记录集直接分配给标量变量

【讨论】:

    【解决方案2】:

    您可以使用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
    

    【讨论】:

    • 谢谢。我想在我的 SP 中做这样的事情;WITH XMLNAMESPACES (DEFAULT 'abc.com') SET @out = (SELECT XmlResult.value('count(//subjects/subject)', 'int') FROM @XmlTable) 但是我收到语法错误。这让我发疯了
    • 使用SELECT @out = XmlResult.value 将其分配给标量变量。
    • 谢谢。我看到了消息(1 行受影响),但没有看到 SELECt @out = xmlResult.Value 的结果...我怎样才能看到结果?
    • 如果您想将其作为标量返回或调用存储过程(如上图所示)从输出参数中获取它,您只需执行 SELECt @out 即可
    【解决方案3】:

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

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

    【讨论】:

    • 是的,这会起作用,但如果您不想输入计数值并使用它。这行不通。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-07
    • 2013-01-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多