Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/sql-server-2008/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server 2008 使用select查询进行SQL更新_Sql Server 2008 - Fatal编程技术网

Sql server 2008 使用select查询进行SQL更新

Sql server 2008 使用select查询进行SQL更新,sql-server-2008,Sql Server 2008,我有一个表,其中多条记录具有相同的LocationID。其中一些记录在“UsedinSA”字段中具有“true”值。如果有一条对应的记录具有相同的“LocationID”和“UsedinSA”中的“true”值,我想将所有“PartofContract”值设置为“true” 我尝试了如下操作,但这只会更新已经为“true”的记录 UPDATE tbAsset SET tbAsset.PartofContract = 1 WHERE LocationID IN (SELECT dbo.tbAsse

我有一个表,其中多条记录具有相同的
LocationID
。其中一些记录在“UsedinSA”字段中具有“true”值。如果有一条对应的记录具有相同的“LocationID”和“UsedinSA”中的“true”值,我想将所有“PartofContract”值设置为“true”

我尝试了如下操作,但这只会更新已经为“true”的记录

UPDATE tbAsset
SET tbAsset.PartofContract = 1
WHERE LocationID IN (SELECT dbo.tbAsset.LocationID FROM dbo.tbasset where tbAsset.UsedinSA = 1)
作为数据示例:

合同一部分中使用的位置ID

  • 1563110
  • 1563100
  • 156309 11
  • 1563090
  • 记录4的“PartofContract”应设置为“True”,因为记录3为,并且它们具有相同的“LocationID”

    提前谢谢


    Matt

    试试这个-我只在表中添加了唯一约束,因为我假设您的表具有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
                   )
    ;  
    

    工作是一种享受。非常感谢你的时间、努力和帮助。