tags:

views:

40

answers:

1

I need to update a field in a SQL-Server table conditionally. The field contains single-letter indicators of various status types, all together in the field. e.g. "I" for Insured, "O" for Other Insured, "H" for Health Qualified, etc., but together as a composite. The field might contain nothing, any of the letters, or all of the letters. e.g. "IHO" or "HOI" or "O" or "OI" etc. Any given single letter should never appear more than once in the field, though.

The application is running through a set of records based on unique ID, and updating just this field given the record's unique ID. Is it possible to, in a single SQL Update statement, accomplish the equivalent of:

"If this field already has an 'I' in it, don't do anything; otherwise, add an 'I' to the existing set of letters."

...and, if so (of course), what would that Update statement look like?

I am far from a SQL expert (obviously), so please be gentle. :)

+4  A: 

Something like

UPDATE MyTable
SET StatusTypes= StatusTypes+ 'I'
WHERE UniqueID=5
AND CHARINDEX('I', StatusTypes)=0
SteveCav
This works, but doesn't address the fundamental design issue of storing multiple values in one column. Since there seems to be a 1:N relationship between customers (?) and statuses, it would be better to fix the design by adding a second table for the statuses: easier to query, easier to add new statuses and probably better performance too.
Pondlife
My thoughts exactly. Queries like the one above can be used to pull the data out into another table and normalise the field`:INSERT INTO WidgetStatus(WidgetID, Status)SELECT UniqueID, 'I' FROM MyTable WHERE CHARINDEX('I', StatusTypes)>0
SteveCav
Ponlife and SteveCav -- totally agree, but it's not my DB. It's a vertical app I can't change, and need to write to / integrate with.
Jamo