Search code examples
sql-serversql-server-2008stored-procedures

T-SQL USE satetement in condition


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.


Solution

  • 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:

    technet.microsoft.com/en-us/library/ms188714.aspx

    https://learn.microsoft.com/en-us/sql/tools/sqlcmd/sqlcmd-use-scripting-variables?view=sql-server-ver16