Tải bản đầy đủ - 0 (trang)
7-4. Exporting Text Files from the Command Line

7-4. Exporting Text Files from the Command Line

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

Chapter 7 ■ Exporting Data from SQL Server



BCP does not have an option to include column headers. Should you need them, then you need to tweak the

SQL to include column headers, possibly using a UNION clause in your T-SQL along these lines

(C:\SQL2012DIRecipes\CH07\IncludeHeadersInTextFile.sql):

SELECT ID, ClientName, Country

FROM (

SELECT 'ID' AS ID, 'ClientName' AS ClientName, 'Country' AS Country, 0 AS RowOrder

UNION

SELECT CAST(ID AS VARCHAR(11)), ClientName, Country, 1 AS RowOrder

FROM CarSales.dbo.Client

) A

ORDER BY RowOrder,ID;

Should the destination database require different field delimiters (a rare occurrence admittedly), then it is

probably easier also to generate these as part of the source SQL.

SELECT

FROM



CAST(ID AS VARCHAR(11)) + '/' + ClientName + ';' + Country

CarSales.dbo.Client;



■■Note In all these examples, I am presuming that you will use the CarSales sample database and the directory

structure of the book samples. Should this not be the case, then you have to substitute the table and field names as

well as the file path with those that you are using.



How It Works

When you think BCP, you probably think “import.” Well, the venerable Bulk Copy program can also be

remarkably efficient when you need to export data as text files from SQL Server. No, the command-line interface

is not the most user-friendly—and indeed, it has been criticized as being clunky, but this utility can nonetheless

help you in many circumstances.

As most of the intricacies of BCP were explained in Chapters 2 and 5, I will only focus on the things that you

need to know to extract data from SQL Server using this tool. To start with, when exporting text data, BCP needs

to know a minimum of six things. These are outlined in Table 7-4. However, the first three elements must be

provided in the order shown in this table, the others can be added in any order.

Table 7-4.  Required BCP Parameters



Element



Comments



The source data



This can be a table, a stored procedure call, a view, or a query. If using a table, view or

stored procedure you should apply three-part notation to include the database name.



The extract type



OUT for a table or view, QUERYOUT for a query (either a select statement or

a stored procedure).



The file path



The complete path and file name, including the extension. Remember to enclose in

double quotes if it contains spaces.



The character type



-c for ASCII, -w for Unicode.



The server name



-S for servername.



The connection type



-T for a trusted connection, -U for username, –P for password for an SQL Server

connection.



358

www.it-ebooks.info



Chapter 7 ■ Exporting Data from SQL Server



When using BCP, there are a few things to consider. First, BCP will always overwrite the contents of a

destination file. Moreover, BCP can only export one table or view at a time—though you can use queries to create

denormalized export tables. Also, if you suspect that a delimiter will be found anywhere inside a data field (a

comma inside an address for instance), then you are strongly advised to use a custom delimiter. Just remember to

tell the person to whom you are sending the data what you have used. Finally, when using a query or executing a

stored procedure with BCP, always enclose it in quotes in the BCP command line.

You may have to escape (or remove) certain characters to ensure that your destination database can load

the text file that you are outputting. For example, if you (or a colleague or client) will later be using MySQL’s LOAD

DATA INFILE to bulk load a text file that you have exported, you should use a backslash (\) to escape instances

of tab, newline, or backslashes that occur within field values. This is most easily done by using T-SQL’S REPLACE

function—although this will slow down the export process a little.

BCP has a few options that are important for you to understand. For instance, by default, BCP uses the tab

character as a column separator, and the newline character as the row terminator. You may need to use other

characters to act as separators, in which case a few well-used variations include

Comma separator: -t,

Pipe separator: -t¦

Tab separator: -t\t

Custom delimiter: -t@@#@@

Newline: -r\n

Carriage Return/Line Feed (CR/LF): -r\r



■■Note Exporting a text file as Unicode doubles its size since each character will be two bytes instead of one. To

avoid this, you may prefer to specify a code page for large files, and if the data that you are exporting lends itself to this

treatment. For example, you can use Code Page –C nnnn (where nnnn is the four-digit reference of the code page).



Hints, Tips, and Traps





To export data as BCP files, you must remember that you cannot use BULK INSERT to

output data, and so will have to resort to command-line BCP.exe, and this means knowing

a few of its many parameters. As we will see, you can also run BCP using xp_cmdshell.







You will need read and write permissions on the path used for the output file.







You will have to CAST or CONVERT any noncharacter values to a VARCHAR of a suitable length

if you are using a UNION query to include column headers.







Remember to handle NULL values if concatenating source fields, or you will lose entire

records from the output should any fields contain NULLs.







If you need to transfer binary and/or CLOB (Character Large OBject) values between

databases, then you are probably best to use the techniques described in Recipes 7-24

and 7-25.







In particularly complex output selection (perhaps involving quoted fields, column

headers, etc.), consider creating the definition of the output as a view or as a stored

procedure, which will then be output as a text file using BCP.



359

www.it-ebooks.info



Chapter 7 ■ Exporting Data from SQL Server



7-5. Exporting Data Using BCP Without Recourse to the

Command Line

Problem

You want to exploit all the power of BCP to export data, but do not want to be restricted to using it from the

command line because you wish this to be part of a wider scripted process.



Solution

Run BCP from T-SQL, SSIS, or SQL Server agent.



Running BCP from SSIS

From SSIS, BCP is run like any other operating system executable—using an Execute Process task, which you

would configure as shown in Figure 7-8 (to use the code that is given in Recipe 7-4).



Figure 7-8.  Running BCP from SSIS



360

www.it-ebooks.info



Chapter 7 ■ exporting Data from SQL Server



Running BCP from SQL Server Agent

To run a BCP export from SQL Server agent, define the job step as:

Type:



Operating System (CmdExec)



Command:



Any valid BCP command—such as:

bcp CarSales.dbo.Client OUT 

C:\SQL2012DIRecipes\CH07\aa1.txt 

-SAdam_01\Adam –c -T



A valid SQL Agent task to run a BCP command should look something like that shown in Figure 7-9.



Figure 7-9. Running BCP from SQL Server Agent



How It Works

There are essentially five main ways of running a BCP export, so it is worth knowing all of them, along with their

uses and any possible limitations. They are shown in Table 7-5.



361

www.it-ebooks.info



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

7-4. Exporting Text Files from the Command Line

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

×