Tải bản đầy đủ - 0 (trang)
5-2. Reading Data from Another SQL Server Instance over a Permanent Connection

5-2. Reading Data from Another SQL Server Instance over a Permanent Connection

Tải bản đầy đủ - 0trang

Chapter 5 ■ SQL Server Sources



Adding a linked server requires the ALTER ANY LINKED SERVER permission. The grantor (or the principal

specified with the AS option) must have either the permission itself with GRANT OPTION or a higher permission.

Then, they can run the following code snippet:

GRANT ALTER ANY LINKED SERVER TO Adam;

If you prefer, you can also specify a linked server using Management Studio, as follows.

1.



In the Object Explorer pane, expand Server Objects, and then right-click Linked

Servers and choose New Linked Server. Enter the name of the SQL Server (or the

instance name) in the New Linked Server dialog box and select the SQL Server radio

button, as shown in Figure 5-1.



Figure 5-1.  Adding a linked server in SSMS

2.



Click Security in the left pane. Specify the security context of any connections using

the linked server (this is described in Recipe 4-9). Then click OK.



245

www.it-ebooks.info



Chapter 5 ■ SQL Server Sources



Security is a major consideration when using linked servers. Unfortunately, it is a vast subject with myriad

ramifications. So all I can offer are a few simple guidelines; a complete analysis of this area is beyond the scope of

this book.

When connecting to a linked server, inevitably there will be a security context under which the remote

login operates. By default (and assuming that security account delegation is available), the remote server uses

the security credentials of the current login from the calling server. Given this potential simplicity, Windows

authentication is the way to go, if you can. The account that you are using has to have SELECT permissions on the

tables that you are reading on the remote server.

If you are not using Windows Authentication, or if Delegation is not configured, you need to add a linked

server login. You could use code like the following:

EXECUTE master.dbo.sp_addlinkedsrvlogin @rmtsrvname = N'SQLLinkedServer', @locallogin = NULL,

@useself = N'False', @rmtuser = N'Adam', @rmtpassword = N'Me4B0ss';

If there is no security account delegation, then you have to map the account on the local server to a remote

login using SQL Server authentication on the remote machine.

When querying a linked server, there are other approaches that you may choose to use to return data using

a linked server connection. For instance, you can also use EXEC...AT in this way, if you desire. First, you need to

enable RPC OUT, as follows:

EXECUTE sp_serveroption @server='SQLLinkedServer', @optname='rpc out', @optvalue='TRUE';

Then you can run an EXECUTE...AT command, like this:

INSERT INTO dbo.Client (ClientName, Town )

EXEC ('SELECT ClientName, Town FROM CarSales.dbo.Client') AT SQLLinkedServer;

If you need to parameterize a query, it can be done like this:

DECLARE @ID INT = 2

INSERT INTO dbo.Client (ClientName, Town)

EXEC ('SELECT ClientName, Town FROM CarSales.dbo.Client WHERE ID=' + @ID) AT SQLLinkedServer;

Rather than sending SELECT queries, you can use a stored procedure to load data. As an example of this,

first create the following two stored procedures on the remote server using the following code

(C:\SQL2012DIRecipes\CH05\ pr_GetETLData.Sql and

C:\SQL2012DIRecipes\CH05\pr_GetETLDataWithParameter.Sql):

CREATE PROCEDURE CarSales.dbo.pr_GetETLData

AS

SELECT

ClientName, Town



FROM

dbo.Client

;

GO



CREATE PROCEDURE CarSales.dbo.pr_GetETLDataWithParameter

(

@ID INT

)



246

www.it-ebooks.info



Chapter 5 ■ SQL Server Sources



AS

SELECT

ClientName, Town



FROM

dbo.Client

WHERE ID = @ID

;

GO

You can now call a stored procedure on the linked server using the following code snippet:

INSERT INTO dbo.Client (ClientName, Town)

EXECUTE ('EXECUTE CarSales.dbo.pr_GetETLData') AT SQLLinkedServer

Finally, your remote stored procedure can have parameters. I find the following the easiest way to call it:

INSERT INTO dbo.Client (ClientName, Town)

EXECUTE SQLLinkedServer.CarSales.dbo.pr_GetETLDataWithParameter 1

Here, the “1” is the ID parameter expected by the pr_GetETLDataWithParameter stored procedure.

There are a few linked server options that you may find useful and that can be set using EXECUTE

sp_serveroption. These linked server options are listed in Table 5-1.

Table 5-1.  Linked Server Options



Option



Description



RPC



Enables RPC from the given server. A stored procedure can be executed

on the server.



RPC Out



Enables RPC to the given server. A stored procedure on the remote server

can be executed.



Collation Compatible



Affects Distributed Query execution against linked servers. If this option is

set to true, SQL Server assumes that all characters in the linked server are

compatible with the local server, with regard to character set and collation

sequence (or sort order). This enables SQL Server to send comparisons

