我有这张桌子
create table periodo (
codigo_p varchar(9)not null,
fecha_inicial date not null,
fecha_final date not null,
estatus char (10) not null constraint chk_estatus check (estatus in ('activo','inactivo')), primary key (codigo_p)
);
有一些数据
codigo_p | fecha_inicial | fecha_final | estatus
-----------+---------------+-------------+------------
2017-2018 | 2003-08-08 | 2003-08-07 | inactivo ---> bad
2018-2019 | 2018-09-15 | 2019-06-05 | activo ---> good
我遇到的问题是如何验证codigo_p,fecha_inicial和fecha_final数据的正确插入?
我正在使用postgresql,我需要我的bd安全,我希望还有其他解决方案,而不是在我的网页前端使用javacript和HTML代码进行验证。
这是我将使用的逻辑。您可以将其转换为代码。
首先,将codigo_p中的字符串转换为2个日期变量。 2017-2018
的值将具有2017-01-01
和2018-12-31
的变量。
然后是简单的日期比较。检查其他两个字段是否在这两个值之间。
您可以比较代码的每个组件:
select (case when not (codigo_p ~ '^[0-9]{4}-[0-9]{4}$' and
left(codigo_p, 4)::int = right(codgo_p, 4)::int - 1
)
then 'bad'
when left(codigo_p, 4)::int >= extract(year from fecha_inicial) and
left(codigo_p, 4)::int >= extract(year from fecha_final) and
right(codigo_p, 4)::int >= extract(year from fecha_inicial) and
right(codigo_p, 4)::int >= extract(year from fecha_final)
then 'good'
else 'bad'
end)
from . . .
我得到了解决方案
基本上解决方案是在约束我做了四(4)然后:
让我来看看这个项目的背景,我正在为一所非美国学校做数据库,他们管理每个学年“年”的时间,由于学校从九月开始到七月结束,所以,有2年的envolve,他们用这个代码管理学术“年”:2017-2018
所以我正在寻找一个wey来验证在codigo_p行中正确插入该代码,同样,我的fecha_inicial(代表起始日)和我的fecha_final(代表最后一天)两者都需要与codigo_p年。
这是解决方案:
3.这时,取下codigo_p的最后4个字符,并将其与fecha_final中提取的年份进行比较
4.这个检查连字符是否在codigo_p的位置
有SQL代码
create table periodo (
codigo_p char(9)not null,
fecha_inicial date not null,
fecha_final date not null,
estatus char (10) not null constraint chk_estatus check (estatus in ('activo','inactivo')),
constraint chk_fecha check (fecha_inicial < fecha_final),
constraint chk_codigo check ( (SUBSTRING (codigo_p,1,4)) = (cast ( (extract (year from fecha_inicial)) as varchar)) ),
constraint chk_codigo2 check ( (SUBSTRING (codigo_p,6,4)) = (cast ( (extract (year from fecha_final)) as varchar)) ),
constraint chk_codigo3 check ( (SUBSTRING (codigo_p,5,1)) = '-' ),
primary key (codigo_p)
);
我真的希望这对某个人有帮助,这是我在本页面的第一个问答,感谢所有人。
对不起,有一些语法错误,英语不是我的第一语言