带有WHERE的SQL UPDATE SELECT

问题描述 投票:1回答:6

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

这是表格的外观。

BusinessUnitGUID |类名| DefaultGUID

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

结果应该是这个。

BusinessUnitGUID |类名| DefaultGUID

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

但是此显示的查询不起作用,因为它返回许多行,因此不精确。

update cSC_BusinessUnit
set defaultguid =
    (
    select defaultguid
    from cSC_BusinessUnit 
    where BusinessUnitGUID = 5
    )
where BusinessUnitGUID = 7
sql sql-server select where
6个回答
5
投票

您还需要检查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

2
投票

也使用以下简短版本

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

0
投票

这能解决您的问题吗?

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

0
投票

您还可以像这样动态设置所有NULL列,只要您只出现ClassName NOT 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

0
投票

您可以尝试

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

-1
投票
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
© www.soinside.com 2019 - 2024. All rights reserved.