Click here to Skip to main content
15,907,687 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
its running ok. i want run server instance name ,user id,password,database name ,table name in a single query. both local database and internet database

What I have tried:

declare @server varchar(50)
declare @db_name varchar(50)
declare @schema varchar(50)
declare @table varchar(50)
declare @query nvarchar(500)

set @server='GOWTHAMAN-PC'
set @db_name='KRISHNA'
set @schema = 'dbo'
set @table = 'tbl_billing_master'

set @query = 'SELECT * FROM ['+@server+'].['+@db_name+'].[' + @schema + '].[' + @table + '] '

EXEC sp_executesql @query
Updated 27-May-21 21:20pm
Giovanni Bejarasco 28-May-21 10:27am    
I'm assuming this gets ultimately used in an application/UI and if that's the case, why not just use multiple connections from your app? This is just a very odd way of accessing your data. Maybe there's a better design. Can you give more context you want to do it this way?

1 solution

That isn't going to work: you can't specify a different server in a SELECT statement. See here:[^]

And ... that's nasty code: it's wide open to SQL Injection which can compromise, damage or destroy your DB. You are going to be very, very careful exactly who can use it, and what they can pass to it ...
Share this answer

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