gpt4 book ai didi

postgresql - 在 PostgreSQL 中更新引用表时如何违反重复键约束(Unique_Violation)?

转载 作者:行者123 更新时间:2023-11-29 13:56:31 25 4
gpt4 key购买 nike

在 PostgreSQL 9.1 版中,我有两个表:ICD9 和 Dx。我现在希望通过将现有记录更改为不同的键值(在 cdesc 中)来更新父表 ICD9。

如果 ICD9 表中不存在新键 (cicd9,cdesc),则将新值级联到子表,Dx :-)

但是,如果具有新值cdesc的"new"键已经存在于ICD9表中,则记录不会更新,因为

错误 23505:重复键值违反唯一约束“constraint_cdesc”。

我需要做的是父表 ICD9 的更新将旧记录更新为新值并且此更新级联到 DX 中使用旧键的所有子记录然后删除现在ICD9 表中未使用的“旧”记录。

如果能为这个新手提供任何帮助,我们将不胜感激。时间差

CREATE TABLE icd9
(
cicd9 character varying(8),
cdesc character varying(80) NOT NULL,
CONSTRAINT constraint_cdesc UNIQUE (cicd9, cdesc),
CONSTRAINT desccheck CHECK (cdesc::text <> ''::text)
)

CREATE TABLE dx
(
cicd9 character varying(8),
cdesc character varying(80) NOT NULL,
CONSTRAINT fk_icd9 FOREIGN KEY (cicd9, cdesc)
REFERENCES icd9 (cicd9, cdesc) MATCH SIMPLE
ON UPDATE CASCADE ON DELETE RESTRICT DEFERRABLE INITIALLY DEFERRED
)

编辑#1:我想我简化了这些表结构以澄清我的观点,这里是完整的结构。非常感谢任何帮助。

CREATE TABLE dx
(
recid serial NOT NULL,
cpatient character varying(33) NOT NULL,
cicd9 character varying(8),
cdesc character varying(80) NOT NULL,
tposted timestamp without time zone NOT NULL,
"timestamp" timestamp without time zone DEFAULT now(),
modified timestamp without time zone DEFAULT now(),
resolved boolean DEFAULT false,
treated boolean DEFAULT false,
chronic boolean DEFAULT false,
groupid character varying(33) NOT NULL,
service integer DEFAULT 0,
pmh boolean DEFAULT false,
explanation text,
CONSTRAINT pk_dx_recid PRIMARY KEY (recid),
CONSTRAINT dx_cpatient_fkey FOREIGN KEY (cpatient)
REFERENCES patients (cpatient) MATCH SIMPLE
ON UPDATE CASCADE ON DELETE RESTRICT,
CONSTRAINT dx_groupid_fkey FOREIGN KEY (groupid)
REFERENCES charts (groupid) MATCH SIMPLE
ON UPDATE CASCADE ON DELETE RESTRICT,
CONSTRAINT fk_icd9 FOREIGN KEY (cicd9, cdesc)
REFERENCES icd9 (cicd9, cdesc) MATCH SIMPLE
ON UPDATE CASCADE ON DELETE RESTRICT DEFERRABLE INITIALLY DEFERRED,
CONSTRAINT noduplicate_dx UNIQUE (cicd9, cdesc, groupid, tposted),
CONSTRAINT desccheck CHECK (cdesc::text <> ''::text),
CONSTRAINT groupcheck CHECK (groupid::bpchar <> ''::bpchar),
CONSTRAINT patientcheck CHECK (cpatient::bpchar <> ''::bpchar)
)
WITH (
OIDS=FALSE
);
ALTER TABLE dx
OWNER TO postgres;


CREATE TABLE icd9
(
recid serial NOT NULL,
cicd9 character varying(8),
cdesc character varying(80) NOT NULL,
"timestamp" timestamp without time zone DEFAULT now(),
modified timestamp without time zone DEFAULT now(),
chronic boolean NOT NULL DEFAULT false,
common boolean NOT NULL DEFAULT false,
CONSTRAINT pk_icd9_recid PRIMARY KEY (recid),
CONSTRAINT constraint_cdesc UNIQUE (cicd9, cdesc),
CONSTRAINT desccheck CHECK (cdesc::text <> ''::text)
)
WITH (
OIDS=FALSE
);
ALTER TABLE icd9
OWNER TO postgres;

最佳答案

除了表设计中可能存在的错误外,我找不到任何方法来暂时中止“unique_violation”,它来自将记录的键值更新为另一条记录所持有的值。在上面的设计中,ICD9 文件旨在作为一个库,其中的记录可能会或可能不会在系统的其他地方使用。

该题的解决方法是将引用该库的表中的子记录移走,然后删除会引起冲突的记录。大部分代码来自 Finding Foreign Keys with No Indexes并特别感谢@Patrick 提供了完成这项工作所需的最终 key 。下面是执行这项工作的代码(对我有用)。希望对某人有所帮助。

CREATE OR REPLACE FUNCTION g_saveicd9(ocicd9 text, ocdesc text, ncicd9 text, ncdesc text, nchronic boolean, ncommon boolean)
RETURNS void AS
$BODY$
DECLARE
-- Declare row format
o ICD9%rowtype;
n ICD9%rowtype;

