Querying a linked sql server - sql-server

I added a linked server, which is showing in the linked server list, but when I query it, it throws an error with the db server name.
EXEC sp_helpserver
EXEC sp_addlinkedserver 'aa-db-dev01'
Select * from openquery('aa-db-dev01','Select * from TestDB.dbo.users')
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near 'aa-db-dev01'.

SELECT * FROM [server].[database].[schema].[table]
This works for me. SSMS intellisense may still underline this as a syntax error, but it should work if your linked server is configured and your query is otherwise correct.

You need to remove the quote marks from around the name of the linked server. It should be like this:
Select * from openquery(aa-db-dev01,'Select * from TestDB.dbo.users')

You can use:
SELECT * FROM [aa-db-dev01].[TestDB].[dbo].[users];

I use open query to perform this task like so:
select top 1 *
INTO [DATABASE_TO_INSERT_INTO].[dbo].[TABLE_TO_SELECT_INTO]
from openquery(
[LINKED_SERVER_NAME],
'select * from [DATABASE_ON_LINKED_SERVER].[dbo].[TABLE_TO_SELECT_FROM]'
)
The example above uses open query to select data from a database on a linked server into a database of your choosing.
Note: For completeness of reference, you may perform a simple select like so:
select top 1 * from openquery(
[LINKED_SERVER_NAME],
'select * from [DATABASE_ON_LINKED_SERVER].[dbo].[TABLE_TO_SELECT_FROM]'
)

The accepted answer works for me.
Also, in MSSQLMS, you can browse the tree in the Object Explorer to the table you want to query.
[Server] -> Server Objects -> Linked Servers -> [Linked server] -> Catalogs -> [Database] -> [table]
then Right click, Script Table as, SELECT To, New Query Window
And the query will be generated for you with the right FROM, which you can use in your JOIN

try Select * from openquery("aa-db-dev01",'Select * from users') ,the database connection should be defined in he linked server configuration

If linked server name is IP address following code is true:
select * from [1.2.3.4,1433\MSSQLSERVER].test.dbo.Table1
It's just, note [] around IP address section.

Related

What is wrong with this SELECT INTO statement in my T-SQL query?

I am using SQL Server 2014 and I have the following T-SQL query, which is supposed to insert the output of a Select statement from a View into a SQL Table that does not yet exist:
USE MyDatabase
SELECT * INTO dbo.[QueryType2_TBL]
FROM
OPENDATASOURCE
(
'SQLOLEDB',
'Data Source=MyDatabase;User ID=XXX;Password=XXXXX'
,SELECT * FROM MyDatabase.dbo.[QueryType2]
);
It seems there are syntax errors in the T-SQL codes but I can't figure out how to correct them. To note that QueryType2_TBL is a table that does not exist on the database. Am I doing it correctly or is there another way to do this?
You are using OPENDATASOURCE as if it were OPENROWSET, those 2 behave differently. Your syntax matches the one for OPENROWSET, which requires query as 3rd parameter (OPENDATASET does not).
Try with the following:
SELECT * INTO dbo.[QueryType2_TBL]
FROM
OPENROWSET
(
'SQLOLEDB',
'Data Source=MyDatabase;User ID=XXX;Password=XXXXX',
'SELECT * FROM MyDatabase.dbo.[QueryType2]'
);
The OPENDATASOURCE is used to establish a connection and use is as if it were the first part of a 4-part named convertion:
OPENDATASOURCE ( provider_name, init_string )
For example:
SELECT
*
FROM
OPENDATASOURCE('SQLNCLI','Data Source=London\Payroll;Integrated Security=SSPI') -- Remote server / file
.AdventureWorks2012 -- Database
.HumanResources -- Schema
.Employee -- Table
You can try like following.
SELECT * INTO dbo.[QueryType2_TBL]
FROM
OPENDATASOURCE
(
'SQLOLEDB',
'Data Source=MyDatabase;User ID=XXX;Password=XXXXX'
).MyDatabase.dbo.[QueryType2]
You might need to check the Data Source and Database Name, you are using the same name. Your Data Source should be the ServerName/IP

Select SQL Server Server's Alias

