Export table data to csv file using SQL Server stored procedure
I have the following requirements:
- Exporting table data to a file
.csv
using a stored procedure - The first line in the file
.csv
will be a custom header
Note: the data in this row will not come from the table. This will be a fixed header for the generated one .csv
.
Similarly, something like this:
Latest price data:
product1;150;20150727
product2;180;20150727
product3;180;20150727
+3
source to share
1 answer
Assuming that date
is the correct column datetime
, the following procedure will at least do the job for that table named prodtbl
:
CREATE proc csvexp (@header as nvarchar(256)) AS
BEGIN
SELECT csv FROM (
SELECT prod,date,prod+';'+CAST(price AS varchar(8))+';'
+replace(CONVERT(varchar,getdate(),102),'.','') csv
FROM prodtbl
UNION ALL
SELECT null,'1/1/1900',@header
) csvexp ORDER BY prod,date
END
Command
EXEC csvexp 'my very own csv export'
then will generate the following output:
my very own csv export
product1;150;20150727
product2;180;20150727
product3;180;20150727
Part of actually getting this output in the file is .csv
yet to be done ...
0
source to share