A useful use of SQL “LIKE”

I needed to update a set of records in the database where a “code” column followed a specific format:

prefix_shortname_number

As it turned out, there were a bunch of entries that I did *not* want to update that followed a similar format:

prefix_shortname_letter

This would have been bad:

UPDATE TABLE_NAME SET column_name = 'value' WHERE code LIKE 'prefix_shortname[_]%'

As luck would have it, SQL Server (I didn’t check this on MySQL) allows a little bit of semi-regex in LIKE statements.  This update statement worked perfectly:

UPDATE TABLE_NAME SET column_name = 'value' WHERE code LIKE 'prefix_shortname_[0-9]%'

SQL Server will match a single character within the range provided between the brackets; which was all I needed :)

About Jon Trelfa

I live in Detroit, Mi.
This entry was posted in Code. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>