Feb 8, 2014

Create a CSV file of any table by sql query in sql server


We can create a csv (Comma separated value) file of data of a table by sql query in sql server.

Step 1: Enable the some setting to create csv file. To execute this query you must have admin permission.

EXEC sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
EXEC sp_configure 'Ad Hoc Distributed Queries', 1;
GO
RECONFIGURE;
GO
EXEC SP_CONFIGURE 'xp_cmdshell', '1'
RECONFIGURE;
GO


Step 2: Sql query to create any table and insert data into it.

CREATE TABLE Student(
    Roll INT IDENTITY,
    Name VARCHAR(50),
    Age INT
)

INSERT Student VALUES('Scott',23),('Greg',24),('Marry',21)

Step 3: Sql query to create AppCsvFile.csv file of all records of student table. Here ExactHelp is name of database. You have to change it accordingly.

EXECUTE Master.dbo.xp_CmdShell 'BCP [ExactHelp].[dbo].[Student]  OUT C:\AppCsvFile.csv -T -c -t,'

Sample output:

output
NULL
Starting copy...
NULL
3 rows copied.
Network packet size (bytes): 4096
Clock Time (ms.) Total     : 31     Average : (96.77 rows per sec.)
NULL

Note: You may face problem regrading the permission to create csv file in C drive. In  this case you should use any other drive or any other folder in C drive. 

1 comment:

Unknown said...

I got the below mentioned error

output
SQLState = 28000, NativeError = 18456
Error = [Microsoft][SQL Native Client][SQL Server]Login failed for user 'NT AUTHORITY\SYSTEM'.
SQLState = 42000, NativeError = 4060
Error = [Microsoft][SQL Native Client][SQL Server]Cannot open database "AdventureWorks2008" requested by the login. The login failed.
NULL