向现有的Postgres表中添加生成的列

14

我正在尝试使用此脚本将生成列添加到现有表:

alter table Asset_Store add column

md5_hash VARCHAR(100) GENERATED ALWAYS AS 

(CAST(UPPER(    
        case
             when OR_ID is not null then MD5(cast(OR_ID as varchar(100)))
             when Asset_ID is not null then MD5(Asset_ID)
             else null
        end 
) as VARCHAR(100)))

STORED

;

但是我遇到了一个错误:

SQL Error [42601]: ERROR: syntax error at or near "("
 Position: 88
 ERROR: syntax error at or near "("
 Position: 88
 ERROR: syntax error at or near "("
 Position: 88

问题是什么?我不明白。
在我的 Asset_Store 表模式中,OR_ID 列是 int 类型,Asset_ID 列是 varchar(100) 类型。
我猜它期望的语法略有不同……但正确的语法是什么?

2
PostgreSQL的版本是什么?它是在12版中引入的。 - Abelisto
1
select version(); 会给你什么结果? - user330315
谢谢。是的,我后来意识到我在使用 PG 11。 - peter.petrov
我应该继续删除这个问题吗? - peter.petrov
2个回答

17

您的语法是正确的。但您使用的PostgreSQL版本可能不支持。

在12版本中:

create table asset_store(or_id text, asset_id text);

alter table Asset_Store add column
md5_hash VARCHAR(100) GENERATED ALWAYS AS 
(CAST(UPPER(    
        case
             when OR_ID is not null then MD5(cast(OR_ID as varchar(100)))
             when Asset_ID is not null then MD5(Asset_ID)
             else null
        end 
) as VARCHAR(100)))
STORED
;
ALTER TABLE
Time: 17.678 ms

谢谢。是的,我后来意识到我在使用 PG 11。 - peter.petrov
对于将来的复制粘贴者来说,在我的不同SQL中,CAST (... as VARCHAR(100)) 表达式都是不必要的。 - undefined

4
更通用、简化的命令
ALTER TABLE "items"
ADD COLUMN "revenue" numeric 
GENERATED ALWAYS AS ("price" * (1-"discount")) STORED;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接