BCP - Using from within SQL Server

From SQLServerPedia

Jump to: navigation, search
See Also: Main_Page - Code Management - Loaders - Bulk Copy Program (BCP)


Since BCP is a command line utility you can call it directly from your T-SQL code. To do so, you will have to use the extended system procedure xp_cmdshell. Keep in mind that extended procedures can be registered in the Master database only; therefore, if you wish to execute xp_cmdshell, you need to switch your database context to Master or include the database name as in "EXEC master..xp_cmdshell". The following code will export the orders table from the Northwind database into a text file in character mode:
USE master  EXEC xp_cmdshell   'bcp northwind..orders out e:\orders.txt -SBP-23H2HEJ1\JPGR -Usa -Psoftware -c'


results:
output  -----------------------------------------------------------------------------------------  NULL  Starting copy...  NULL  830 rows copied.  Network packet size (bytes): 4096  Clock Time (ms.): total 40  NULL    (7 row(s) affected)


Notice that this is using the JPGR instance of BP-23H2HEJ1 server with user id of sa and password of "software".