SQL 使用 WHERE 更新 SELECT

SQL UPDATE SELECT with WHERE

我想 UPDATE table 中的一列,但在每一行中必须有另一个值依赖于另一行的 WHERE

这就是 table 的样子。

业务单位GUID |类名 |默认 GUID

    5        | PriceList | 349FDAFD34M
    5        | Footer1   | 987IOXG376L
    5        | Header1   | 12WQX954MIO
    7        | PriceList | NULL
    7        | Footer1   | NULL
    7        | Header1   | NULL

结果应该是这样的。

业务单位GUID |类名 |默认 GUID

    5        | PriceList | 349FDAFD34M
    5        | Footer1   | 987IOXG376L
    5        | Header1   | 12WQX954MIO
    7        | PriceList | 349FDAFD34M
    7        | Footer1   | 987IOXG376L
    7        | Header1   | 12WQX954MIO

但是这个显示的查询不起作用,因为它 returns 行很多,所以不精确。

update cSC_BusinessUnit
set defaultguid =
    (
    select defaultguid
    from cSC_BusinessUnit 
    where BusinessUnitGUID = 5
    )
where BusinessUnitGUID = 7

这是否解决了您的问题?

update cSC_BusinessUnit t1
set defaultguid =
    (
    select defaultguid
    from cSC_BusinessUnit t2
    where t2.BusinessUnitGUID = 5
    and t1.classname = t2.classname
    )
where BusinessUnitGUID = 7

您还需要检查 ClassName:

update b1
set b1.defaultguid =
    (
    select b2.defaultguid
    from cSC_BusinessUnit b2
    where b2.BusinessUnitGUID = 5
        AND b2.ClassName = b1.ClassName
    )
from cSC_BusinessUnit b1
where b1.BusinessUnitGUID = 7

只要 ClassName NOT NULL

只有一次出现,您也可以像这样动态设置所有 NULL 列
update A
set DefaultGUID =
    (
        select B.DefaultGUID
        from cSC_BusinessUnit B
        where B.ClassName = A.ClassName
        And B.DefaultGUID IS NOT NULL
    )
from cSC_BusinessUnit A

你可以试试

update cSC_BusinessUnit a
set a.defaultguid =
    (
    select defaultguid
    from cSC_BusinessUnit b
    where b.BusinessUnitGUID = 5 and b.ClassName = a.ClassName
    )
where a.BusinessUnitGUID = 7

也使用下面的简短版本

UPDATE  b1
SET     b1.defaultguid = b2.defaultguid
FROM    cSC_BusinessUnit b1
        JOIN
        cSC_BusinessUnit b2
            ON b1.ClassName = b2.ClassName
                And b2.BusinessUnitGUID = 5
WHERE   b1.BusinessUnitGUID = 7
update b1
set b1.defaultguid =
    (
    select b2.defaultguid
    from cSC_BusinessUnit b2
    where b2.BusinessUnitGUID = 5
        AND b2.ClassName = b1.ClassName
    )
from cSC_BusinessUnit b1
where b1.BusinessUnitGUID = 7