简体   繁体   English

查询更新无条件的第一列,仅在满足特定条件时更新另一列

[英]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: 我有以下SQL Server查询来更新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": 我也想更新表tblTicket中的列出价,但前提是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. 如果满足特定条件,则可以使用CASE更新列,否则可以使用相同的值“设置”该列。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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