Use OpenQuery in SQLServer to access other databases

Source: Internet
Author: User
OpenQuery is a technology used by SQLServer to interact with other servers. Through OpenQuery, SQLServer can directly access other database resources. Other databases exist in the OpenQuery expression as the external server. Use sp_slave servers to find all slave servers of the current database.

OpenQuery is a technology used by SQL Server to interact with other servers. Through OpenQuery, SQL Server can directly access other database resources. Other databases use the Linked Server in the OpenQuery expression. Use sp_receivservers to find all the linked servers of the current database.

OpenQuery is used by SQL ServerOthersServer interaction technology,

Through OpenQuery, SQL Server can directlyAccessOthersDatabaseResources.

WhileOthersDatabaseThe OpenQuery expression contains the Linked Server.

UseSp_incluservers can find the currentDatabaseAll linked servers.

You can also view the currentDatabaseLinked Server in:

The OpenQuery expression can be written as follows:

Select * from OpenQuery([linkedServerName],'Select * from table1 where rownum < 10')

It is worth noting that if you want to execute the followingDatabaseStatement,

Select * from tbl_emp Where empName = 'leo''

Leo must be input in double quotation marks, as shown below,

Select * from OpenQuery([linkedServerName],'Select * from table1 where empName = ''leo''')

If you want to input a parameter to OPENQUERY,

Dynamic SQL statements can be assembled and executed through exec.

DECLARE @Sql VARCHAR(1000)DECLARE @organizationID VARCHAR(10)SELECT @organizationID = (SELECT ORGANIZATION_ID FROM MYORGS WHERE ORGANIZATION_NAME = 'MMT')SET @Sql = 'SELECT * from tableName where organization_id='+@organizationIDSET @Sql = 'SELECT * FROM OPENQUERY(BETSYCRP2, ''' + REPLACE(@Sql, '''', '''''') + ''')'EXEC(@Sql) 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.