Skip to content

Instantly share code, notes, and snippets.

@ovrmrw
Last active January 18, 2016 09:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ovrmrw/e7ad8d7365f670d24b59 to your computer and use it in GitHub Desktop.
Save ovrmrw/e7ad8d7365f670d24b59 to your computer and use it in GitHub Desktop.
sample code to convert data from SQLServer to CSV on Node.js
import 'babel-polyfill';
import lodash from 'lodash';
const config = require('./config.json') as { mssql: any };
import Sequelize from 'sequelize';
const sequelize = new Sequelize(config.mssql.schema, config.mssql.user, config.mssql.password, {
host: config.mssql.host,
dialect: 'mssql'
});
(async () => {
// a query for SELECT from SQLServer.
const sql = `
SELECT *
FROM yourTable
`;
const records = await sequelize.query(sql, {
type: sequelize.QueryTypes.SELECT
});
let columnNames: string[] = []; // array for collecting column names.
let lines: (string | number)[][] = []; // array for collecting values as line.
records.forEach((record, i) => { // looping per records.
let values: (string | number)[] = [];
lodash.forEach(record, (value: string | number, fieldName: string) => { // looping per columns.
if (i === 0) { // create header line.
columnNames.push(`"${fieldName.replace(/"/g, '""')}"`); // escaping " for csv format.
}
values.push(typeof value === 'number' ? value : `"${value.replace(/"/g, '""')}"`); // if value is string then surrounding by ", and escaping.
});
lines.push(values);
});
// checking retreived data.
console.log(columnNames.join(','));
lines.forEach(values => {
console.log(values.join(','));
});
// TODO: write codes for saving data to csv file.
})();
@ovrmrw
Copy link
Author

ovrmrw commented Jan 18, 2016

This sample needs Babel, TypeScript, Sequelize, Tedious and Lodash.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment