using functions in an update query

6 views
Skip to first unread message

Russell

unread,
Mar 16, 2010, 7:06:43 AM3/16/10
to web2py-users
Hi,

I'm trying to update some text fields in a database. In SQL I would
do something like this...

UPDATE products SET product_code=substr(product_code,2);

or even...

UPDATE products SET product_name = replace(product_name, 'Tiger',
'Woods');

Does anyone have an example of how to do this with the DAL?

Thanks
Russell

selecta

unread,
Mar 16, 2010, 7:12:26 AM3/16/10
to web2py-users
for p in db(db.products.id>0).select():
p.update(product_name = 'Tiger Woods')

or

[p.update(product_name = 'Tiger Woods') for p in
db(db.products.id>0).select()]

mr.freeze

unread,
Mar 16, 2010, 10:09:54 AM3/16/10
to web2py-users
It will be faster if the update is performed on the set (without
selecting each one):

db(db.products.id>0).update(product_code=db.products.product_code[:2])

You can do _update to see what SQL will be generated.

Russell

unread,
Mar 16, 2010, 5:29:38 PM3/16/10
to web2py-users
Thanks mr.freeze, that's got it. And so obvious too.

>>>db(db.products.id>0)._update(product_code=db.products.product_code[:2])
"UPDATE products SET product_code=SUBSTR(product_code,1,(2 - 0))"

I guess my question was mainly about the SQL scalar functions
supported by web2py, and the syntax for using them.

For the record, web2py DAL supports: upper(), lower(), len(), and
slicing. But not strip() or replace().

Reply all
Reply to author
Forward
0 new messages