Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 65 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
65
Dung lượng
1,28 MB
Nội dung
Microsoft SQL Server 2000 Programming by Example 624 Today 2001-01-02 00:00:00 Linked Servers Any client application can establish connections to more than one server at a time, but it is not possible to join directly result sets from different connections. Using the rowset functions from the last section, you can execute queries that relate information coming from different data sources. However, SQL Server must establish a connection on every call to OPENDATASOURCE or OPENROWSET, using the connection string or connection parameters sent along with the function call. If you are a Microsoft Access user, you will be familiar with the concept of a linked table. This is a permanent definition of a logical connection to an external data source. SQL Server 2000 implements links to any OLE DB data source, as linked servers, to any SQL Server instance. Any user connected to an instance of SQL Server can access any linked server defined in that instance without knowing the parameters to connect to this particular data source. In this way, you have the flexibility of the OPENROWSET and OPENDATASOURCE functions without exposing to the users the complexity inherent to any OLE DB connection. Caution Having a SQL Server registered in Enterprise Manager does not mean that you have declared that server as a linked server. This is only a setting in a client application, Enterprise Manager, stored in a specific client computer, perhaps the server itself, and it does not have to be visible to any other client connecting to the server. Users can access objects on linked servers, using fully qualified four-part names and using any data access statement. In this way, you can use any kind of information exposed by the OLE DB provider as if it were a table on a database, and join that information to other tables in the local server. In the following sections, you will learn how to set up and use linked servers. Setting Up and Querying Linked Servers The first thing you need to set up a linked server, which connects to an external data source, is an appropriate OLE DB provider. Microsoft has tested the following OLE DB providers to use in a linked server: • Microsoft OLE DB Provider for SQL Server (SQLOLEDB)— Use this provider to connect to SQL Server 6.5, 7.0, and 2000. • Microsoft OLE DB Provider for ODBC (MSDASQL)— Use this provider to connect to any data source, as long as you have a valid ODBC driver for this particular data source. Chapter 15. Working with Heterogeneous Environments: Setting Up Linked Servers 625 • Microsoft OLE DB Provider for Jet (Microsoft.Jet.OLEDB.4.0)— This provider connects you to Microsoft Access databases, Microsoft Excel spreadsheets, and text files. • Microsoft OLE DB Provider for DTS Packages (DTSPackageDSO)— This provider gives you access to the result set of a transformation step from a DTS package. • Microsoft OLE DB Provider for Oracle (MSDAORA). • Microsoft OLE DB Provider for Microsoft Directory Services (ADSDSOObject)— Use this provider to get information from the Active Directory information on Microsoft Windows 2000 or Microsoft Exchange 2000. • Microsoft OLE DB Provider for Microsoft Indexing Service (MSIDXS)— This provider gives you access to local files indexed by the Microsoft Indexing Service. • Microsoft OLE DB Provider for DB2 (DB2OLEDB)— This provider is part of the Microsoft Host Integration Server, and gives you connectivity to IBM DB2 databases. To set up a linked server, you can use the sp_addlinkedserver system stored procedure. Listing 15.15 shows how to create a linked server in the SQLBE server to connect to the SQLBE\Inst2 instance of SQL Server . Listing 15.15 Setting Up a Linked Server Using the sp_addlinkedserver System Stored Procedure Use sp_addlinkedserver with SQL Server as a product name EXEC sp_addlinkedserver @server = N'SQLBE\Inst3', @srvproduct = N'SQL Server' GO Use sp_addlinkedserver with SQLOLEDB as a provider name EXEC sp_addlinkedserver @server = N'SQLBEInst2', @srvproduct = N'', @provider = N'SQLOLEDB', @datasrc = N'SQLBE\Inst2' GO Use sp_addlinkedserver with SQLOLEDB as a provider name and with an initial catalog EXEC sp_addlinkedserver @server = N'NewSQLBEInst2', @srvproduct = N'', @provider = N'SQLOLEDB', @datasrc = N'SQLBE\Inst2', @catalog = N'Northwind' GO To execute the sp_addlinkedserver system stored procedure to create a linked server to a SQL Server instance, you must supply Microsoft SQL Server 2000 Programming by Example 626 • The actual name of the SQL Server default instance or named instance (@server) • N'SQL Server' as product name (@srvproduct) or • The logical name you want to provide to the linked server (@server). • N'' as product name (@srvproduct). • The name of the OLE DB provider used to connect to the data source— in this case, N'SQLOLEDB' (@provider). • The actual name of the SQL Server default instance or named instance to connect (@datasrc). • Optionally, you can specify the catalog or database to which to connect (@catalog). However, this parameter is used only to specify an initial database to connect. After the connection is made, you can access any database on that server, providing you have permissions to use it and the @catalog parameter is disregarded. To query a linked server, you must use a fully qualified name, using four-part names, as seen in Listing 15.16. In this way, tables from linked servers can be used as any local table on any DML operation, such as SELECT, INSERT, UPDATE, or DELETE. The last example on Listing 15.16 shows how to link remote tables to other remote and local tables, as if all these tables were local tables . Listing 15.16 You Can Use LinkedServers to Access Remote Tables Using Fully Qualified Names PRINT 'Selecting data from a linked server' + CHAR(10) SELECT CategoryID, CategoryName FROM [SQLBE\Inst3].northwind.dbo.categories WHERE CategoryID BETWEEN 1 AND 3 PRINT 'Inserting a row into a linked server' + CHAR(10) INSERT SQLBEInst2.Northwind.dbo.Categories (CategoryName) VALUES('More products') PRINT 'Updating a row from a linked server' + CHAR(10) UPDATE SQLBEInst2.Northwind.dbo.Categories SET CategoryName = 'Extra Products' WHERE CategoryName = 'More products' PRINT 'Deleting a row from a linked server' + CHAR(10) DELETE NewSQLBEInst2.Northwind.dbo.Categories WHERE CategoryName = 'Extra Products' Chapter 15. Working with Heterogeneous Environments: Setting Up Linked Servers 627 PRINT 'Join data coming from linked servers' + CHAR(10) SELECT OrderDate, Quantity, OD.UnitPrice, CategoryName, ProductName FROM [SQLBE\Inst3].northwind.dbo.categories C JOIN SQLBEInst2.Northwind.dbo.Products P ON P.CategoryID = C.CategoryID JOIN NewSQLBEInst2.Northwind.dbo.[Order Details] OD ON OD.ProductID = P.ProductID JOIN Northwind.dbo.Orders O ON O.OrderID = OD.OrderID WHERE P.CategoryID = 1 AND Year(OrderDate ) = 1998 AND CustomerID = 'BSBEV' Selecting data from a linked server CategoryID CategoryName 1 Beverages 2 Condiments 3 Confections (3 row(s) affected) Inserting a row into a linked server (1 row(s) affected) Updating a row from a linked server (1 row(s) affected) Deleting a row from a linked server (1 row(s) affected) Join data coming from linked servers OrderDate Quantity UnitPrice CategoryName ProductName 1998-04-14 00:00:00.000 30 46.0000 Beverages Ipoh Coffee (1 row(s) affected) Caution You cannot omit any of the four parts of the fully qualified name when referencing a remote table from a linked server. Microsoft SQL Server 2000 Programming by Example 628 If you want to execute a stored procedure from a linked server, you must first enable RPC (Remote Procedure Calls) on the linked server. Listing 15.17 shows an example of how to enable RPC in a linked server by using the sp_serveroption system stored procedure, and how to call a stored procedure remotely. Listing 15.17 You Can Execute Remote Stored Procedures in a Linked Server Set RPC OUT true to accept remote procedure calls EXECUTE sp_serveroption N'SQLBEinst2', 'RPC OUT', 'true' Execute a remote procedure EXECUTE sqlbeinst2.northwind.dbo.CustOrderHist 'BSBEV' ProductName Total Aniseed Syrup 30 Boston Crab Meat 10 Geitost 15 Gnocchi di nonna Alice 20 Gustaf's Knäckebröd 21 Ipoh Coffee 30 Konbu 23 Manjimup Dried Apples 3 Maxilaku 6 Mozzarella di Giovanni 1 Outback Lager 7 Raclette Courdavault 4 Ravioli Angelo 6 Sir Rodney's Scones 29 Spegesild 15 Steeleye Stout 20 Tarte au sucre 10 Uncle Bob's Organic Dried Pears 34 Wimmers gute Semmelknödel 9 (19 row(s) affected) Chapter 15. Working with Heterogeneous Environments: Setting Up Linked Servers 629 You can define a linked server to connect to an Access database. Listing 15.18 shows how to create a linked server to connect to the DTS.MDB Access database created in Chapter 14. In this example, you must write in @datasrc the location of the MDB file . Note Linking an Access database, the value of @srvproduct is only informative. And the location of the database must be sent using the @datasrc parameter, not the @location parameter. Listing 15.18 Setting Up a Linked Server to an Access Database EXEC sp_addlinkedserver @server = N'DTSMDB', @srvproduct = N'Access 2000', @provider = N'Microsoft.Jet.OLEDB.4.0', @datasrc = N'd:\sql\dts.mdb' GO Map every login in SQL Server to the Admin login in Access EXEC sp_addlinkedsrvlogin @rmtsrvname = 'DTSMDB', @useself= false, @locallogin = NULL, @rmtuser = 'Admin', @rmtpassword = NULL GO Read data from Access through the linked server SELECT ProductName, UnitPrice FROM DTSMDB Products WHERE UnitPrice > 100 GO ProductName UnitPrice Microsoft SQL Server 2000 Programming by Example 630 Thüringer Rostbratwurst 123.7900 Côte de Blaye 263.5000 As you saw in Listing 15.18, it is not enough to create the linked server to access its data. In some cases, it is necessary to map the local logins to remote logins to be able to connect to the linked server. To map logins, use the sp_addlinkedsrvlogin system stored procedure. This procedure accepts the following parameters: • @rmtsrvname—The name of the linked server. In this case, it is 'DTSMDB'. • @useself— True to map every local account to the same account in the linked server, so the @locallogin, @rmtuser, and @rmtpassword parameters will be ignored. In this case, you don't want to automatically map every local user to a remote user, because your Access database is not secured in this case, so you give a value of @rmtuser = false. • @locallogin—Name of the local login to map, only if @useself = false. You specify NULL in this case because you want to map all local logins to the same remote login. • @rmtuser—Name of the remote login to map the @locallogin. If you use an unsecured Access database, @rmtuser = 'Admin'. • @rmtpassword—Password to use in the remote server for the remote user specified in @rmtuser. In this case, it must be a blank password, @rmtpassword = NULL. You can create a linked server to read text files from a directory. To test it, you can create a little text file, like the one in Listing 15.19, in the D:\SQL directory. Listing 15.19 Ages.txt File ID Age Name 1 55 Joseph 2 32 John 3 34 Frederick 4 70 Antony 5 65 Francis 6 75 Jon 7 43 Manfred 8 21 Dick 9 18 Louis Now, you can create a linked server to read files in any directory, as in the example in Listing 15.20, using the OLE DB provider for Jet. Listing 15.20 Setting Up a Linked Server to a Disk Directory Create a Linked Server Chapter 15. Working with Heterogeneous Environments: Setting Up Linked Servers 631 To read text files from the D:\SQL directory EXEC sp_addlinkedserver @server = N'TextFiles', @srvproduct = N'Text files', @provider = N'Microsoft.Jet.OLEDB.4.0', @datasrc = N'D:\SQL', @provstr='Text' GO Map every login in SQL Server to the Admin login in Jet EXEC sp_addlinkedsrvlogin @rmtsrvname = 'TextFiles', @useself= false, @locallogin = NULL, @rmtuser = 'Admin', @rmtpassword = NULL GO Read data from the Ages.txt file SELECT * FROM TextFiles ages#txt GO ID_Age_Name 1 55 Joseph 2 32 John 3 34 Frederick 4 70 Antony 5 65 Francis 6 75 Jon 7 43 Manfred 8 21 Dick 9 18 Louis Note Note that, as in Listing 15.20, you must convert the character "." ("ages.txt") from the filename into the character '#' ("ages#txt"), because the character "." is not valid inside a table name in SQL Server. Microsoft SQL Server 2000 Programming by Example 632 Pass-Through Queries When working with linked servers, SQL Server 2000 always tries to send the queries to the linked servers to be processed remotely. This decreases the network traffic. In particular, the query execution is more efficient because it is performed in the same server in which the affected data is stored. In this case, the query is "passed through" the linked server for remote execution. You can force the execution of pass-through queries remotely by using the OPENQUERY function. OPENQUERY is similar to the OPENDATASOURCE and OPENROWSET functions, because it connects to a remote data source and returns a result set. However, OPENQUERY uses a linked server definition to connect to the remote server. In this way, you have a persistent definition of the connection properties, providing easier maintenance of your database application. As you can see in the examples from Listing 15.21, the syntax of OPENQUERY is very simple: You provide the linked server name to send the query and the query to be executed. Listing 15.21 Using OPENQUERY to Send Pass-Through Queries to a Linked Server Gets the date and time in the linked server SELECT * FROM OPENQUERY(SQLBEinst2, 'SELECT Getdate() AS Now') Reads some data from the linked server SELECT DISTINCT ProductName, UnitPrice FROM OPENQUERY(SQLBEinst2, 'SELECT DISTINCT P.ProductID, ProductName, OD.UnitPrice FROM Northwind.dbo.Products P JOIN Northwind.dbo.[Order details] OD ON OD.ProductID = P.ProductID WHERE OD.UnitPrice > 100') Updating data through OPENQUERY UPDATE OPENQUERY(SQLBEinst2, 'SELECT * FROM Northwind.dbo.Categories') SET CategoryName = 'Obsolete' WHERE CategoryID = 3 Testing changes SELECT categoryname FROM SQLBEInst2.Northwind.dbo.categories WHERE CategoryID = 3 GO Chapter 15. Working with Heterogeneous Environments: Setting Up Linked Servers 633 Now 2001-02-20 17:33:16.370 ProductID ProductName UnitPrice 29 Thüringer Rostbratwurst 123.7900 38 Côte de Blaye 210.8000 38 Côte de Blaye 263.5000 categoryname Obsolete The first query in Listing 15.21 retrieves the system data and time from the linked server. The second query remotely executes a query that joins two tables. When the combined result set is returned, the local server performs the DISTINCT operation. The third query updates data remotely using the OPENQUERY function. Caution OPENROWSET, OPENDATASOURCE, and OPENQUERY accept only string constants as values for their parameters. String variables are not accepted. Partitioned Views Consider you have a very big table, SalesInfo, with your worldwide sales information. You have different regions and you want to be able to execute queries to any subset of the complete sales table, regardless of the region. This table is too big and the maintenance is starting to be difficult. You decide to divide the table among four servers, North, West, South, and East, each one storing data from only one region. To ensure that you store on every server only data related to that specific server, create a check constraint that enforces the value for the particular regions this server manages. Now you want to access any data from anywhere, so, on every server you create a view that combines the data from every server with the data from the other servers by a UNION ALL. Use UNION ALL because you do not want to remove duplicates in the final result set. This view is called a partitioned view. You can test a simple version of this technique using the example from Listing 15.22. This script can be run in a single server and single instance, and still it uses the partitioned view technique. This is the only simplification used in this example. You can change this script to create every table in a different instance or server and modify the view to retrieve every table from the appropriate server, as shown in Listing 15.22. Listing 15.22 Create a Partitioned View Based on Four Tables [...]... news://msnews .microsoft. com /microsoft. public.sqlserver .server news://msnews .microsoft. com /microsoft. public.sqlserver.setup news://msnews .microsoft. com /microsoft. public.sqlserver.tools news://msnews .microsoft. com /microsoft. public.sqlserver.xml news://msnews .microsoft. com /microsoft. public.ae.arabic.sqlserver news://msnews .microsoft. com /microsoft. public.de.sqlserver news://msnews .microsoft. com /microsoft. public.es.sqlserver... news://msnews .microsoft. com /microsoft. public.sqlserver.fulltext news://msnews .microsoft. com /microsoft. public.sqlserver.mseq news://msnews .microsoft. com /microsoft. public.sqlserver.odbc news://msnews .microsoft. com /microsoft. public.sqlserver.olap news://msnews .microsoft. com /microsoft. public.sqlserver .programming news://msnews .microsoft. com /microsoft. public.sqlserver.replication news://msnews .microsoft. com /microsoft. public.sqlserver.security... news://msnews .microsoft. com /microsoft. public.sqlserver.clients news://msnews .microsoft. com /microsoft. public.sqlserver.clustering news://msnews .microsoft. com /microsoft. public.sqlserver.connect news://msnews .microsoft. com /microsoft. public.sqlserver.datamining news://msnews .microsoft. com /microsoft. public.sqlserver.datawarehouse news://msnews .microsoft. com /microsoft. public.sqlserver.dts news://msnews .microsoft. com /microsoft. public.sqlserver.fulltext... news://msnews .microsoft. com /microsoft. public.es.sqlserver news://msnews .microsoft. com /microsoft. public.espanol.sqlserver.administracion news://msnews .microsoft. com /microsoft. public.espanol.sqlserver.olap news://msnews .microsoft. com /microsoft. public.fr.sqlserver news://msnews .microsoft. com /microsoft. public.il.hebrew.sqlserver news://msnews .microsoft. com /microsoft. public.jp.sqlserver .server 641 Appendix A Using SQL Server Instances In... http://www.sqlserverbyexample.com 640 You can find extra SQL Server support in the Microsoft SQL Server public newsgroups, where Microsoft SQL Server engineers, SQL Server Most Valuable Professionals (MVP), and many SQL Server professionals try every day to learn a bit more about SQL Server and share their knowledge with their colleagues: news://msnews .microsoft. com /microsoft. public.sqlserver.ce news://msnews .microsoft. com /microsoft. public.sqlserver.clients... 651 Each SQL Server instance has its own directory with its data files However, the common tools (client tools) for all instances are stored in a directory called 80 that is located inside the Microsoft SQL Server folder Every SQL Server named instance has its own SQL Server and SQL Agent services The names of these services are mssql$instancename (SQL Server service) and sqlagent$instancename (SQL Agent)... Using the SERVERPROPERTY Function USE Master SELECT SERVERPROPERTY('machinename') SELECT SERVERPROPERTY('servername') SELECT SERVERPROPERTY('instancename') GO - SQLBYEXAMPLE (1 row(s) affected) 657 SQLBYEXAMPLE\APPENDIXA (1 row(s) affected) APPENDIXA (1 row(s) affected) • @@SERVERNAME—This function returns the name of the server and current instance of SQL Server This... different server There are many ways to test the connection to SQL Server For example, you can use osql, which is a command-line utility that connects to SQL Server using ODBC Figure A.14 shows how this command is used from the DOS prompt Figure A.14 Using osql to test connectivity to SQL Server 653 Clients that connect to a named instance of SQL Server 2000 must have installed at least the Microsoft. .. Manager, Query Analyzer, Profiler, Server Network Utility, Client Network Utility, isql, and osq, are shared among instances In this appendix, you will install a new named instance of SQL Server 2000 Enterprise Edition in a server called SQLBYEXAMPLE Be aware that Internet Explorer 5.0 is a prerequisite of the installation of SQL Server 2000, because the MMC (SQL Server snap-in) and the Books online... just one server, instead of maintaining as many servers as installations you have to support This appendix teaches you the following: • • • • How to install a new SQL Server instance How to connect to different instances of SQL Server in the same machine System functions used in multi-instance installations Current limitations of SQL Server instances Installing SQL Server Instances A SQL Server instance . news://msnews .microsoft. com /microsoft. public.sqlserver.odbc news://msnews .microsoft. com /microsoft. public.sqlserver.olap news://msnews .microsoft. com /microsoft. public.sqlserver .programming news://msnews .microsoft. com /microsoft. public.sqlserver.replication. news://msnews .microsoft. com /microsoft. public.ae.arabic.sqlserver news://msnews .microsoft. com /microsoft. public.de.sqlserver news://msnews .microsoft. com /microsoft. public.es.sqlserver news://msnews .microsoft. com /microsoft. public.espanol.sqlserver.administracion. news://msnews .microsoft. com /microsoft. public.sqlserver.ce news://msnews .microsoft. com /microsoft. public.sqlserver.clients news://msnews .microsoft. com /microsoft. public.sqlserver.clustering news://msnews .microsoft. com /microsoft. public.sqlserver.connect