Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Concatenate server name parameter

Author  Topic 

LarryC74
Yak Posting Veteran

94 Posts

Posted - 2013-01-17 : 11:22:23
Hey everyone!

I'd like to set a parameter for the name of a server and have it write like this. We'll used the link server procedure to link to the new server when doing some comparisons

Declare @ServerName varchar(10);
Set @ServerName = 'DDD-111'
Set @ServerName2 = @ServerName --This is temp...until we get the new server up

--this gives me an error asking me to link to the server (although I'm in the server)
Select *
From [@ServerName].[Database].[dbo].[TableName]
Join
[@ServerName2].[Database].[dbo].[TableName]

--However when I run it like this, it works fine
Select *
From [ServerName].[Database].[dbo].[TableName]
Join
[ServerName].[Database].[dbo].[TableName]



What I want to do is write one long script, have these a parameter at the top and then just execute it. So I wouldn't have to go through each query and change the name of the server.

Everyday life brings me back to reality

James K
Master Smack Fu Yak Hacker

3873 Posts

Posted - 2013-01-17 : 11:31:23
SQL Server does not let you use a scalar variable (or any variable) in that context. If you do want to use a variable, the only choice you have, and it is a bad one, is to use dynamic sql either via exec or sp_executesql. So you would do soemthing like this:
Declare @ServerName varchar(10);
Set @ServerName = 'DDD-111'
Set @ServerName2 = @ServerName --This is temp...until we get the new server up

DECLARE @sql NVARCHAR(4000);
SET @sql =
'Select *
From [@ServerName].[Database].[dbo].[TableName]
Join ' + QUOTENAME(@ServerName2)
+'.[Database].[dbo].[TableName]';

EXEC(@sql);
This is bad for a number of reasons, the least of which is not that it is vulerable to SQL injection. Inability to reuse query plans, broken ownership chains etc. are other reasons.

YHard code the name and then when you change over to the new server, do a global change in your code. That would be my preferred approach.
Go to Top of Page

LarryC74
Yak Posting Veteran

94 Posts

Posted - 2013-01-17 : 11:36:54
Thanks James!

That was my first thought but then thought the parameter would work.

Thanks for the informtion! I'll just hard code it.

Larry



Everyday life brings me back to reality
Go to Top of Page
   

- Advertisement -