We help IT Professionals succeed at work.

How can I export my stored procedure results into CSV file inside the proc itself?

I have a stored procedure , which produces some records at the end of execution. I want to export all these records to a CSV file and I want to write the code for this in stored procedure itself.
Any idea on how can I do that?
Comment
Watch Question

Information Services Manager
Commented:
I've never needed to do this myself, but this looks like a good example.
http://www.simple-talk.com/sql/t-sql-programming/reading-and-writing-files-in-sql-server-using-t-sql/
Scott PletcherSenior DBA
Most Valuable Expert 2018
Distinguished Expert 2019
Commented:
bcp should be able to handle that.

Feed the results of your SELECT into a temp table.

Use bcp to export to the csv.

If you also need to return the result from the stored proc, naturally just do a:
SELECT * FROM #temptable

Author

Commented:
Thank you very much guys, that was really helpful :).
Scott PletcherSenior DBA
Most Valuable Expert 2018
Distinguished Expert 2019

Commented:
Np.  Sorry for the delay, **very** busy lately.

bcp can be a bear to get working right the first time.  If you need help with it, just let me know.