Skip to content
Advertisement

Why do I need to declare variables twice: within and without the dynamic query?

I’m reworking an existing static query to be dynamic. Why am I needing to declare the variables twice? Once at the top of the file (for a subsequent, unchanging query) and again within the dynamic SQL statement. Is this something to do with how dynamic SQL behaves?

My code is this:

FYI I only have read access on ‘my_db’.
I used https://www.sqlservertutorial.net/sql-server-basics/sql-server-pivot/ to pivot dynamic query

Advertisement

Answer

For the same reason that:

  • A variable is declared in a stored procedure
  • That procedure calls a second procedure
  • The variable declared in the first procedure is not accessible in the second procedure.

In other words: scope. The dynamic code is executed as it’s own batch, process, session… thing, I’m sorry but I don’t know the exact technical term as used by SQL.

Check out sp_ExecuteSQL’s support for parameters. It’s fussy and complex but will allow you to pass parameter values into (and out of!) your dynamic SQL.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement