简体   繁体   English

如何在SQL中的IF语句中使用“使用[数据库]”事务?

[英]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." 在工作中,我们的生产数据库是"Appt"但测试环境的数据库是"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" ). 它在测试环境中运行良好,因为"Appt""ApptDEMO"存在于那里(它只是不使用"Appt" )。 But in production, it tells me that "ApptDEMO" doesn't exist. 但在制作中,它告诉我“ApptDEMO”不存在。

I want to create a script that I don't need to make x amount of different scripts for different environments. 我想创建一个脚本,我不需要为不同的环境制作x个不同的脚本。 Is this possible? 这可能吗?

Try this (with dynamic SQL): 试试这个(使用动态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. 除了使查询动态化之外,不能动态更改数据库( USE [DB] )。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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