简体   繁体   中英

How can i use “Use [database]” transactions within IF statements in SQL?

I'm trying to do something along the lines of:

IF(@@SERVERNAME = 'SERVER1')
BEGIN
  USE Appt
END
IF(@@SERVERNAME = 'SERVER2')
BEGIN
  USE ApptDEMO
END

At work, our database for production is "Appt" but the one for test environment is "ApptDEMO." They're the same thing, but they're just named differently.

It runs fine in the test environment because both "Appt" and "ApptDEMO" exist there (it just doesnt use "Appt" ). But in production, it tells me that "ApptDEMO" doesn't exist.

I want to create a script that I don't need to make x amount of different scripts for different environments. Is this possible?

Try this (with dynamic SQL):

DECLARE @sql nvarchar(4000)
IF (@@SERVERNAME = 'SERVER1')
BEGIN
    SET @sql = N'USE Appt'
END
ELSE IF (@@SERVERNAME = 'SERVER2')
BEGIN
    SET @sql = N'USE ApptDEMO'
END

IF (@sql != N'')
BEGIN
    EXECUTE sp_executesql @sql
END

Database can't be changed dynamically ( USE [DB] ) other then making the query dynamic.

Below code may clarify your understanding.

SELECT DB_NAME();
-- Master --Default Database

SELECT @@SERVERNAME
-- SERVER1

DECLARE @USEDB NVARCHAR(MAX) = 
CASE @@SERVERNAME WHEN 'SERVER1' THEN 'USE [Appt];'
                  WHEN 'SERVER2' THEN 'USE [ApptDEMO];'
END -- Same as IF statement

EXEC(@USEDB) -- The database [Appt] will be changed within this batch, not outside.
SELECT DB_NAME();
-- Master --Default Database

DECLARE @MyQuery VARCHAR(MAX) = 'Select DB_NAME();'
DECLARE @UseDBWithQuery VARCHAR(MAX) = @USEDB + @MyQuery

EXEC(@UseDBWithQuery)
-- Appt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM