I am trying to create a sql statement like

set @sql = 'select @stage1 = count(MY_ID)
From VW_OPEN
where ' + @filter

and run it with

exec (@sql)

However this generates an error
Must declare the variable '@stage1'.

If I run statement
select @stage1 = count(MY_ID)
From VW_OPEN

the var @stage 1 is set. Also @sql and @filter are all defind as varchars.

TIA

Changing the select line to
Select ' + @stage1 + ' = count(MY_ID)

runs without error but returns an incorrect null value?