使用select查询的SQL Update

时间:2014-08-05 12:31:27

标签: sql-server-2008

我有一张表,其中多条记录具有相同的LocationID。其中一些记录中有一个真实的' ' UsedinSA'中的价值领域。我想设置所有' PartofContract'值为' true'如果有一个相应的记录具有相同的' LocationID'和一个真实的' < UsedinSA'中的价值。

我尝试如下,但这只会更新已经“真实”的记录。

UPDATE tbAsset
SET tbAsset.PartofContract = 1
WHERE LocationID IN (SELECT dbo.tbAsset.LocationID FROM dbo.tbasset where tbAsset.UsedinSA = 1)

作为数据的一个例子:

LocationID UsedinSA PartofContract

  1. 156311 0 0
  2. 156310 0 0
  3. 156309 1 1
  4. 156309 0 0
  5. 记录4应该有' PartofContract'设为' True'因为记录3是,并且它们具有相同的位置ID'。

    提前致谢

    马特

1 个答案:

答案 0 :(得分:2)

试试这个 - 我只提出了唯一约束,因为我假设你的表有PK或唯一约束:

use tempdb  --somewhere safe for a sandbox
--==========================================
drop    table dbo.tbAsset
;
--create some test data
select  1 as record_id --pk
        ,156311 as LocationID 
        ,0 as UsedinSA 
        ,0 as PartofContract
into    dbo.tbAsset
union   all
select  2 as record_id 
        ,156310 as LocationID 
        ,0 as UsedinSA 
        ,0 as PartofContract
union   all
select  3 as record_id
        ,156309 as LocationID 
        ,1 as UsedinSA 
        ,1 as PartofContract
union   all
select  4 as record_id
        ,156309 as LocationID 
        ,0 as UsedinSA 
        ,0 as PartofContract
;
create  unique clustered index ix_tbAsset_record_id on dbo.tbAsset(record_id)
;
--==========================================
with was_used_in_usa as 
        (
                SELECT ass.LocationID
                FROM dbo.tbAsset ass
                WHERE ass.UsedinSA = 1
        )
update  ass
set     ass.PartofContract = 1
from    dbo.tbAsset ass
where   exists ( select  * 
                 from    was_used_in_usa 
                 where   ass.LocationID = was_used_in_usa.LocationID
               )
;