Click here to Skip to main content
15,885,914 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Hi All

I have an Sql Stored Procedure and i want to export data to the .csv file from my Stored Procedure. my procedure is --



SQL
create Proc ExportTest
AS
BEGIN
SELECT * FROM EMPLOYEE

-- I NEED TO EXPORT RESULT OF THIS SELECT STATEMENT TO THE .CSV FILE
END



Thanks
Posted
Updated 12-Jul-17 14:00pm

If you can use a command line, I suggest you check the bcp utility[^]. It is a powerful command line tool that allows exporting (or importing) data in various formats.

Here[^] you can read a nice article on how to use the utility with a few examples.

If you have troubles with it, just comment below. We will be able to assist you.
 
Share this answer
 
you can use query Like given below



SQL
declare @sql varchar(8000)
select @sql = 'bcp "select * from EmailVarification..tblTransaction" queryout c:\bcp\Tom.xls -c -t, -T -S' + @@servername
exec master..xp_cmdshell @sql



in this query EmailVarification is DB name and tblTransaction is table name.
for execute this query you have to set path for write file.
currently in this query you have to create a "bcp" folder in "C:\ "Drive .

Thanks
 
Share this answer
 
Comments
Member 12055056 13-Oct-15 7:56am    
Can I for destination folder put remote location (remote server)?

Thanks,

Ivana
Yes, it is possible to do it from a stored procedure. We currently have something like this working in our production environment.

Use T-SQL

SQL
INSERT INTO OPENROWSET('Microsoft.ACE.OLEDB.12.0','Text;Database=D:\;HDR=YES;FMT=Delimited','SELECT * FROM [FileName.csv]')
SELECT Field1, Field2, Field3 FROM DatabaseName


But, there's a couple of caveats:

1. You need to have the Microsoft.ACE.OLEDB.12.0 provider available. The Jet 4.0 provider will work, too, but it's ancient, so I used this one instead.

2. The .CSV file will have to exist already. If you're using headers (HDR=YES), make sure the first line of the .CSV file is a delimited list of all the fields.
 
Share this answer
 
 
Share this answer
 
Sorry, it is not possible to write data to disk using Stored Procedure. You can use SQL Server Export Import Wizard to generate the file and save it as a SSIS package for further use.
 
Share this answer
 
Comments
Christian Graus 22-Jan-14 17:19pm    
Nope, this is wrong.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900