Note 1: From what I have seen in my research so far, there is no way to accomplish what I'm looking to do, but I hope I'm wrong ...
Note 2: The goal of this is to eliminate the need to change connection between queries to different databases
I am writing a SQL script (in SSMS) to look up information based on an id number. There are 2 databases that this query can run against (a testing DB and a production DB). An id number will either be in the testing DB or the production, but not both. What I want to do is to use the :CONNECT statement in SQLCMD mode (or an alternative method, but I've yet to find one) to connect to the appropriate DB. Like this:
:CONNECT /*Testing database name*/
IF NOT EXISTS (SELECT * FROM /*appropriate table*/ WHERE ID = @ID)
:CONNECT /*Production database name*/
/*Continue with the rest of the query*/
Theoretically, the code above would ensure that I am connected to the correct DB (assuming the ID exists at all). What keeps happening though is that the 2nd :CONNECT statement activates regardless of the IF EXISTS, resulting in the query always running against production.
Is there a way to accomplish this goal? Thank you in advance!