I've tables and data as follow,declare @t1 table(DDate datetime, RID varchar(30), Posi tinyint, TripN varchar(20), Busn varchar(10), mflg bit);insert into @t1 values('20100802','_R100400000001',1,'trip1','wkm1925',0);insert into @t1 values('20100802','_R100400000001',2,'trip2','wnr4474',0);insert into @t1 values('20100803','_R100400000001',1,'trip1','wkm1925',0);insert into @t1 values('20100803','_R100400000001',2,'trip2','wkm4474',0);insert into @t1 values('20100804','_R100400000001',1,'trip1','wkm1925',0);/*@t1(DDate, RID, Posi) is unique*/declare @t2 table(DDate datetime, RID varchar(30), Posi tinyint, TripN varchar(20), Busn varchar(10), mflg bit);insert into @t2 values('20100802','_R100400000001',1,'trip1','ack6796',0);insert into @t2 values('20100803','_R100400000001',1,'trip2','wkm1925',1);insert into @t2 values('20100807','_R100400000001',1,'trip1','wkm4474',0);/*@t2(DDate, RID, Posi) is unique*/1. I want to insert/update @t1 into @t2?2. If row not exist in @t2, perform insert3. If row exist in @t2 and mflg=0, perform updateMy expected result as follow,@t2DDate | RID | Posi | TripN | Busn | mflg-----------------------------------------------------------------------------20100802 _R100400000001 1 trip1 wkm1925 0 --- update20100802 _R100400000001 2 trip2 wnr4474 0 --- insert20100803 _R100400000001 1 trip2 wkm1925 1 --- not updated because of mflg=120100803 _R100400000001 2 trip2 wkm4474 0 --- insert20100804 _R100400000001 1 trip1 wkm1925 0 --- insert20100807 _R100400000001 1 trip1 wkm4474 0 --- not effected because existing row
How my T-SQL look's like?