2016-09-12 4 views
1

Bitte meine Probe sehen, wie unten:Kann aktualisieren sich nicht in SQL Server 2008 R2

create table tbl1(cl1 int, cl2 varchar(10)) 
create table tbl2(cl1 int, cl2 varchar(10)) 

insert tbl1 
select 1, 'a' union all 
select 1, 'b' union all 
select 1, 'c' union all 
select 1, 'd' union all 
select 1, 'e' 

insert tbl2 
select 1, '' union all 
select 1, '' union all 
select 1, 'c' union all 
select 1, '' union all 
select 1, 'a' 

select * from tbl1 
select * from tbl2 

update b 
set b.cl2 = a.cl2 
from tbl1 a inner join tbl2 b on a.cl1=b.cl1 
where b.cl2 = '' and a.cl2 not in (select cl2 from tbl2 where tbl2.cl1 = a.cl1) 

Was ich will, ist es, alle leeren Wert bei Cl2 Spalte in tbl2 Tabelle zu aktualisieren, mit nicht Werte duplizieren.

Ich habe versucht, wie das Skript oben zu laufen, aber es hat nicht richtig funktioniert.

Bitte helfen Sie mir, die Lösung zu finden.

Danke.

+0

Letzte Auswahl dient zum Einfügen von Daten nach tbl2. –

Antwort

0

Versuchen Sie dieses Skript.

create table #tbl1(cl1 int, cl2 varchar(10)) 
create table #tbl2(cl1 int, cl2 varchar(10)) 

insert #tbl1 
select 1, 'a' union all 
select 1, 'b' union all 
select 1, 'c' union all 
select 1, 'd' union all 
select 1, 'e' 

insert #tbl2 
select 1, '' union all 
select 1, '' union all 
select 1, 'c' union all 
select 1, '' union all 
select 1, 'a' 

    update b 
    set b.cl2 = a.cl2 
    from #tbl1 a inner join #tbl2 b on a.cl1=b.cl1 
    where b.cl2 = '' and a.cl2 not in (select t.cl2 from #tbl2 t where a.cl1 = a.cl1) 

Select * from #tbl1 
Select * from #tbl2 
+0

Dies gilt immer 'where a.cl1 = a.cl1' –

+0

ja, aber es gibt die gewünschte Ausgabe wie erwartet. Sie können die Bedingung aus der Unterabfrage entfernen. –

+0

hi haresh hanat, ich führe deine Probe, das Ergebnis ist mein Ergebnis. Der Wert 'b' erscheint in 2 Zeilen (Zeile 1 und Zeile 4). Es hat immer noch doppelte Daten. –

Verwandte Themen