views:

38

answers:

2

I have a text field that stores a combination of three values, ':' delimited. (looks like A:B:C).

I'd like to split those values into three actual columns in the table, but I'm not sure of the best way to go about doing this. I'm using sqlite3, any help super appreciated!

A: 

If you're using php, it goes somehitng like this:

PHP:

$explodedStr = explode(":", $delimitedStr);

SQL:

"INSERT INTO tableName (column1, column2, column3)
 VALUES ('".$explodedStr[0]."','".$explodedStr[1]."', '".$explodedStr[2]."
Babiker
you'd actually probably want an update, not an insert.
nathan gonzalez
+1  A: 

First, alter the schema to add the columns you want. I'm assuming you know how to do this.

Second, run an "update" query that splits the data.

update mytable set column1=..., column2=..., column3=...;

The trick is formulating the "..." to extract the right columns from the "source" column.

You could quite likely do something with ltrim(), rtrim() and CASE (see http://www.sqlite.org/lang_expr.html), but you might have an easier time if you defined a user-defined function, perhaps based on length() and substring().

Jon Watte
And, of course, an alternative is to select out all the values, run a sed expression on them to create update statements, and then run the output file as a SQL command.select source from table > filesed -e "s/^([^:]*):([^:]*):([^:]*)\$/update table set column1='\\1', column2='\\2', column3='\\3' where source='\$';" < file > newfilesqlite3 < newfile
Jon Watte