当3行具有相同的值时,我需要生成Update子句

时间:2017-02-26 19:00:57

标签: sql sql-server-2008

当3行或任意数量的行具有相同的值时,我需要创建Update子句

DECLARE @Tbl_1 TABLE (Id int,ParentID int,State nvarchar(50) )
DECLARE @Tbl_2 TABLE (Id int,ParentID int,State nvarchar(50) )


INSERT INTO @Tbl_1 VALUES 
(1,10,'New')



INSERT INTO @Tbl_2 VALUES 
 (1,1,'New')
,(2,1,'New')
,(3,1,'New')

SELECT * FROM @Tbl_1
Id  ParentID    State
1   10          New

SELECT * FROM @Tbl_2
Id  ParentID    State
1   1           New
2   1           New
3   1           New

我需要设置@ Tbl_1.State ='Deducted'

当@ Tbl_2.State ='Deducted'

中所有匹配的行时

如果@ tbl_2.State看起来像这样

Id  ParentID    State
1   10          Deducted
1   10          Deducted
1   10          New

我需要@ tbl_1.State ='新'我不需要进行更新因为所有匹配的行没有='扣除'

但如果所有匹配行='扣除' 然后 我做了更新

,最终数据应如下所示 @ tbl_1

Id  ParentID    State
1   10          Deducted

@ tbl_2

Id  ParentID    State
1   10          Deducted
1   10          Deducted
1   10          Deducted

3 个答案:

答案 0 :(得分:1)

update t
set State = 'Deducted'
FROM @Tbl_1 t
where 'Deducted' = all (select State from @Tbl_2 t2 where ParentID = t.Id) 

那里解释了关键字的工作原理:http://www.dofactory.com/sql/where-any-all

答案 1 :(得分:0)

这是一种方法:

update t1
    set state = 'Deducted'
    from @tbl_1 t1
    where not exists (select 1
                      from @tbl_2 t2
                      where t2.state <> 'Deducted' and t2.id = t1.id
                     );

这解释了&#34;当@ Tbl_2.State中所有匹配的行=&#39; Deducted&#39;&#34;意思是即使'Deducted'中没有行,它也应该是@tbl_2

答案 2 :(得分:0)

您可以使用这样的更新联接:

update t1
set state = 'Deducted'
from @tbl_1 t1
join (
    select ParentID
    from @tbl_2
    group by ParentID
    having max(state) = min(state)
        and min(state) = 'Deducted'
    ) t2 on t1.id = t2.ParentID;

它会将tbl_1中的所有行更新为Deducted,其中所有行都设置为在tbl_2中扣除。如果tbl_2中没有对应的行,它将不会更新行,我假设它是按照需要的。

Demo