Is there a way I can select the alias of a SQL Server? For example, I have a server on a box that is named PRODSQL02 but users generally know and connect to this box as PROD.
I have been using ##SERVERNAME but the end recipients of this information don't always understand that PRODSQL02 = PROD.
You can do
SELECT REPLACE(##SERVERNAME, 'SQL02','')
Which removes the 'SQL02' portion of any servername.
You can use substring like this SELECT SUBSTRING(##SERVERNAME, 1, 4) to just get prod out of the value.

how to use View of One DB in another DB in same server

I have View V_empmaster in MYemp database in Sqlserver2008 server, Now I want to use V_empmaster view in MASTERDB database in Same server.
My query is :
select * from dbo.MasterDB.V_empmaster;
but SQL Execution Error message is displayed
Error source: .NetSqlclientDataProvider
Error Message: Invalid objectname 'dbo.V_empmaster'
Anyone help me out what is my mistake even if it is silly
The parts of a name are server.database.schema.object. You've got schema and database the wrong way around:
select * from MasterDB.dbo.V_empmaster
When you refer view from another database in the same server, you should use three part object qualifier:
-- set context to MYemp db
use MYemp
GO
-- access V_empmaster data in MYemp db
select * from dbo.V_empmaster
GO
-- switch context to MASTERDB
use MASTERDB
GO
-- to access V_empmaster from MYemp, three part qualifier
-- ([dbName].[schemaName].[objectName]) is used
select * from MYemp.dbo.V_empmaster

SQL Server Linked Server Example Query

While in Management Studio, I am trying to run a query/do a join between two linked servers.
Is this a correct syntax using linked db servers:
select foo.id
from databaseserver1.db1.table1 foo,
databaseserver2.db1.table1 bar
where foo.name=bar.name
Basically, do you just preface the db server name to the db.table ?
The format should probably be:
<server>.<database>.<schema>.<table>
For example:
DatabaseServer1.db1.dbo.table1
Update: I know this is an old question and the answer I have is correct; however, I think any one else stumbling upon this should know a few things.
Namely, when querying against a linked server in a join situation the ENTIRE table from the linked server will likely be downloaded to the server the query is executing from in order to do the join operation. In the OP's case, both table1 from DB1 and table1 from DB2 will be transferred in their entirety to the server executing the query, presumably named DB3.
If you have large tables, this may result in an operation that takes a long time to execute. After all it is now constrained by network traffic speeds which is orders of magnitude slower than memory or even disk transfer speeds.
If possible, perform a single query against the remote server, without joining to a local table, to pull the data you need into a temp table. Then query off of that.
If that's not possible then you need to look at the various things that would cause SQL server to have to load the entire table locally. For example using GETDATE() or even certain joins. Others performance killers include not giving appropriate rights.
See http://thomaslarock.com/2013/05/top-3-performance-killers-for-linked-server-queries/ for some more info.
SELECT * FROM OPENQUERY([SERVER_NAME], 'SELECT * FROM DATABASE_NAME..TABLENAME')
This may help you.
For those having trouble with these other answers , try OPENQUERY
Example:
SELECT * FROM OPENQUERY([LinkedServer], 'select * from [DBName].[schema].[tablename]')
If you still find issue with <server>.<database>.<schema>.<table>
Enclose server name in []
You need to specify the schema/owner (dbo by default) as part of the reference. Also, it would be preferable to use the newer (ANSI-92) join style.
select foo.id
from databaseserver1.db1.dbo.table1 foo
inner join databaseserver2.db1.dbo.table1 bar
on foo.name = bar.name
select * from [Server].[database].[schema].[tablename]
This is the correct way to call.
Be sure to verify that the servers are linked before executing the query!
To check for linked servers call:
EXEC sys.sp_linkedservers
right click on a table and click script table as select
select name from drsql01.test.dbo.employee
drslq01 is servernmae --linked serer
test is database name
dbo is schema -default schema
employee is table name
I hope it helps to understand, how to execute query for linked server
Usually direct queries should not be used in case of linked server because it heavily use temp database of SQL server. At first step data is retrieved into temp DB then filtering occur. There are many threads about this. It is better to use open OPENQUERY because it passes SQL to the source linked server and then it return filtered results e.g.
SELECT *
FROM OPENQUERY(Linked_Server_Name , 'select * from TableName where ID = 500')
For what it's worth, I found the following syntax to work the best:
SELECT * FROM [LINKED_SERVER]...[TABLE]
I couldn't get the recommendations of others to work, using the database name. Additionally, this data source has no schema.
In sql-server(local) there are two ways to query data from a linked server(remote).
Distributed query (four part notation):
Might not work with all remote servers. If your remote server is MySQL then distributed query will not work.
Filters and joins might not work efficiently. If you have a simple query with WHERE clause, sql-server(local) might first fetch entire table from the remote server and then apply the WHERE clause locally. In case of large tables this is very inefficient since a lot of data will be moved from remote to local. However this is not always the case. If the local server has access to remote server's table statistics then it might be as efficient as using openquery More details
On the positive side T-SQL syntax will work.
SELECT * FROM [SERVER_NAME].[DATABASE_NAME].[SCHEMA_NAME].[TABLE_NAME]
OPENQUERY
This is basically a pass-through. The query is fully processed on the remote server thus will make use of index or any optimization on the remote server. Effectively reducing the amount of data transferred from the remote to local sql-server.
Minor drawback of this approach is that T-SQL syntax will not work if the remote server is anything other than sql-server.
SELECT * FROM OPENQUERY([SERVER_NAME], 'SELECT * FROM DATABASE_NAME.SCHEMA_NAME.TABLENAME')
Overall OPENQUERY seems like a much better option to use in majority of the cases.
I have done to find out the data type in the table at link_server using openquery and the results were successful.
SELECT * FROM OPENQUERY (LINKSERVERNAME, '
SELECT DATA_TYPE, COLUMN_NAME
FROM [DATABASENAME].INFORMATION_SCHEMA.COLUMNS
WHERE
TABLE_NAME =''TABLENAME''
')
Its work for me
Following Query is work best.
Try this Query:
SELECT * FROM OPENQUERY([LINKED_SERVER_NAME], 'SELECT * FROM [DATABASE_NAME].[SCHEMA].[TABLE_NAME]')
It Very helps to link MySQL to MS SQL
PostgreSQL:
You must provide a database name in the Data Source DSN.
Run Management Studio as Administrator
You must omit the DBName from the query:
SELECT * FROM OPENQUERY([LinkedServer], 'select * from schema."tablename"')
For MariaDB (and so probably MySQL), attempting to specify the schema using the three-dot syntax did not work, resulting in the error "invalid use of schema or catalog". The following solution worked:
In SSMS, go to Server Objects > Linked Servers > Providers > MSDASQL
Ensure that "Dynamic parameter", "Level zero only", and "Allow inprocess" are all checked
You can then query any schema and table using the following syntax:
SELECT TOP 10 *
FROM LinkedServerName...[SchemaName.TableName]
Source: SELECT * FROM MySQL Linked Server using SQL Server without OpenQuery
Have you tried adding " around the first name?
like:
select foo.id
from "databaseserver1".db1.table1 foo,
"databaseserver2".db1.table1 bar
where foo.name=bar.name

How to get the data from linked servers using queries

I have created a linkedserver as ravikiran-vm which is the virtual machine in my desktop.
Now I have a database called kiran which contains an employ table.
To retrieve employ data, I do the following:
select * from ravikiran-vm.kiran.employ
but it shows the error "Incorrect syntax near '-'."
Can anyone help me, please?
Thanks in advance.
Thanks guys with ur support it working fine...
Now i hav to schedule this as a new job.when i execute it as normal it shows o/p.
but when i cinfigure the same query as sqlserver agent job it gives error and query not executing...Plz help me in this regard
Thanks in advance
I think you should change the name of the linked server, as the - char is reserved in SQL.
You could try surrounding the name with brackets, but it becomes boring
Also, you should include the schema name in the query, or double point to use the default one:
so, you can try:
select * from [ravikiran-vm].kiran.dbo.employ
select * from [ravikiran-vm].kiran..employ
Or whatever your schema be.
You have to use OPENQUERY:
SELECT * FROM OPENQUERY([ravikiran-vm],'SELECT * FROM KIRAN..EMPLOY')
to get data from linked server you use 4 part notation
Server.Database.Schema.Table
since you have an invalid character in your name(-) you need to add brackets around the name
select * from [ravikiran-vm].kiran..employ
You probably also don't want all the data returned
Usually direct queries should not be used in case of linked server because it heavily use temp database of SQL server. At first step data is retrieved into temp DB then filtering occur. There are many threads about this. It is better to use open OPENQUERY because it passes SQL to the source linked server and then it return filtered results e.g.
SELECT * FROM OPENQUERY(Linked_Server_Name , 'select * from TableName where ID = 500')
1- Link the server
EXEC sp_addlinkedserver 'OracleSvr',
'Oracle 7.3',
'MSDAORA',
'ORCLDB'
2-SELECT
SELECT *
FROM OPENQUERY(OracleSvr, 'SELECT name, id FROM albert.titles')
3-UPDATE
UPDATE OPENQUERY (OracleSvr, 'SELECT name FROM albert.titles WHERE id = 101')
4-INSERT
INSERT OPENQUERY (OracleSvr, 'SELECT name FROM albert.titles')
VALUES ('NewTitle');
5-DELETE
DELETE OPENQUERY (OracleSvr, 'SELECT name FROM albert.titles WHERE name = ''NewTitle''')
i just copied from here (http://www.sqlservercentral.com/Forums/Topic916320-392-1.aspx)
Select * from likedservername.databasename.dbo(schema).tablename
Ex1:
select * from [Bse].[Bse].[dbo].Binary
Else
Select * from openquery (linkedservername, 'select * from databasename.dbo(schema).tablename');
Ex2:
select * from openquery ([Bse], 'select * from [Bse].[dbo].Binary');

Resources