Search code examples
sqliteinsertcopytclrow

SQLite: Copy all values from a previous row with one substitution


Using SQLite I need to copy nearly all of an existing row from a table, make a change to a single column, and insert the new row into the table. Something roughly like

INSERT INTO $tablename (c1, c2, ... , cn) 
    SELECT (c1, c2, ... , cn) FROM $tablenam

I tried substituting a some value ci into the the list of SELECT columns. This works if the value is a float or an integer, but not if it is a string. If the value is a string, SQLite interprets it as a column name, which naturally doesn't exist and I get an error.

I can write code to perform this operation, but I was hoping to do it in one query.

I am currently coding in Tcl.


Solution

  • You mean this doesn't work?

    INSERT INTO $tablename (c1, c2, ... , cn)
        SELECT (c1, c2, ..., "othervalue", ... , cn) FROM $tablename
    

    How are you constructing your query?

    pseudocode e.g. this won't work as othervalue is interpreted as columnname

    dothquery("INSERT INTO $tablename (c1, c2, ... , cn)
            SELECT (c1, c2, ..., othervalue, ... , cn) FROM $tablename")
    

    while this works, because the " around othervalue are included in escaped format and then sqllite should recognize it as expression not anymore as columnname

    dothquery("INSERT INTO $tablename (c1, c2, ... , cn)
            SELECT (c1, c2, ..., \"othervalue\", ... , cn) FROM $tablename")