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
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
)
;
工作是一种享受。非常感谢你的时间、努力和帮助。