简体   繁体   中英

SQL Update with Case/IFs

I have 8 bit columns, A1,A2,a3,a4,b1,b2,b3,b4. All 8 are completely independent and its based on these that another field should be populated.

I want to update this other field with the text A, B or AB depending on which of any of the 8 columns are set to 1.

Here are a couple of examples; - all 8 fields are set to 1 then populate with AB,
- if A3 and B1 are set to 1 then populate with AB,
- if A1 and A3 are set to 1 then populate with A,
- if B4 and B2 are set to 1 then populate with B.

So for any combination of A1 through B4 the field should be set

Below is the what I have tried but it is incomplete but will give an idea;

UPDATE

Correct answer from adrianm

UPDATE m
SET ref = ASet + BSet 
FROM contactMaster m
inner join contact c on 
m.contactid = c.contactid
 CROSS APPLY (
     SELECT CASE WHEN (c.A1 | c.A2 | c.A3 | c.A4) = 1 THEN 'C' ELSE '' END AS ASet
           ,CASE WHEN (c.B1 | c.B2 | c.B3 | c.B4) = 1 THEN 'D' ELSE '' END AS BSet
 ) AS CA1 
where ref is null
UPDATE ContactMaster
    SET ref = ASet + BSet 
FROM ContactMaster
     INNER JOIN Contact
          ON ContactMaster.ContactId = Contact.ContactId
     CROSS APPLY (
         SELECT CASE WHEN (Contact.A1 | Contact.A2 | Contact.A3 | Contact.A4) = 1 THEN 'A' ELSE '' END AS ASet
               ,CASE WHEN (Contact.B1 | Contact.B2 | Contact.B3 | Contact.B4) = 1 THEN 'B' ELSE '' END AS BSet
     ) AS CA1 
WHERE ContactMaster.ref IS NULL
IF (Select Count(*) from table where A1=1 AND A2 =1 AND a3 =1 AND a4 =1 AND b1 =1 AND b2 =1 AND b3 =1 AND b4=1 )>0
    BEGIN

    UPDATE MyTable 
    SET ColumnValue ='AB' 
    where A1=1 AND A2 =1 AND a3 =1 AND a4 =1 AND b1 =1 AND b2 =1 AND b3 =1 AND b4=1
    END

   ELSE IF (Select Count(*) from table where A1 =1 and A3 =1 )>0

    BEGIN
     Update MyTable set columnValue ='A'
     where A1 =1 and A3 =1
    END   

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