SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Concatenate server name parameter
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

LarryC74
Yak Posting Veteran

94 Posts

Posted - 01/17/2013 :  11:22:23  Show Profile  Reply with Quote
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
Flowing Fount of Yak Knowledge

3661 Posts

Posted - 01/17/2013 :  11:31:23  Show Profile  Reply with Quote
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 - 01/17/2013 :  11:36:54  Show Profile  Reply with Quote
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
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.14 seconds. Powered By: Snitz Forums 2000