Hello,
For such advanced SQL scripts with variables, we recommend using an "SQL script" recipe (in the flow) instead of an SQL query dataset. You can see an example below:
For creating an "SQL script" recipe you can choose as such:
Note that your recipe would not require an input dataset.
Cheers,
Alex