如何从存储过程内的EXEC(Query)中获取返回值

时间:2018-03-30 16:05:54

标签: sql sql-server

有没有办法从以下SQL脚本中获取返回值?

ALTER PROCEDURE spInvert 
    (@Id INT, @column CHAR(1))
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @ColumnValue CHAR(1)
    DECLARE @Query VARCHAR(1000)

    SET @Query = 'select Top 1 ' + @column + ' from TEST5 where Id = ''' + @Id + ''

    SET @ColumnValue = EXEC(@Query) // here I need to get the column value
END

@ColumnValue将为1或0.我期待来自@ColumnValue的单一值。我想检查@ColumnValue是否为NULL。如果不为空,我想用这个@ColumnValue更新表。

提前致谢

4 个答案:

答案 0 :(得分:1)

鉴于您的示例代码,我根本不会使用动态SQL。只需更改一下查询并使用EXISTS。

ALTER PROCEDURE spInvert (@Id INT, @column char(1))
AS
BEGIN

SET NOCOUNT ON;

select @column where exists(select * from TEST5 where Id = @Id)

END

答案 1 :(得分:0)

以下是类似的帖子,它回答了我提到的两种情况:

How to get sp_executesql result into a variable?

答案 2 :(得分:0)

由于您的过程中有TOP 1,因此只返回一个值。因此,只需在程序结束时放置SELECT @ColumnValue即可。虽然,这是非常不必要的,你可以删除它:

SET @ColumnValue = EXEC(@Query) // here i need to get the column value

并将其替换为:

EXEC(@Query)

答案 3 :(得分:0)

如果更新SP中的表,可以尝试以下查询。最好不要在过程名称中使用sp

ALTER PROCEDURE USP_Invert 
    (@Id INT, @column VARCHAR(100))
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @Query VARCHAR(1000)

    SET @Query ='UPDATE TEST5 SET ' + @column +' = CASE WHEN (SELECT Top 1 ' + @column + ' FROM TEST5 where Id = ' + Convert(VARCHAR(10),@Id) + ') = 0 THEN 1
                                                    WHEN (SELECT Top 1 ' + @column + ' FROM TEST5 where Id = ' + Convert(VARCHAR(10),@Id) + ') = 1 THEN 0 END '

    EXEC(@Query); -- here I need to get the column value
END

由于