exec failed because the name not a valid identifier?

后端 未结 2 975
天涯浪人
天涯浪人 2020-12-15 02:08

I have a query I need run it as a dynamic query to output a meaningful column name. As an example, if I run the query directly, it returns data correctly. However, if I use

相关标签:
2条回答
  • 2020-12-15 02:55

    Try this instead in the end:

    exec (@query)
    

    If you do not have the brackets, SQL Server assumes the value of the variable to be a stored procedure name.

    OR

    EXECUTE sp_executesql @query
    

    And it should not be because of FULL JOIN.
    But I hope you have already created the temp tables: #TrafficFinal, #TrafficFinal2, #TrafficFinal3 before this.


    Please note that there are performance considerations between using EXEC and sp_executesql. Because sp_executesql uses forced statement caching like an sp.
    More details here.


    On another note, is there a reason why you are using dynamic sql for this case, when you can use the query as is, considering you are not doing any query manipulations and executing it the way it is?

    0 讨论(0)
  • 2020-12-15 03:05

    As was in my case if your sql is generated by concatenating or uses converts then sql at execute need to be prefixed with letter N as below

    e.g.

    Exec N'Select bla..' 
    

    the N defines string literal is unicode.

    0 讨论(0)
提交回复
热议问题