Import and Export data from csv in TSQL

There are common task which you have to perform as DBA or as programmer to import/export data in databbase.

it’s really easy to import/export data from SQL Server if you know the correct commands to use it.

here are easiest way which i found to import/export data from csv to table vise versa.

Use bulk insert statement in T-SQL


BULK INSERT [table_name]
FROM 'C:\Users\Public\data.csv'
WITH(FIELDTERMINATOR = ',', FIRSTROW=0, ROWTERMINATOR = '\n')

just make sure you put the CSV file in public folder or folder which have read permission from sql server account (like MS SQL server folder on program files).
otherwise you will always get an error that sql server can’t access or see the CSV file.

Use BCP utility using command line for export data into csv from table

bcp "SELECT TOP 3 * FROM test.dbo.table1" queryout c:\temp\table1.csv -c -t, -T -S .\SQLEXPRESS

Advertisements