on character columns to the provider. If this option is not set, SQL Server

always evaluates comparisons on character columns locally. Essentially

this allows optimal query plans on remote server to be used.



Connect Timeout



Time-out value in seconds for connecting to a linked server.



Query Timeout



Time-out value for queries against a linked server.



Enable Promotion of Distributed

Transactions



Use this option to protect the actions of a server-to-server procedure

through a Microsoft Distributed Transaction Coordinator (MS DTC)

transaction. When this option is True, calling a remote stored procedure

starts a distributed transaction and enlists the transaction with MS DTC.

If set to False, the remotely stored procedure can still work. MS DTC must

be enabled on all servers for this to work. Unfortunately, a discussion of

MTC is outside the scope of this book.



247

www.it-ebooks.info



Chapter 5 ■ SQL Server Sources



Hints, Tips, and Traps





Use the Network name of SQL Server (for the default instance on a server) or use the

servername\instancename (for a specific instance).







To drop a linked server, right-click the linked server name in the list of linked servers,

click Delete, and confirm; or use the following T-SQL snippet:

EXECUTE master.dbo.sp_dropserver SQLLinkedServer, 'droplogins';







You cannot use CLR-based data types with linked servers either. This means not sourcing

GEOGRAPHY, GEOMETRY, or HIERARCHYID data types unless you use CAST or CONVERT on these

types—or OPENQUERY.







At the risk of stating the obvious, you need a destination table to run EXEC...AT, whose

DDL matches the source data.



5-3. Loading Large Data Sets Using T-SQL

Problem

You want to load large data sets from one SQL Server instance to another using T-SQL. You want to perform the

load as efficiently as possible.



Solution

Export the source data using BCP in native format and use the T-SQL BULK INSERT command to load the file.

The simple and fast way to load data between SQL Server instances is to do it like this:

1.



Create a destination table. The following is the one that I use in these examples

(C:\SQL2012DIRecipes\CH05\TblClient_BCP.Sql):

USE CarSales_Staging

GO

CREATE TABLE dbo.Client_BCP

(

ID int NOT NULL,

ClientName nvarchar(150) NULL,

Town varchar(50) NULL,

County varchar(50) NULL,

ClientSize varchar(10) NULL,

ClientSince smalldatetime NULL

) ;

GO



248

www.it-ebooks.info



s



2.



Run the following T-SQL snippet to import the native BCP file

(C:\SQL2012DIRecipes\CH05\Clients.bcp in the accompanying examples):

BULK INSERT CarSales_Staging.dbo.Client_BCP

FROM 'C:\SQL2012DIRecipes\CH05\Clients.bcp'

WITH

(

DATAFILETYPE = 'widenative'

) ;



How It Works

When a direct connection to another SQL Server instance is not possible, you may have to resort to “indirect”

means. In essence, you have to export the data as a file, copy the file onto the destination server, and re-import

it into another instance. Now, you can export data as a flat file or as XML; these subjects are handled in Chapter 7.

Equally, importing them in these formats is the subject of Chapters 2 and 3. However, if you are sending data

between SQL Server databases, instances, and even versions, then the venerable yet magisterial BCP utility (and

with it the BCP native file format) really comes into its own. Consequently, I wish to concentrate here on ways of

loading BCP files. The reasons for choosing this method are fairly simple:





reliability—BCP has been around since the very beginnings of SQL Server, and is

remarkably robust, as is its descendant, BULK INSERT.







speed—nothing loads as fast as a native BCP file, in my experience.



This does not mean that it is a perfect solution. The following are a few minor quibbles.





You always need to know the details of a BCP file and to have knowledge about the DDL

defining the table whose data it contains separately.







You cannot just open a native BCP file and reverse-engineer its structure.







If you are not loading all the columns in the source file into the destination table, or if the

source file columns are not in the same order as those of the destination table, you need a

format file to perform column mapping.







This approach is built for bulk loading—not selecting and/or transforming data en route.



There are several advantages to using BULK INSERT for the import phase of this process.





As it is nothing but T-SQL, it can be run from a query window, a stored procedure, or even

using SQLCMD.







BULK INSERT runs in-process; this makes it the fastest option.







You do not need xp_cmdshell and the requisite permissions as you do with BCP when

run from T-SQL.







It is arguably less clunky to use than the BCP command-line executable and all its flags.







BULK INSERT accepts parallel loads, as described in Chapter 13.



The main thing to ensure with BULK INSERT is that the DATAFILETYPE parameter matches the flag used when

exporting the data. Essentially, –n maps to native and –N maps to widenative.

The BULK INSERT snippet in step 2 of this recipe used only one of the available options. As you may surmise,

there are many others. Table 5-2 provides a succinct overview.



249

www.it-ebooks.info



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

5-2. Reading Data from Another SQL Server Instance over a Permanent Connection

Tải bản đầy đủ ngay(0 tr)

×