miércoles, 26 de febrero de 2014

How to put result from EXEC Procedue into a Variable 
in SQL Server
(Cómo colocar el resultado de un EXEC Procedure en una Variable en SQL Server)

First of all we have to create a Store Procedure with OUTPUT variables, and this Procedure doesn't has to return any row, so you don't have to do any Select statement into the procedure, but may you'll understand it better if I let you a little example

Primero de todo tenemos que crear un Procedimiento almacenado con variables OUTPUT, y este procedimiento almacenado no tiene que devolver ninguna fila, así que procura no hacer ningun Select a alguna tabla dentro de este procedimiento, pero a lo mejor entiendes mejor si te coloco un pequeño ejemplo

CREATE PROCEDURE SP_TEST
(@A INT, @B INT OUTPUT)
AS
BEGIN


    -------------------------------------------
    --[UPDATE/INSERT/DELETE] OR WHATEVER BLOCK
    -------------------------------------------
    /*
    [UPDATE/INSERT/DELETE] FROM XTABLES
    WHERE PK = @A ... BLAH BLAH BLAH

    --BUT JUST WATCH OUT THAT THESE SQL STATEMENTS
    --DON'T RETURN ANYTHING!!
    */
   
    -------------------------------------------
    --ASSIGN A VALUE TO @B THAT HAS THE OUTPUT
    -------------------------------------------
    --USE SET OR SELECT STATEMENT TO ASSIGN A VALUE TO @B

    --EXAMPLES WHIT SELECT OR SET
    --SELECT @B = COLUMN FROM XTABLE WHERE PK = @A
    --SET @B = 100 /*OR ANY VALUE YOU LIKE*/


    SET @B = 100
END

------------------------------------------------------------------------------
And now you can be able of execute the Store procedure assigning a value to a variable like this example

Y ahora puedes ejecutar el Procedimiento almacenado para almacenar el resultado en una variable como se muestra en este ejemplo

DECLARE @C INT
EXEC SP_TEST 1, @C OUTPUT

SELECT @C AS Result


------------------------------------------------------------------------------
And finally the result of @C will be the same as the @B variable assigned value in the Store Procedure, in this case @C is equal to 100

Y finalmente el resultado de @C será el mismo que el valor que le asignamos a la variable @B en el procedimiento almacenado, en este caso @C es igual a 100



Result
-----------
100

(1 row(s) affected)





No hay comentarios:

Publicar un comentario