我正在将数据(导入)从表 tmp_header 复制到 as_solution2 表中,需要在目标表中检查第一个IdNumber和Date,以免复制重复的值。如果在命运表中找到了date和idNumber,则我不复制该行,如果找不到,则将行复制到表as_solution2中。 源表具有800.000条记录,而目的地表已包含200.000条记录。
腔室:“ as_solution2”表中的id_solution pk不是串行的,因此我创建了一个序列并从最后一个id开始。
v_max_cod_solicitud := (select max(id_solution)+1 from municipalidad.as_solution2);
CREATE SEQUENCE increment START v_max_cod_solicitud;
这会引发错误error
tmp_header(id,cod_cause,idNumber,date_sol(2012-05-12),glosa_desc) as_solution2(id_solution,cod_cause,idNumber,date_sol,desc)
CREATE OR REPLACE FUNCTION municipalidad.as_importar()
RETURNS integer AS
$$
DECLARE
v_max_cod_solicitud numeric;
id_solution numeric;
begin
v_max_cod_solicitud := (select max(id_solution)+1 from municipalidad.as_solution2);
CREATE SEQUENCE increment START v_max_cod_solicitud;
INSERT INTO municipalidad.as_solution2(
id_solution,
cod_cause,
idNumber,
date_sol,
desc,
)
SELECT
(SELECT nextval('increment')), <-- when saving i need to start from the last sequence number
cod_causingreso,
idNumber,
date_sol,
glosa_atenc,
FROM municipalidad.tmp_header as tmp_e
WHERE(SELECT count(*)
FROM municipalidad.as_solution2 as s2
WHERE s2.idNumber = tmp_e.idNumber AND s2.date_sol::date = tmp_e.date_sol::date)=0;
drop sequence increment;
return 1;
end
$$
LANGUAGE 'plpgsql'
预先感谢
答案 0 :(得分:1)
您可以使用start参数强行执行序列,如下所示:
execute (format ('CREATE SEQUENCE incremento start %s', v_max_cod_solicitud));
无关,但是我认为您可以通过将插入更改为使用反联接而不是Where select count (*) = 0
来提高效率:
INSERT INTO as_solution2(
id_solution,
cod_cause,
idNumber,
date_sol,
description
)
SELECT
nextval('incremento'), -- when saving i need to start from the last sequence number
cod_causingreso,
idNumber,
date_sol,
glosa_atenc
FROM tmp_header as tmp_e
WHERE not exists (
select null
from as_solution2 s2
where
s2.idNumber = tmp_e.idNumber AND
s2.date_sol::date = tmp_e.date_sol::date
)
这将随着数据集大小的增加而很好地扩展。
答案 1 :(得分:0)
即使未在https://www.postgresql.org/docs/9.5/sql-keywords-appendix.html中将其列为保留关键字,也可能不允许在此处创建序列语句:
CREATE SEQUENCE increment START v_max_cod_solicitud;
如解析器所期望的那样:
ALTER SEQUENCE name [ INCREMENT [ BY ] increment ]
它可能以为您忘记了名字