Why won’t this piece of code work for me? It gives the error Must declare the scalar variable "@y".
DECLARE @y int
DECLARE @dbname VARCHAR(50)
SET @y = -1
SET @dbname = 'SomeDb.dbo.'
SET @sql = 'SELECT @y=1 from ' + @dbname + 'Respondent'
exec(@sql)
The
execfunction creates a new execution scope. Your @y variable doesn’t exist there.Use sp_executesql instead. Note that you’ll still have to do some extra work to pass your variable across the function boundary.