Click here to Skip to main content
15,891,136 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How to put server instance name dynamic in select statement used for linked server, below is my statement
SQL
SELECT  * FROM  [HOME-PC].SampleDB.dbo.Records WHERE Col_1_1=62 and Col_1_2=1

Now i want like below
SQL
declare @instancename nvarchar(50)
set @instancename='Home-PC'
SELECT  * FROM  [@instancename].SampleDB.dbo.Records WHERE Col_1_1=62 and Col_1_2=1


please suggest me..
Posted
Comments
Tomas Takac 30-Nov-14 2:55am    
4-part identifier? Why? Is this to connect to a linked server?

Build your sql string and finally execute it using sp_executesql
check this post : http://stackoverflow.com/questions/803211/how-to-get-sp-executesql-result-into-a-variable[^]
 
Share this answer
 
Comments
Maciej Los 30-Nov-14 4:58am    
+5
See the two solutions given here: http://stackoverflow.com/questions/10170791/linked-server-query-dynamic-sql[^]. You can use a synonym[^] and/or dynamic query.
 
Share this answer
 
Comments
Maciej Los 30-Nov-14 4:58am    
5
I solved it by concatenating string and then execute
SQL
CREATE procedure [dbo].[GetRemoteData]
(
@District nvarchar(10),
@Vdc nvarchar(10),
@instanceName nvarchar(max),
@dbname nvarchar(max)
)
as
begin
declare @conInstanceName nvarchar(max)
declare @tablename nvarchar(max)
set @tablename='dbo.Records'
set @conInstanceName='['+@instanceName+']'+'.'+@dbname+'.'+@tablename
declare @SQLQUERY nvarchar(500)
set @SQLQUERY='select top 10 * from'+@conInstanceName
EXEC sp_executesql @SQLQUERY

end
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900