BEGIN
-- Existing key values
o.cicd9 := ocicd9;
o.cdesc := ocdesc;

-- New record values
n.cicd9 := ncicd9;
n.cdesc := ncdesc;
n.chronic := nchronic;
n.common := ncommon;

-- Must set contraints all immediate to trigger constraints immediately for exceptions.
SET CONSTRAINTS ALL IMMEDIATE;

BEGIN
-- Edit ICD9 record.
UPDATE icd9 SET
cicd9 = n.cicd9, cdesc = n.cdesc, chronic = n.chronic, common = n.common
WHERE
cicd9 = o.cicd9 and cdesc = o.cdesc;

IF FOUND THEN
-- Successfully changed an existing record to new values. (The new value did not already exist). Exit function.
RETURN;
END IF;

EXCEPTION

WHEN unique_violation THEN

-- The new key already exists, so need to manually move all children to the "new" key.
PERFORM merge_children_of_icd9(o.cicd9, o.cdesc, n.cicd9, n.cdesc);

-- Remove the old key values from ICD9
DELETE FROM icd9
WHERE cicd9 = o.cicd9 and cdesc = o.cdesc;

-- Update existing record.
UPDATE icd9 SET
chronic = n.chronic, common = n.common
WHERE
cicd9 = n.cicd9 and cdesc = n.cdesc;

RETURN; -- Exit function.
END;

-- No record found to update, so create new record.
BEGIN
INSERT INTO icd9(
cicd9, cdesc, chronic, common)
VALUES (
n.cicd9, n.cdesc, n.chronic, n.common);

-- Successfully inserted a new icd9 record, so exit function. This line is not reached if INSERT throws an exception.
RETURN;

EXCEPTION

WHEN unique_violation THEN

-- Key (o.cicd9,o.cdesc) not found for update, but target key (n.cicd9,n.cdesc) already exists.
-- Update target record with non-key values.
UPDATE icd9 SET
chronic = n.chronic, common = n.common
WHERE
cicd9 = n.cicd9 and cdesc = n.cdesc;

RETURN;

END;

END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION g_saveicd9(text, text, text, text, boolean, boolean)
OWNER TO postgres;


CREATE OR REPLACE FUNCTION merge_children_of_icd9(ocicd9 text, ocdesc text, ncicd9 text, ncdesc text)
RETURNS void AS
$BODY$

DECLARE
r RECORD;

BEGIN
FOR r IN

WITH fk_actions ( code, action ) AS (
VALUES ( 'a', 'error' ),
( 'r', 'restrict' ),
( 'c', 'cascade' ),
( 'n', 'set null' ),
( 'd', 'set default' )
),
fk_list AS (
SELECT pg_constraint.oid as fkoid, conrelid, confrelid::regclass as parentid,
conname, relname, nspname,
fk_actions_update.action as update_action,
fk_actions_delete.action as delete_action,
conkey as key_cols
FROM pg_constraint
JOIN pg_class ON conrelid = pg_class.oid
JOIN pg_namespace ON pg_class.relnamespace = pg_namespace.oid
JOIN fk_actions AS fk_actions_update ON confupdtype = fk_actions_update.code
JOIN fk_actions AS fk_actions_delete ON confdeltype = fk_actions_delete.code
WHERE contype = 'f'
),
fk_attributes AS (
SELECT fkoid, conrelid, attname, attnum
FROM fk_list
JOIN pg_attribute
ON conrelid = attrelid
AND attnum = ANY( key_cols )
ORDER BY fkoid, attnum
),
fk_cols_list AS (
SELECT fkoid, array_agg(attname) as cols_list
FROM fk_attributes
GROUP BY fkoid
)
SELECT fk_list.fkoid, fk_list.conrelid, fk_list.parentid, fk_list.conname, fk_list.relname, fk_cols_list.cols_list
FROM fk_list
JOIN fk_cols_list USING (fkoid)
WHERE parentid = 'icd9'::regclass

LOOP

-- In an UPDATE statement in PL/pgSQL, the table name has to be given as a literal. If you want to dynamically set the
-- table name and the columns, use the EXECUTE command and paste the query string together.
-- The USING clause can only be used for substituting data values.
-- cols_list[1] is cicd9. cols_list[2] is cdesc.

EXECUTE 'UPDATE ' || quote_ident(r.relname) ||
' SET ' || quote_ident(r.cols_list[1]) || ' = $1, '
|| quote_ident(r.cols_list[2]) || ' = $2' ||
' WHERE ' || quote_ident(r.cols_list[1]) || ' = $3 AND '
|| quote_ident(r.cols_list[2]) || ' = $4'
USING ncicd9, ncdesc, ocicd9, ocdesc;

END LOOP;

RETURN;
END
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION merge_children_of_icd9(text, text, text, text)
OWNER TO postgres;

关于postgresql - 在 PostgreSQL 中更新引用表时如何违反重复键约束(Unique_Violation)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30696558/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com