top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to create a CSV file of any table by sql query in sql server?

+5 votes
548 views
How to create a CSV file of any table by sql query in sql server?
posted Aug 3, 2015 by Mohammed Hussain

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

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.

answer Aug 5, 2015 by Shivaranjini
...