2014-02-21 70 views
0

一個專欄中,我有兩個表:的SQL Server 2008:更新基於環路上的另一臺

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,L-型永遠是A1,C2,B1和E2爲了讓每一個的Pid 。現在,我想基於下一isactive從TBLA填充upcoming_Ltype = 1 L-型從TBLB

預期結果:

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

沒有訂單。 – gvee

+0

A1,C2,B1,E2是order。我們可以在臨時表中分別給它們分配數字1,2,3和4。 –

回答

-1

Pune是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 
相關問題