Using if within an exec () and showing syntax error

0

How about good morning I try to print the value of a variable inside an exec () depending on an if but I mark syntax errors.

DECLARE @VALOR1 INT
SET @VALOR1 = 1

EXEC ('
    IF ('+@VALOR1+' = 1) 
            print '+@VALOR1+'
        ELSE 
            SET '+@VALOR1+' = 2
            print '+@VALOR1+'
    END ')

could someone help me? Thank you! PD (the assignment of value1 to 2 is only to see what enters the else.

    
asked by Cesar Sanchez 15.05.2018 в 19:23
source

1 answer

0

You have a syntax error in Else :

DECLARE @VALOR1 INT
SET @VALOR1 = 1

EXEC ('
    IF ('+@VALOR1+' = 1) 
            print '+@VALOR1+'
        ELSE 
            SET '+@VALOR1+' = 2 //<-- Esta linea genera el error : Set 1 = 2
            print '+@VALOR1+'
    END ')

For what the code should be:

DECLARE @VALOR1 INT
SET @VALOR1 = 1

EXEC ('
    DECLARE @VALOR1 INT
    IF ( ' + @VALOR1 +' = 1)
        BEGIN
            print ' + @VALOR1 + '
        END
        ELSE 
        BEGIN 
            print ' + @VALOR1 + '
        END' )

Now within a exec you can not assign to the variables declared outside the code executed by the exec since it is considered that they are generated by a different session and if you put:

SET @VALOR1 = ' + @VALOR1 + '

It will give you a variable error @ VALOR1 not declared since it does not exist within the session created by the exec .

Greetings

    
answered by 15.05.2018 / 19:56
source