It seems that USE statement is compiled by MS SQL Server 2008R2.
For example,
if(1=0)
begin
USE MyDB
end
The result will be in executing USE MyDB
while ignoring IF statement.
How can it be changed to work with condition?
P.S. Also tried execute sp_executesql N'USE [MyDB]'
, it works with condition, but it does not change current context.
When you need a conditional "Use MyDB", I would look at sqlcmd and variables.
Use $(DatabaseName)
GO
That's the only way I have found to get "dynamic" Use MyDatabase names.
Reference article: