error concatenating parameter inside exec

  • The two examples below are a simplified version of an error I'm running in to. The top version runs fine, the bottom version where I'm using exec keeps throwing errors. I think it's the concatenation with 1 and the parameter. I've got other parts of my code where I'm using exec and concatenating code with parameters that works just fine, so I'm scratching my head on this one. Any tips greatly appreciated.

    works fine:

    Declare @testvar Varchar(MAX)

    select top 1 @testvar=NameSchema from #TempCommonMatchFormatted
         select @testvar
     

    throws error:

    Declare @testvar Varchar(MAX)
        
    exec('select top 1 '+@testvar+'=NameSchema from #TempCommonMatchFormatted
         select '+@testvar)

    error:

    Msg 102, Level 15, State 1, Line 1
    Incorrect syntax near '='.
        

  • scotsditch - Friday, September 28, 2018 12:25 PM

    The two examples below are a simplified version of an error I'm running in to. The top version runs fine, the bottom version where I'm using exec keeps throwing errors. I think it's the concatenation with 1 and the parameter. I've got other parts of my code where I'm using exec and concatenating code with parameters that works just fine, so I'm scratching my head on this one. Any tips greatly appreciated.

    works fine:

    Declare @testvar Varchar(MAX)

    select top 1 @testvar=NameSchema from #TempCommonMatchFormatted
         select @testvar
     

    throws error:

    Declare @testvar Varchar(MAX)
        
    exec('select top 1 '+@testvar+'=NameSchema from #TempCommonMatchFormatted
         select '+@testvar)

    error:

    Msg 102, Level 15, State 1, Line 1
    Incorrect syntax near '='.
        

    That is because in the second you are putting the contents of the variable @testvar in the string.
    Even if you were putting the string @testvar into the string it would fail as the variable isn't declared in the dynamic SQL that would be executed.


  • exec('declare @testvar nvarchar(128); select top (1) @testvar = NameSchema from #TempCommonMatchFormatted; select @testvar as testvar')

    If you want to return a value(s) to a variable(s), the best way is using sp_executesql:


    Declare @sql nvarchar(4000)
    Declare @testvar nvarchar(128)

    Set @sql = 'select top 1 @testvar = NameSchema from #TempCommonMatchFormatted'
    Exec master.sys.sp_executesql @sql, N'@testvar nvarchar(128) OUTPUT', @testvar OUTPUT

    Select @testvar

    SQL DBA,SQL Server MVP(07, 08, 09) "Money can't buy you happiness." Maybe so, but it can make your unhappiness a LOT more comfortable!

  • Thank you!  Been bugging hunting that one for a while.

Viewing 4 posts - 1 through 3 (of 3 total)

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