Forum Discussion

AdagioB's avatar
AdagioB
Tin Contributor
Sep 06, 2023

Joining databases in test and production

I have a challenge, where I am looking for a good idea on how to do this the smartest way

 

In our old setup we had two different SQL servers. One for production and one for test. This way all our databases had the same name in test and production. When writing our SQL scripts (both stored procedures and in C#/VB.Net code files) we often wrote code like this after connecting to db2:

SELECT *
FROM MyTable mt INNER JOIN 
db1.MyOtherTable myt ON mt.id = myt.id

 

Unfortunately our new setup requires both test and production tables to be on the same SQL Managed Instance in Azure. From what I can tell, this means I would need to give new names to the test databases. The result is we now have the following databases (names just as example):

db1

db2

db1_test

db2_test

 

If we connect to db2_test and call the above stored procedure, it will connect to db1 instead of db1_test

I will of course create a new SQL server user that will only have access to the xxx_test databases, but it will still try to connect to the production database

 

This does not seem to be the correct way to go. Creating new stored procedures for test is just an invitation to disaster. Going through thousands of stored procedure (not to mention all SQL scripts written in code files) to write something like the below also seems to be a bad move

 

IF @IsTest = 1
BEGIN
SELECT *
FROM MyTable mt INNER JOIN 
db1_test.MyOtherTable myt ON mt.id = myt.id
END
ELSE
BEGIN
SELECT *
FROM MyTable mt INNER JOIN 
db1.MyOtherTable myt ON mt.id = myt.id
END

Using dynamic SQL also seems to be a lot of work and will increase risk of errors in code

 

The only "decent" solution I can think of is having a replace('db1', 'db1_test') script (Powershell? We are building using Azure Devops Pipelines. Not sure if it is possible) to be called on all stored procedures when building for test, hoping this wont break something else. Not a perfect solution, but that is the best I can come up with

Does anybody else have a better idea? I am just trying to do some brainstorming before I start anything

No RepliesBe the first to reply