gpt4 book ai didi

sql - 如何在 Postgresql 中创建条件插入函数?

转载 作者:行者123 更新时间:2023-12-01 21:33:59 26 4
gpt4 key购买 nike

我尝试编写一个函数,根据此表中的值在我的表中的 column3 中插入一些值,但我不太熟悉在 Postgresql 9.6 中编写函数。

--Create some table

CREATE TABLE test(column1 INT, column2 INT, column3 TEXT)
INSERT INTO test VALUES(-8020,15),(-200,1),(23,115)

--Build function

CREATE OR REPLACE FUNCTION new_function()
RETURNS TEXT AS
$$
BEGIN

IF test(column1) <= -7000 THEN INSERT INTO test(column3) VALUES('small');
ELSIF test(column1) >= -7000 AND test(column2) <= 15 THEN INSERT INTO test(column3) VALUES('nohello');
ELSIF test(column1) >= -7000 ANDtable(column2) >= 15 THEN INSERT INTO test(column3) VALUES('test');
ELSE INSERT INTO test(column6) VALUES("nodata");
END IF;

END;
$$
LANGUAGE plpgsql;

结果应该是一个如下所示的表格:

Column1 | Column2 | Column3
---------------------------
-8020 | 15 | small
-200 | 1 | nohello
23 | 115 | test

调用 new_function 时出现错误 column1 doesn't exist.

最佳答案

您似乎实际上是在寻找更新(更改现有行的值)而不是插入(创建新行)。

但最重要的是,我建议只使用计算列:

create table test(
column1 int,
column2 int,
column3 text generated always as (
case
when column1 <= -7000 then 'small'
when column1 <= 15 then 'nohello'
else 'nodata'
end
) stored
);

当在表中插入或更新行时,数据库会相应地自动调整计算列,因此它始终是最新的。

Demo on DB Fiddle :

insert into test(column1, column2) values(-8020,15),(-200,1),(23,115);

select * from test;
column1 | column2 | column3------: | ------: | :------  -8020 |      15 | small     -200 |       1 | nohello     23 |     115 | nodata 

Note that generated columns are available starting Postgres 12 only. In earlier versions, one alternative is have just the first two columns in the table, and to create a view to expose the third column:

create view myview as 
select
column1,
column2,
case
when column1 <= -7000 then 'small'
when column1 <= 15 then 'nohello'
else 'nodata'
end as column3
from mytable

然后您可以查询 View 而不是表来显示您的数据。

关于sql - 如何在 Postgresql 中创建条件插入函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62219872/

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