Changing Databases Dynamically using Variables I want change into a database programatically using in code:

DECLARE @SQL nvarchar(2000)
DECLARE @DBName sysname

SET @DBName= 'foo'
SET @SQL = 'USE [' + @DBName + ']'

select @SQL
execute @SQL


When I execute the @SQL I get this error:


  Msg 203, Level 16, State 2, Line 9
  The name 'USE [foo]' is not a valid identifier.


Is there a way to do this? Thank you in advance.

The goal is to now be in the foo database after this runs.
I changed 

execute @SQL


to 

exec (@SQL)


and it worked for me. However, the scope of the use is only in the dynamic SQL.