create table tableone ( TableoneID varchar(50), orderNo varchar(20), Ordernumber varchar(20), NUB1 int ) insert into tableone values (NEWID() ,'S001', 'X3600000001', 2), (NEWID() ,'S001', 'X3600000002', 2), ( NEWID() ,'S002', 'X3600000003', 6), ( NEWID() ,'S002', 'X3600000004', 6), (NEWID() ,'S003', 'X3600000005', 6), (NEWID() ,'S003', 'X3600000006', 8) create table tabletwo ( TabletwoID varchar(50), orderNo varchar(20), Deliveryitem varchar(20), NUB2 int ) insert into tabletwo values (NEWID(), 'S001', 'D3600000001', 4), (NEWID(), 'S002', 'D3600000002', 7), (NEWID(), 'S003', 'D3600000003', 8), (NEWID(), 'S003', 'D3600000004', 4), (NEWID(), 'S003', 'D3600000005', 2); -- SQL Server WITH /* Table1(TableoneID,orderNo,Ordernumber,NUB1)AS( SELECT NEWID(),'S001','X3600000001',2 UNION ALL SELECT NEWID(),'S001','X3600000002',2 UNION ALL SELECT NEWID(),'S002','X3600000003',6 UNION ALL SELECT NEWID(),'S002','X3600000004',6 UNION ALL SELECT NEWID(),'S003','X3600000005',6 UNION ALL SELECT NEWID(),'S003','X3600000006',8 ) ,Table2(TabletwoID,orderNo,Deliveryitem,NUB2)AS( SELECT NEWID(),'S001','D3600000001',4 UNION ALL SELECT NEWID(),'S002','D3600000002',7 UNION ALL SELECT NEWID(),'S003','D3600000003',8 UNION ALL SELECT NEWID(),'S003','D3600000004',4 UNION ALL SELECT NEWID(),'S003','D3600000005',2 ), */ t1 AS ( SELECT *, ROW_NUMBER()OVER(PARTITION BY orderNo ORDER BY orderNumber) rn FROM tableone ) ,t2 AS ( SELECT *, ROW_NUMBER()OVER(PARTITION BY orderNo ORDER BY Deliveryitem) rn FROM tabletwo ) ,t3 AS ( SELECT ISNULL(t1.orderNo,t2.orderNo) orderNo, ISNULL(t1.rn,t2.rn) rn, t1.Ordernumber, t1.NUB1, t2.Deliveryitem, t2.NUB2 FROM t1 FULL JOIN t2 ON t1.orderNo = t2.OrderNo AND t1.rn = t2.rn ) SELECT NEWID() MergeTableID, CASE WHEN rn=1 THEN orderNo ELSE NULL END orderNo, Ordernumber, NUB1, Deliveryitem, NUB2 FROM t3 ORDER BY t3.orderNo, rn
以上内容在sql2008中实现,为了效率就没用游标