Monday, April 7, 2008

Quick way to convert table (CSV or any other shit) to SQL INSERT batch

Imagine, you have the following unending list of data:


...
49826 447965543413
68428 447965595078
69731 447965596678
116149 447965640054
121889 447965644402
148077 447965666626
177127 447965696290
269990 447965791450
...


You need to insert this data in new temporary table, to use this data in queries for analysing database. Now the best solution I know is to take any smart text editor (I use Notepad++) which can replace text using regular expressions.

So, search string will be ^([0-9]*)[ \t]([0-9]*)$ and replace string will be INSERT INTO table_name (attribute1, attribute2) VALUES (\1, \2), where \1 and \2 means numbers of capturing group. That's all - nice and fast way to do such a work, don't need to programm anything. As the output you'll have something like this:


...
INSERT INTO table_name (attribute1, attribute2) VALUES (49826, 447965543413)
INSERT INTO table_name (attribute1, attribute2) VALUES (68428, 447965595078)
INSERT INTO table_name (attribute1, attribute2) VALUES (69731, 447965596678)
INSERT INTO table_name (attribute1, attribute2) VALUES (116149, 447965640054)
INSERT INTO table_name (attribute1, attribute2) VALUES (121889, 447965644402)
INSERT INTO table_name (attribute1, attribute2) VALUES (148077, 447965666626)
INSERT INTO table_name (attribute1, attribute2) VALUES (177127, 447965696290)
INSERT INTO table_name (attribute1, attribute2) VALUES (269990, 447965791450)
...