SQL Server 2008:基于另一个表上的循环更新列

时间:2014-02-21 17:19:20

标签: sql-server sql-update

我有两张桌子:

create table  tblA (Pid int, Ltype varchar(2), upcoming_Ltype varchar(2))
insert into tblA (pid, ltype)
values
(123, 'A1'),
(123, 'C2'),
(567, 'B1'),
(457, 'A1')

create table tblB (Pid int, Ltype varchar(2), isactive bit)
insert into tblB (Pid, Ltype, isactive)
values
(123,'A1',1),
(123,'C2',1),
(123,'B1',1),
(123,'E2',1),

(567,'A1',1),
(567,'C2',1),
(567,'B1',1),
(567,'E2',1),

(457,'A1',1),
(457,'C2',0),
(457,'B1',1),
(457,'E2',1)

这里,请注意,在tblB中,Ltype始终为A1,C2,B1和E2,以便每个Pid。现在,我想根据来自tblB的下一个isactive = 1 Ltype来填充来自tblA的coming_Ltype

预期结果:

TBLA:

(123, 'A1',C2), 
(123, 'C2',B1),
(567, 'B1',E2),
(457, 'A1',B1)   <-- skipping C2

这是我的努力(不工作):

UPDATE tblA
SET upcoming_Ltype =
(
  SELECT Ltype
  FROM tblB
  WHERE tblA.Pid = tblB.Pid 
  AND tblB.isActive = 1
  AND tblB.Ltype > tblA.Ltype 
)

1 个答案:

答案 0 :(得分:-1)

那是来自浦那的Bhupinder Singh吗?

如果您创建一个选择查询来计算值,那么您可以在更新

中加入它
use tempdb
CREATE Table #order_lkp
(Ltype varchar(2) not null UNIQUE, sortorder int identity)

INSERT #order_lkp VALUES('A1'), ('C2'), ('B1'), ('E2')

create table  tblA (Pid int, Ltype varchar(2), upcoming_Ltype varchar(2))
insert into tblA (pid, ltype)
values
(123, 'A1'),
(123, 'C2'),
(567, 'B1'),
(457, 'A1')

create table tblB (Pid int, Ltype varchar(2), isactive bit)
insert into tblB (Pid, Ltype, isactive)
values
(123,'A1',1),
(123,'C2',1),
(123,'B1',1),
(123,'E2',1),

(567,'A1',1),
(567,'C2',1),
(567,'B1',1),
(567,'E2',1),

(457,'A1',1),
(457,'C2',0),
(457,'B1',1),
(457,'E2',1)
GO
WITH UPCOMING_LKP AS
(
SELECT find_upcoming_sortorder.Pid, find_upcoming_sortorder.Ltype,
o.Ltype AS upcoming_Ltype 
 FROM 
(
SELECT 
ta.Pid, 
ta.Ltype, 
ta.sortorder
,MIN(tb.sortorder )
AS upcoming_sortorder
FROM 
(SELECT tblA.Ltype,tblA.Pid,sortorder FROM tblA JOIN  #order_lkp ON tblA.Ltype =  #order_lkp.Ltype) ta
LEFT JOIN  
(SELECT tblB.Ltype,tblB.Pid,sortorder FROM tblB JOIN  #order_lkp ON tblB.Ltype =  #order_lkp.Ltype WHERE tblB.isactive <> 0 ) tb
ON 
ta.Pid= tb.Pid  
AND tb.sortorder > ta.sortorder 
GROUP BY ta.Pid, ta.Ltype 
,ta.sortorder
) find_upcoming_sortorder
JOIN #order_lkp o ON o.sortorder = find_upcoming_sortorder.upcoming_sortorder
)


UPDATE a 
SET a.upcoming_Ltype = lkp.upcoming_Ltype
FROM tblA  a
JOIN UPCOMING_LKP lkp ON a.Pid = lkp.Pid AND a.Ltype = lkp.Ltype


GO
DROP table  tblA ;
GO
DROP table  tblB;
GO
DROP Table #order_lkp