Take the 2-minute tour ×
Database Administrators Stack Exchange is a question and answer site for database professionals who wish to improve their database skills and learn from others in the community. It's 100% free, no registration required.

Hi I want to fetch data from MS SQL DB of a Remote server using Linked Servers. I have linked the servers. I am fetching data as follows.

select * from [IP of server].[Database Name].[dbo].[Table Name]

But I want to get [IP address] from a variable and use it.

Ex: Declare @ServIP varchar(50)

set @ServIP = 'IP of server'

select * from [@ServIP].[Database Name].[dbo].[Table Name]

I'm getting error If I use variable.

How can I do it?

share|improve this question
    
Why are you using the IP address? –  ChrisBint Jul 19 '12 at 15:02
    
I'm accessing Remote Server's data. I need to mention which Server. –  Ethan Jul 19 '12 at 15:25
add comment

migrated from stackoverflow.com Jul 19 '12 at 15:59

This question came from our site for professional and enthusiast programmers.

1 Answer

up vote 0 down vote accepted

Dynamic SQL:

declare @ServIP varchar(50) = 'IP of server'
declare @dsql varchar(1024)
set @dsql = 'select * from ' + quotename(@ServIP) + '.DbName.dbo.TableName'
exec (@dsql)
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.