How can I have a single piece of SQL conditionally change the target server ?
So on my local dev machine, I can run it and have the command …
INSERT INTO [sds].[dbo].[Team_Email_Addresses]
SELECT [class] AS 'Team number' ,
[description] AS 'Team name' ,
[DutyEmail] AS 'Team email address'
FROM [DEVSERVER].[cases].[dbo].[sp_class]
WHERE [status] = 1
But on the test machine I want the same piece of SQL to run and have the command …
INSERT INTO [sds].[dbo].[Team_Email_Addresses]
SELECT [class] AS 'Team number' ,
[description] AS 'Team name' ,
[DutyEmail] AS 'Team email address'
FROM [TESTSERVER].[cases].[dbo].[sp_class]
WHERE [status] = 1
I’ve tried using a variable @TGT and setting it to either devserver or testserver with the SQL FROM [@TGT].[cases].[dbo].[sp_class], but I get an error Could not find server '@TGT' in sys.servers.
You would need to use dynamic SQL. Also you should not be using
'single quotes'to delimit column aliases; this syntax has been deprecated. You should be using[square brackets]or"double quotes"(the former generally preferred).(In fact you don’t really need the aliases here, though you should be specifying the insert column list.)
Or, what you can do to make the code more stable, is to use synonyms in your two environments. In dev:
In Test:
Now your query can simply be:
Of course synonyms only work if you are on SQL Server 2005 or better. It is always useful to specify the version of SQL Server you are using!