Postgresql 有没有办法读取行并使其无法读取

Postgresql 有没有办法读取行并使其无法读取,postgresql,concurrency,Postgresql,Concurrency,我有一个下表模式 CREATE TABLE public.crewcode ( crewcodeid integer NOT NULL DEFAULT nextval('crewcode_crewcodeid_seq'::regclass), nationality character varying(20) COLLATE pg_catalog."default", code character varying(10) COLLATE pg_catalog."de

我有一个下表模式

CREATE TABLE public.crewcode (
crewcodeid integer NOT NULL DEFAULT nextval('crewcode_crewcodeid_seq'::regclass),
nationality character varying(20) COLLATE pg_catalog."default",
code character varying(10) COLLATE pg_catalog."default",
codenumber bigint,
isediting boolean,
CONSTRAINT crewcode_pkey PRIMARY KEY (crewcodeid))
插入一些数据

INSERT INTO public.crewcode(
crewcodeid, nationality, code, codenumber, isediting)
VALUES ('IN', '000001', 1, false);
下面有一个从ado.net运行的过程,得到了一些结果

当我运行此过程时,它将以desc方式获得单个记录。然后从中提取代码号并将其递增1,然后用递增的数字添加一行。您可以在下面的存储过程中看到代码

DECLARE
    LastCodeNumber integer;
    codeId integer;
    editCheck boolean;
    NewCodeNumber integer;
begin 

SELECT crewcodeid, codenumber, isediting FROM public.crewcode where nationality=NationalityInput order by codenumber desc limit 1
INTO codeId, LastCodeNumber, editCheck;

if (codeId is NULL) then
    INSERT INTO public.crewcode (nationality, code, codenumber, isediting) VALUES(NationalityInput, '000001', 1, false);
    crewCode = '000001';
else
    if not (editCheck) then
    
        UPDATE public.crewcode set isediting=true where crewcodeid=codeId;
        
    else
        return;
    END if;
        
    
    NewCodeNumber = LastCodeNumber + 1;
    crewCode = LPAD(NewCodeNumber::text, 6, '0');
    
    
    INSERT INTO public.crewcode (nationality, code, codenumber, isediting) VALUES(NationalityInput, crewCode, NewCodeNumber, false);


    UPDATE public.crewcode set isediting=false where crewcodeid=codeId;
END if;

end;

现在的问题是,当我调用存储过程并行时,我将创建如下的结果

我该怎么做才能保证没有像上面那样的复制品?我尝试过添加IsEditing列,并将其设置为true,读取时设置为false,但这不起作用,因为在并行代码中,所有内容都将同时执行,所以我的解决方案不起作用。还有别的办法吗


谢谢你的帮助

创建唯一约束以防止重复。如果不这样做,代码将是唯一的国籍。似乎您需要在
(国籍,代码,代码编号)
上创建唯一索引,我已在表上添加了唯一索引,它可以正常工作。谢谢你的解决方案。但在某些情况下,当我生成10个并行代码时,它会给我“重复键值违反唯一约束”ind_crewcode“错误。那么有什么办法吗?我的SP应该等到其他执行完成,这样它就不会生成上述错误。