SQL 空数组作为 PostgreSQL 数组列默认值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30933266/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 03:45:37  来源:igfitidea点击:

Empty array as PostgreSQL array column default value

sqlpostgresql

提问by Hett

I have a defined an array field in postgresql 9.4 database:

我在 postgresql 9.4 数据库中定义了一个数组字段:

character varying(64)[]

Can I have an empty array e.g. {} for default value of that field? What will be the syntax for setting so?

我可以有一个空数组,例如 {} 作为该字段的默认值吗?设置的语法是什么?

I'm getting following error in case of setting just brackets {}:

如果只设置括号 {},我会收到以下错误:

SQL error:

ERROR:  syntax error at or near "{"
LINE 1: ...public"."accounts" ALTER COLUMN "pwd_history" SET DEFAULT {}
                                                                     ^

In statement:
ALTER TABLE "public"."accounts" ALTER COLUMN "pwd_history" SET DEFAULT {}

回答by a_horse_with_no_name

You need to use the explicit arrayinitializer and cast that to the correct type:

您需要使用显式array初始化程序并将其转换为正确的类型:

ALTER TABLE public.accounts 
    ALTER COLUMN pwd_history SET DEFAULT array[]::varchar[];

回答by GollyJer

I tested both the accepted answer and the one from the comments. They both work.
I'll graduate the comments to an answer as it's my preferred syntax.

我测试了接受的答案和评论中的答案。他们都工作。
我会将评论归结为答案,因为这是我的首选语法。

ALTER TABLE public.accounts 
    ALTER COLUMN pwd_history SET DEFAULT '{}';