How to export data from a SQL database into a CSV file and add some new data?
September 8, 2010 1:47 PM Subscribe
How can I export data from a SQL database into a CSV file and add a new column at the same time?
This might be a really easy question for someone with SQL experience. I have none so far. So please help me out.
I want to do three things. First, I would like to have a query which lists all the records that match a specific ZIP Code. As far as I understood this should look something like this:
SELECT FirstName, LastName, Street, Place, ZIP, Email
FROM DATABASE
WHERE ZIP LIKE '2%'
Second, I want to write the results into a csv file. The rows must be separated by comma. And finally, I want the query to write a new column for each record called 'station' which will have the same value for all records.
The CSV should look something like this in the end:
Firstname, Lastname, Street, Place, ZIP, Email, Station
Thomas, Mueller, Main Street 2, Munich, 80938, info@mueller.de, Munich
Fritz, Mueller, Second Street 7, Erding, 87498, test@mueller.de, Munich
How can I do this with SQL?
posted by jfricke to computers & internet (8 answers total) 1 user marked this as a favorite
SELECT FirstName, LastName, Street, Place, ZIP, Email, 'Munich' as Station
FROM DATABASE
WHERE ZIP LIKE '2%'
which adds a constant named Station to the query, with value Munich.
As far as getting this into a CSV, there is no generic SQL way to do this - how you would do it varies on the database you're using and/or the way you're querying it. Many database clients have some way to save to CSV or export to XLS, or copy and paste to excel, etc. Really depends on your database and client.
posted by RustyBrooks at 1:52 PM on September 8, 2010 [1 favorite]