我有一张桌子:
CREATE TABLE STOTMARS
(
KODAS integer NOT NULL,
PUNKTAS varchar(50) NOT NULL,
MARS varchar(10) NOT NULL,
EILNR integer NOT NULL,
METRAI integer NOT NULL,
VIDGR integer NOT NULL,
TARPINIS varchar(1),
CONSTRAINT STOTMARS_ID PRIMARY KEY (KODAS,PUNKTAS,MARS,EILNR)
);
CREATE INDEX STOTMARS_EILNR ON STOTMARS (EILNR);
CREATE INDEX STOTMARS_KODAS ON STOTMARS (KODAS);
CREATE INDEX STOTMARS_MARS ON STOTMARS (MARS);
CREATE INDEX STOTMARS_PUNKTAS ON STOTMARS (PUNKTAS);
GRANT DELETE, INSERT, REFERENCES, SELECT, UPDATE
ON STOTMARS TO SYSDBA WITH GRANT OPTION;
我需要在PUNKTAS =' Dvaro st.3'的行中更新EILNR的值。来自行的EILNR值具有相同的KODAS值和PUNKTAS值' Centro st.1'
到目前为止,我试过了:
update STOTMARS a
set a.EILNR = (
select
b.EILNR
from STOTMARS b
where a.PUNKTAS = 'Centro st.1' and a.MARS = b.MARS
)
where a.PUNKTAS = 'Dvaro st.3'
但是这给了我错误:
Executing statement...
Error: *** IBPP::SQLException ***
Context: Statement::Execute( update STOTMARS a
set a.EILNR = (
select
b.EILNR
from STOTMARS b
where a.PUNKTAS = 'Centro st.1' and a.MARS = b.MARS
)
where a.PUNKTAS = 'Dvaro st.3' )
Message: isc_dsql_execute2 failed
SQL Message : -625
The insert failed because a column definition includes validation constraints.
Engine Code : 335544347
Engine Message :
validation error for column EILNR, value "*** null ***"
Total execution time: 0.000s
使查询更清晰:
select
a.MARS, a.EILNR, b.EILNR
from STOTMARS a
join STOTMARS b
on a.MARS = b.MARS and b.PUNKTAS = 'Dvaro st.3'
where a.PUNKTAS = 'Centro st.1'
给我一个表格,其中每个第三列值应替换为该行的第二列值。
答案 0 :(得分:1)
问题是内部选择没有产生任何行,因此更新尝试分配null
,因为所应用的条件是互斥的,并且由于NOT NULL
约束而失败{1}}:
EILNR
update STOTMARS a
set a.EILNR = (
select
b.EILNR
from STOTMARS b
where a.PUNKTAS = 'Centro st.1' and a.MARS = b.MARS
)
where a.PUNKTAS = 'Dvaro st.3'
不能同时为a.PUNKTAS
和'Centro st.1'
。内部选择中的条件应该使用'Dvaro st.3'
:
b.PUNKTAS
您可能还想考虑使用MERGE
而不是此相关更新。
答案 1 :(得分:0)
您可以通过多种方式避免NULL
。一种方法是用适当的值替换值:
update STOTMARS a
set a.EILNR = (select coalesce(max(b.EILNR), 0)
from STOTMARS b
where a.PUNKTAS = 'Centro st.1' and a.MARS = b.MARS
)
where a.PUNKTAS = 'Dvaro st.3';
或者,添加一个比较子句:
update STOTMARS a
set a.EILNR = (select coalesce(max(b.EILNR), 0)
from STOTMARS b
where a.PUNKTAS = 'Centro st.1' and a.MARS = b.MARS
)
where a.PUNKTAS = 'Dvaro st.3' and
(select b.EILNR
from STOTMARS b
where a.PUNKTAS = 'Centro st.1' and a.MARS = b.MARS
) is not null;
请注意,这不会使用not exists
,因此可以考虑NULL
值sin EILNR
。