Skip to content
Advertisement

How to get the return value from EXEC(Query) inside stored procedure

Is there any way to get the return value from the following SQL script?

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

The @ColumnValue will be 1 or 0. I am expecting single value from @ColumnValue. I want to check if the @ColumnValue is NULL or not. If Not Null, I want to update a table with this @ColumnValue.

Thanks in advance

Advertisement

Answer

If you update table inside SP, you can try the following query.It is better not to use sp in procedure name.

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

Thanks

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement