Unfortunately, I do not know a direct solution to this problem. Nearest working version:
DECLARE @db nvarchar(MAX)
SET @db = 'use DBname'
Exec sp_executesql @db
but this only changes the context of the length of the procedure call. However, you can include more operators in this call to use context:
DECLARE @sql nvarchar(MAX)
SET @sql = 'use DBName SELECT * FROM Table1'
Exec sp_executesql @sql
source
share