• Your string literals need to be NVarchar, not Varchar, so N'string contents' rather than just 'string contents'

    Also, @query1 shouldn't be in quotes, you want the executesql to execute the contents of that variable, not to try and execute the literal '@query1', which will just give you a syntax error.

    set @query1 = N'Exec sp_executesql @query'

    I have no clue why you're trying to do this, nested sp_executesql?? @Query1 should be the query you're trying to run, the SELECT @OutputVariable = ' + <function result>

    All you needed to do was change the sp_executesql line in your original code and add the output variable into the SELECT

    Gail Shaw
    Microsoft Certified Master: SQL Server, MVP, M.Sc (Comp Sci)
    SQL In The Wild: Discussions on DB performance with occasional diversions into recoverability

    We walk in the dark places no others will enter
    We stand on the bridge and no one may pass