简体   繁体   中英

Combine three fields into one

I am trying to make a change to one of the tables in our database named NonConf . Currently, we have three Yes/No fields called Closed , Open , and OnHold . We are going to be adding more statuses and I think it is a bad idea to continue adding fields for the new statuses. Instead I would like to convert the fields to one Status field.

I have already added the Status field to the NonConf table. How do I use an UPDATE query to populate Status ?

You can use a Switch expression instead of nesting multiple IIf expressions.

UPDATE NonConf AS N
SET N.Status = 
    Switch
        (
            N.Closed, "Closed", 
            N.Open, "Open",
            N.OnHold,"OnHold",
            True, ""
        );

Switch operates similar to SELECT CASE in VBA. So it returns the value from the first expression/value pair where the expression is True . The last expression/value pair ( True, "" ) catches anything which falls through the earlier pairs. Perhaps instead of an empty string, you would prefer Null or some other value to indicate none of the sourced Yes/No columns were True .

You can use one query to update the Status in one shot via a nested IIF :

UPDATE NonConf AS N
SET N.Status = 
IIF (N.Closed, "Closed", 
IIF(N.Open, "Open",
IIF(N.OnHold,"OnHold","")))

Something along these lines, one query for each status

UPDATE yourTable
SET status = 'Closed'
WHERE yourTable.Closed = 'Yes'
  AND status IS NOT NULL

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM