简体   繁体   中英

Query to update 1 column with no condition and another column only if certain condition is met

I have the below SQL Server query to update column type in tblTicket:

    UPDATE A set type=B.type
    FROM  tblTicket A 
    JOIN (select b.tblTicket_id,a.type
        from tblP a
        JOIN tblA b ON a.allocation_id = b.id
        WHERE b.tblTicket_id =@tblTicket_id Group By b.tblTicket_id,a.type) B
    ON A.id=b.tblTicket_id

I also want to update column bid in table tblTicket, but only if a.name = "ML":

        UPDATE A set bid = B.id
        FROM  tblTicket A 
        JOIN (select b.tblTicket_id,f.id
        FROM tblP a
        JOIN tblA b ON a.allocation_id = b.id
        JOIN FIRM f ON f.firm = a.firm
        WHERE b.tblTicket_id =@tblTicket_id and a.name = 'ML' Group By b.tblTicket_id,f.id) B
        ON A.id=b.tblTicket_id

Can I combine the 1st query with the 2nd query above ? Thank you.

Using CASE you can update a column if a certain condition is satisfied, otherwise you can "set" that column with the same value.

A "best practice" tip: avoid using same aliases (even switching from uppercase to lowercase and vice-versa) in your nested queries.

UPDATE A set type=B.type,
             bid = case when a.name = 'ML' then B.id else bid end
FROM  tblTicket A 
JOIN (select b.tblTicket_id,a.type
    from tblP a
    JOIN tblA b ON a.allocation_id = b.id
    WHERE b.tblTicket_id =@tblTicket_id Group By b.tblTicket_id,a.type) B
ON A.id=b.tblTicket_id

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