【问题标题】:set a variable with a return value of a query使用查询的返回值设置变量
【发布时间】:2011-05-05 12:40:47
【问题描述】:

嗨,我的存储过程中有这样的东西,

SET @SQl = 'Some query' --this query return only a cell the type int
SET @VAR = exec(@SQL) --the varaible @var it's local and the type int

如何获取查询的返回值并设置为变量,这可能吗?或者我在做什么是错的???

感谢您的帮助

【问题讨论】:

    标签: sql-server-2005 tsql stored-procedures


    【解决方案1】:

    如果查询返回一个你需要做的标量结果集

    DECLARE @VAR INT
    
    DECLARE @Result TABLE
    (
    C INT
    )
    
    DECLARE @SQl NVARCHAR(MAX)
    SET @SQl = 'SELECT 1'
    
    INSERT INTO @Result
    EXEC(@SQl)
    
    SELECT @VAR = C FROM @Result
    

    更好地使用sp_executesqlOUTPUT 参数

    DECLARE @VAR INT
    
    DECLARE @SQl NVARCHAR(MAX)
    SET @SQl = 'SELECT @out = 1'
    
    EXEC sp_executesql @SQl, N'@out int output', @out = @VAR OUTPUT
    
    SELECT @VAR 
    

    【讨论】:

    • 很好,但我还有另一个问题,我如何在查询中设置这样的参数 out select count(idTable) from table ??也许像这样select count(idTable) = @out from table
    • @Jorge - select @out = count(idTable)
    • @Jorge - 是的。不知道你希望我如何从这些信息中诊断出你做错了什么!
    • 我在此链接中发布了与问题相关的代码,非常感谢您提出我的第一个问题stackoverflow.com/questions/5899265/where-is-the-problem
    • 你不能像这样将多个 EXEC 调用链接在一起。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-02
    • 2016-11-25
    相关资源
    最近更新 更多