sp_ExecuteSQL

  • Is it possible to get a value returned (like an output variable) from a call to sp_executeSQL?

    If so, how?

    I would think it would be something like this:

    EXEC sp_Executesql @SQLText, @parmlist,

            @Item1,

            @Itemout OUTPUT

    Although specifying OUTPUT here does not return the value. This doesn't work

     

    TIA!!

    Francis

    Francis
    -----------------
    SQLRanger.com

  • hey francis,

    you would need to do something like the example below:

    -- [BEGIN] : Code Snippet

    DECLARE @SQLText AS NVARCHAR(500)

    SET @SQLText = N'SELECT @Itemout=some_field FROM Some_Table WHERE some_other_field = @Item1'

    DECLARE @Item1 AS VARCHAR(20), @Itemout AS VARCHAR(20), @parmlist AS NVARCHAR(100)

    SET @parmlist = N'@Item1 AS VARCHAR(20), @Itemout AS VARCHAR(20) OUTPUT'

    EXEC sp_executesql @SQLText, @parmlist, @Item1, @Itemout OUTPUT

    -- [END] : Code Snippet

    hope this helps

  • Using sp_ExecuteSQl isn't a good idea....

    .....HMC

  • Got it. Thanks!

    Francis
    -----------------
    SQLRanger.com

  • if you are referring about the return value of a user-defined function or the value of an output parameter of a stored procedure, then the answer is yes ...

    for a user-defined function,

    SET @SQLText = N'SELECT @Itemout = fn_somefunction()'

    for a stored procedure,

    SET @SQLText = N'EXEC usp_someproc @Itemout'

  • DECLARE @SQLString NVARCHAR(500)

    DECLARE @ParmDefinition NVARCHAR(500)

    DECLARE @Balance varchar(30)

    SET @SQLString = N'SELECT @balOUT = balance from UserAccount where accId = 2 and userId = 1001'

    SET @ParmDefinition = N'@balOUT varchar(30) OUTPUT'

    EXECUTE sp_executesql @SQLString, @ParmDefinition, @balOUT=@balance OUTPUT

    print '--balance on next line--'

    print @Balance

  • Yep, thats it. JourneymanProgrammer had it too, but it didn't sink in until I saw another example

     

    thanks!

    Francis
    -----------------
    SQLRanger.com

Viewing 7 posts - 1 through 6 (of 6 total)

You must be logged in to reply to this topic. Login to reply