将生成的列添加到现有表 Postgres

pet*_*rov 15 sql postgresql

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

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

;
Run Code Online (Sandbox Code Playgroud)

但我收到错误:

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
Run Code Online (Sandbox Code Playgroud)

有什么问题吗?我不明白。

在我的 Asset_Store 表的架构中,列
OR_ID 为int,Asset_ID 为varchar(100)

我猜它需要稍微不同的语法......但是正确的语法是什么?

jja*_*nes 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
;
Run Code Online (Sandbox Code Playgroud)
ALTER TABLE
Time: 17.678 ms
Run Code Online (Sandbox Code Playgroud)


小智 5

更通用、简化的命令

ALTER TABLE "items"
ADD COLUMN "revenue" numeric 
GENERATED ALWAYS AS ("price" * (1-"discount")) STORED;
Run Code Online (Sandbox Code Playgroud)