The bcp (Bulk Copy Program) utility in Microsoft SQL Server lets you efficiently import or export large volumes of data between SQL Server tables and external data files using command-line instructions. It's built into SQL Server client tools and works with any SQL Server instance—local or remote—when you have appropriate permissions. No extra software is required beyond SQL Server client tools (which include bcp.exe) and a valid login with permissions to access the target database and tables.
What You'll Need
- SQL Server client tools installed (includes
bcp.exe); included with SQL Server Management Studio (SSMS) or the SQL Server Feature Pack (e.g., Microsoft OLE DB Driver, ODBC Driver) - Access to a SQL Server instance (on-premises or Azure SQL Database)
- Valid SQL Server login (Windows Authentication or SQL Authentication) with sufficient permissions (e.g.,
SELECTfor export,INSERTfor import) - A source or destination data file (e.g., CSV, TXT, or native format file)
- Target table (for import) or source table (for export) with compatible schema
Step-by-Step
- Open Command Prompt or PowerShell as a user with rights to run
bcp. Ensure the directory containingbcp.exe(typicallyC:\Program Files\Microsoft SQL Server\{Version}\Tools\Binn\) is in your system PATH, or use the full path tobcp.exe. - Verify
bcpis available by runningbcp /?in the command line. You should see the help text listing all available options. If you get a 'command not found' error, install the SQL Server command-line tools or add the Binn folder to your PATH. - Export data from a table using the basic syntax:
bcp [database].[schema].[table] out "C:\path\to\data.txt" -S "server\instance" -T -c -t,. Replace placeholders:databaseandschema(e.g.,AdventureWorks2019.dbo),server\instance(e.g.,localhost\SQLEXPRESS), and adjust the file path. The-Tflag uses Windows Authentication; for SQL Authentication, replace with-U "username" -P "password". The-cflag exports character data, and-t,sets the field terminator to a comma. - Import data into a table with:
bcp [database].[schema].[table] in "C:\path\to\data.txt" -S "server\instance" -T -c -t,. Ensure the target table exists and its column order/data types match the file. If column order differs, use a format file or specify columns explicitly via the-cand-tflags, or use a query:"SELECT col1, col2 FROM [table]" queryout "file.txt" .... - Handle headers and special cases. To skip the first line (e.g., column headers) during import, add
-F 2(start at row 2). To include headers during export, use-q(quoted identifiers) with a query:"SELECT 'col1,col2' UNION ALL SELECT col1 + ',' + col2 FROM [table]" queryout ...—though this is inefficient for large files; better to generate headers separately. - Use format files for complex mappings. Generate a non-XML format file with
bcp [table] format nul -f "C:\path\format.fmt" -S "server" -T -n, then edit the file to adjust column offsets, terminators, and data types. For XML format (recommended for readability and schema flexibility), use-xinstead of-fand-f "format.xml". - Optimize performance. For large imports/exports, use
-b {batch_size}(e.g.,-b 10000) to process data in batches, reducing memory pressure. Add-h "TABLOCK"to acquire a table lock during import (improves speed but blocks other users).
Common Mistakes
- Using the wrong authentication method: forgetting
-U/-Pwhen not using Windows Auth, or vice versa, leading to login failures. - Mismatched data types or column order: importing a CSV where the file columns don’t align with the table schema (e.g., text in a numeric column), causing truncation or conversion errors.
- Ignoring field terminators: using
-t,for CSV but omitting it when the file uses tabs (-t\t) or pipes (-t|), resulting in misaligned data. - Overlooking file permissions: writing to a protected directory (e.g.,
C:\root) without admin rights; use a user-writable path like\Users\Public\. - Using relative paths:
bcpresolves paths relative to the current directory, not the script location. Always use absolute paths to avoid ambiguity. - Forgetting to escape special characters in passwords: if your SQL password contains
&,%, or spaces, wrap it in quotes:-P "MyP@ss%word!".
Tips
- Test with a small sample first: export/import just 100 rows using
-F 1 -L 100to verify format and permissions before full runs. - Use
-vto see verbose output, including row counts and timing, which helps diagnose slow operations. - For Azure SQL Database, include
-N(use native format) or specify-C 65001for UTF-8 encoding to avoid character corruption. - Combine with PowerShell for automation: use
Invoke-Sqlcmdto generate dynamic table lists, then loop throughStart-Process bcpcalls. - Log errors to a file: append
2>> "C:\logs\bcp_error.log"to capture stderr (e.g.,bcp ... > "output.txt" 2>> "error.log"). - Pre-create the target table with matching schema:
bcpdoes not create tables—only populates them.
Troubleshooting
If bcp fails, follow this checklist:
- Check connectivity: Can you connect via SSMS or
sqlcmdusing the same server, login, and instance? If not, fix authentication or network issues first. - Verify file paths and permissions: Ensure the file exists (for
in) or the directory is writable (forout). Try a simple test file likeecho test > test.txtandbcp ... out "test.txt" .... - Review error messages: Look for common codes like
SQLState = 42000(syntax error),4861(cannot bulk load because the file couldn’t be opened), or208(invalid object name). Use-e "errorfile.txt"to log problematic rows. - Inspect the data file: Open it in a text editor to confirm terminators, encoding, and line endings. Windows Notepad often adds a BOM (Byte Order Mark) for UTF-8; use
-C 65001to handle this. - Simplify the command: Remove optional flags (e.g.,
-q,-h) and test with minimal syntax (e.g.,bcp table in file.txt -S server -T -c). - Test with native format: If character encoding issues persist, use
-n(native format) for both export and import between SQL Server instances to preserve exact data types.
Frequently Asked Questions
Does bcp work with Azure SQL Database?
Yes, but you must use SQL Authentication (no Windows Auth), include the full server name (e.g., myserver.database.windows.net), and often specify -N or -C 65001 for encoding. Also, ensure the firewall allows your client IP.
Can bcp handle JSON or XML columns?
Yes—treat them as text. Use -c and ensure your CSV/TSV file escapes quotes or delimiters properly. For complex nested data, export/import using a query that casts the column to varchar(max) first.
How do I export data with column headers?
bcp doesn’t natively add headers. Workaround: export headers separately with SELECT 'col1,col2,col3', then append the data export (e.g., using PowerShell’s Get-Content and Add-Content).
What’s the difference between -c, -n, and -w?
-c exports character data (ANSI), -n uses SQL Server native format (binary, preserves data types), and -w exports Unicode character data (UTF-16). Use -n for high-performance SQL-to-SQL transfers, -c for CSV compatibility, and -w for Unicode text.
Can bcp update existing rows instead of inserting?
No—bcp only inserts or appends. For updates, use INSERT into a staging table, then run a UPDATE ... FROM statement, or use MERGE with a staging table loaded via bcp.
Why do I get truncation errors even though the data fits?
Check the table definition: varchar(n) columns truncate if the file’s longest value exceeds n. Also, ensure no hidden characters (e.g., carriage returns in fields) confuse the parser—use -t and -r to set row terminators explicitly.