variable for query string
<p>As higher in hierarchy forum users suggested Im postig my problem as a new question related to this one: <a href="https://stackoverflow.com/questions/3833352/declare-variable-for-query-string">declare variable for query string</a>.</p>

<p>Im using dynamic query here because I want to be able to use variables (I need it for my experiment involving parameter sniffing). My query looks like that:</p>

<pre><code>DECLARE @i NVARCHAR(10)
SET @i = 'POL'

DECLARE @sql VARCHAR(MAX)
SET @sql = 'SELECT

a.something1,
b.something2,
c.something3

FROM
aaa a WITH(NOLOCK)
LEFT JOIN bbb b WITH(NOLOCK) ON....
LEFT JOIN ccc c WITH(NOLOCK) ON....

WHERE
a.somethingelse = ''aa''
AND
((a.entirelysomethingelse=''aaa'') OR (a.entirelysomethingelse=''aaaa''))
AND
b.anotherdifferentsomething != 41
AND 
c.yetanotherdifferentthing LIKE(''%@%'')
AND
c.datafromvariablewannabe = (@i)
GROUP BY
...
ORDER BY
...'
EXECUTE (@SQL)
</code></pre>

<p>When I want to execute my query Im getting error like:</p>

<pre><code>'Msg 137, Level 15, State 2, Line 28
Must declare the scalar variable "@i".'
</code></pre>

<p>When I moved declaration of variable @i into the @sql then it sorta works. Still I don't think It's what I wanted. Am I doing something wrong or it has to look like this?:</p>

<pre><code>DECLARE @sql VARCHAR(MAX)
SET @sql = '

DECLARE @i NVARCHAR(10)
SET @i = 'POL'

SELECT

a.something1,
b.something2,
c.something3

FROM
aaa a WITH(NOLOCK)
LEFT JOIN bbb b WITH(NOLOCK) ON....
LEFT JOIN ccc c WITH(NOLOCK) ON....

WHERE
a.somethingelse = ''aa''
AND
((a.entirelysomethingelse=''aaa'') OR (a.entirelysomethingelse=''aaaa''))
AND
b.anotherdifferentsomething != 41
AND 
c.yetanotherdifferentthing LIKE(''%@%'')
AND
c.datafromvariablewannabe = (@i)
GROUP BY
...
ORDER BY
...'
EXECUTE (@SQL)
</code></pre>

<p>Are there any mistakes in my code so Im getting MSG137 error or it's just impossible task that I want to do here.</p>

<p>I don't want to create a stored procedure from this query. I want to be able to use variables but without relying on stored procedure.</p>

<p>I apologize admins/forum users for problems involving my earlier question in hyperlinked question.</p>