我的語句如下:
update kc set kc_cw=(select kc_cw1 from kc1 where kc_plbh=kc_plbh1 and kc_zh=kc_zh1 and kc_cw<>kc_cw1)
如果加上"and kc_cw1<>kc_cw1就會報不能把null值給kc_cw,去掉這一句不會有錯,但我想kc_cw不同的才更新呀,如何做呢。如果是sqlserver如句應如下:經驗告訴我,下面語句在sqlserver執行就沒有問題。
update kc set kc_cw=kc_cw1
from kc1
where kc_plbh=kc_plbh1
and kc_zh=kc_zh1
and kc_cw<>kc_cw1
有什麼辦法讓我隻更新kc_cw不同的行,如果去掉它數據量太大了不知要更新多久。
update kc set kc_cw=(select kc_cw1 from kc1 where kc_plbh=kc_plbh1 and kc_zh=kc_zh1 and kc_cw<>kc_cw1)
如果加上"and kc_cw1<>kc_cw1就會報不能把null值給kc_cw,去掉這一句不會有錯,但我想kc_cw不同的才更新呀,如何做呢。如果是sqlserver如句應如下:經驗告訴我,下面語句在sqlserver執行就沒有問題。
update kc set kc_cw=kc_cw1
from kc1
where kc_plbh=kc_plbh1
and kc_zh=kc_zh1
and kc_cw<>kc_cw1
有什麼辦法讓我隻更新kc_cw不同的行,如果去掉它數據量太大了不知要更新多久。
set a.kc_cw=(select b.kc_cw1
from kc1 b
where a.kc_plbh = b.kc_plbh1
and a.kc_zh = b.kc_zh1 )
where exists(select 1 from kc1 c where a.kc_plbh = c.kc_plbh1 and a.kc_zh = c.kc_zh1 and a.kc_cw <> c.kc_cw1)这样呢?将条件放外面
update kc a
set a.kc_cw=(select b.kc_cw1
from kc1 b
where a.kc_plbh = b.kc_plbh1
and a.kc_zh = b.kc_zh1 )
where a.kc_cw<>c.kc_cw1
set a.kc_cw=(select b.kc_cw1
from kc1 b
where a.kc_plbh = b.kc_plbh1
and a.kc_zh = b.kc_zh1 )
where exists(select * from kc1 c where a.kc_plbh = c.kc_plbh1 and a.kc_zh = c.kc_zh1 and a.kc_cw <> c.kc_cw1)
select kc_cw1 from kc1 where kc_plbh=kc_plbh1 and kc_zh=kc_zh1 and kc_cw <>kc_cw1
产生了null执行上述的,察看下结果集构成
我還這樣查看了
select *
from (
select kc_cw1 from kc1 where kc_plbh=kc_plbh1 and kc_zh=kc_zh1 and kc_cw <>kc_cw1 )
a
where kc_cw1 is null
這樣查後沒查到值。
T2.KC_CW
FROM KC1 T1,
KC T2
WHERE KC_PLBH = KC_PLBH1
AND KC_ZH = KC_ZH1
AND KC_CW <> KC_CW1) J1
Set KC_CW = KC_CW1
试试这样....
空值的问题,如果kc_cw非空,那么kc_cw1最好也设为非空
如果kc_cw1没有非空约束,就添加条件
kc_cw1 is not nullupdate kc a
set a.kc_cw=(select b.kc_cw1
from kc1 b
where a.kc_plbh = b.kc_plbh1
and a.kc_zh = b.kc_zh1 b.kc_cw is not null)
where a.kc_cw<>b.kc_cw1
using kc1
on (kc.plbh=kc1.plbh1 and kc.kc_zh=kc1.kc_zh1 and kc.kc_cw<>kc1.kc_cw1)
when matched then
update set kc.kc_cw=kc1.kc_cw1;
using kc1
on (kc.plbh=kc1.plbh1 and kc.kc_zh=kc1.kc_zh1 and kc.kc_cw <>kc1.kc_cw1)
when matched then
update set kc.kc_cw=kc1.kc_cw1; update kc a
set a.kc_cw=(select b.kc_cw1
from kc1 b
where a.kc_plbh = b.kc_plbh1
and a.kc_zh = b.kc_zh1 b.kc_cw is not null)
where a.kc_cw<>b.kc_cw1
以上兩個語法通不過。update kc a
set a.kc_cw=(select b.kc_cw1
from kc1 b
where a.kc_plbh = b.kc_plbh1
and a.kc_zh = b.kc_zh1 )
where exists(select * from kc1 c where a.kc_plbh = c.kc_plbh1 and a.kc_zh = c.kc_zh1 and a.kc_cw <> c.kc_cw1)
正在運行中......
你的原sql的错误是由于在找不到匹配的值时会返回null导致的,
而set语句中的子查询的结果又无法在where中重复使用,所以1楼的方法很正确了,
where语句剔除了相同的记录,返回null的行不会被更新。一直觉得这样做比较没效率,两个子查询不能共用,可是没办法在一条sql中解决
所以你可以试着使用视图来更新,或者在kc_cw1上建立触发器,自动更新.
set a.kc_cw=(select b.kc_cw1
from kc1 b
where a.kc_plbh = b.kc_plbh1
and a.kc_zh = b.kc_zh1 )
where exists(select * from kc1 c where a.kc_plbh = c.kc_plbh1 and a.kc_zh = c.kc_zh1 and a.kc_cw <> c.kc_cw1)