Monday, December 10, 2007

SQL: OpenQuery, OpenRowSet, and OpenDataSource

My SQL Server instance is: Vision.

Enable the Ad Hoc query:

Run the Ad Hoc query:

The OPENDATASOURCE function can be used in the same Transact-SQL syntax locations as a linked-server name. Therefore, OPENDATASOURCE can be used as the first part of a four-part name that refers to a table or view name in a SELECT, INSERT, UPDATE, or DELETE statement, or to a remote stored procedure in an EXECUTE statement.


SELECT TOP 5 *
FROM OPENDATASOURCE('SQLNCLI',
'Data Source=Vision;Integrated Security=SSPI')
.AdventureWorks.HumanResources.Employee

SELECT a.*
FROM OPENROWSET('SQLNCLI', 'Server=Vision;Trusted_Connection=yes;',
'SELECT GroupName, Name, DepartmentID
FROM AdventureWorks.HumanResources.Department
ORDER BY GroupName, Name'
) AS a;
===
OpenQuery is used with a Linked Server.

--create a linked server, first
EXEC sp_addlinkedserver 'OracleSvr',
'Oracle 7.3',
'MSDAORA',
'ORCLDB'
GO
--run the OPENQUERY function
SELECT *
FROM OPENQUERY(OracleSvr, 'SELECT name, id FROM joe.titles')
GO