Trying to have a single SQL script that works on a number of environments, but the USE statement causes an error for the other environment, i.e. in the example below, when running against SQL02, the USE [application], even when inside a BEGIN ... END?
-- connected to SQL02
DECLARE @STAGE INTEGER = 3
IF @@SERVERNAME = 'SQL02'
SET @STAGE = 1
IF @@SERVERNAME = 'SQL03'
SET @STAGE = 2
IF @STAGE = 1
BEGIN
IF EXISTS ( SELECT *
FROM [application_tst].[sys].[database_principals]
WHERE name = N'qauser' )
BEGIN
USE [application_tst]
--rest of code
END
END
IF @STAGE = 2
BEGIN
IF EXISTS ( SELECT *
FROM [application].[sys].[database_principals]
WHERE name = N'qauser' )
BEGIN
USE [application]
--rest of code
END
END
You will need to use explicit three part names everywhere and not use
USE. USE is an execution time command and your batch will fail to compile as expected because you expect the name resolution to occur as if the USE was executed during compilation.An alternative is to use dynamic sql, which will delay compilation until is invoked.