mardi 29 septembre 2015

SQLITE UPDATE field IF NULL from another table

I have a DB with a different tables. What I'm doing is to UPDATE the last inserted row of a table with data from another record af the same table, or from another similar table.

I Got it working but I'm wondering if my solution is correct or something is missing and if I could write it in a more compact and speeder way.

Moreover my code is very very unmanageable, because of if in the future the table structure will change I'll must rewrite the query to add or remove fields.

I was wandering if it's possible to write a query that take a whole record from a table and update all NULL fields in another record of the same table.

sprintf(global_sql, "UPDATE "\
                        "Table1 "\
                    "SET "\
                        "fiedl1 = case when fiedl1 is null then (SELECT fiedl1 FROM Table1 WHERE Table1_id = %d) else fiedl1 end, "\
                        "fiedl2 = case when fiedl2 is null then (SELECT fiedl2 FROM Table1 WHERE Table1_id = %d) else fiedl2 end, "\
                        "fiedl3 = case when fiedl3 is null then (SELECT fiedl3 FROM Table1 WHERE Table1_id = %d) else fiedl3 end "\
                    "WHERE "\
                        "Table1_id = (SELECT max(Table1_id) FROM Table1)", sourceRecord_idx, sourceRecord_idx, sourceRecord_idx); 

As you can see for each single field I must write its specific SET case and moreover the value for each filed is retrieved by a select.

I guess/hope there is a simplier and more maintainable way to do that.

Aucun commentaire:

Enregistrer un commentaire