Search code examples
databaseqore

AbstractTable.update() - more complex condition?


From the docs:

int SqlUtil::AbstractTable::update (
hash  set,
hash  cond,
reference< string >   sql,
hash  opt 
) 

updates rows in the table matching an optional condition and returns the count of rows updated; no transaction management is performed with this method Example:

int ucnt = table.update(("id": id), ("name": name));

where ("name": name) is a condition hash. Can the condition be more complex though? What if I had a list or a hash names and wanted to update all rows with a name that is in it? Is it possible to do it with one update statement or do I need to iterate through names?


Solution

  • Yes, the where condition can be complex with update statements generated by SqlUtil.

    The where condition is represented by the cond parameter in the method docs in your question.

    To update rows based on a match from a list of values, use op_in() as follows:

    int rows = table.update(("col1": val1, "col2": val2), ("col3": op_in(my_list)));
    

    This will generate SQL like:

    update table set col1 = %v, col2 = %v where col3 in (%v)
    

    (NOTE: the exact SQL generated will differ depending on the underlying database, and the %v characters are placeholder specifications for bind by value operations in the generated SQL where the actual values are sent separately to the SQL server for reasons described in the previous link)

    To update values based on a match of a another column value, use op_like() as in:

    int rows = table.update(("col1": val1, "col2": val2), ("col3": op_like("%some value%")));
    

    Which will generate SQL like:

    update table set col1 = %v, col2 = %v where col3 like %v
    

    In general you can use any SQL operator function in the where clause of the update method.