在 Postgres 中添加一个具有默认值的列作为常量
Add a column with default value as a constant in Postgres
我想更改现有的 table 以添加一个列,该列将大字符串定义为 Postgres 数据库中的默认值。
我试过以下方法:
DO $$
declare PARAGRAPH character varying(4000):= 'Large text in here, around 4000 characters';
begin
ALTER TABLE USERS
ADD COLUMN NOTES_TEXT character varying(4000) DEFAULT PARAGRAPH NOT NULL;
END $$;
我发现的另一种方法如下:
DO $$
declare PARAGRAPH character varying(4000);
begin
select 'Very large text goes in here.' into PARAGRAPH;
ALTER TABLE USERS
ADD COLUMN NOTES_TEXT character varying(4000) DEFAULT PARAGRAPH NOT NULL;
END $$;
但是,我在两次尝试中都遇到了与无法识别的变量相关的错误。
你知道这在 Postgres 中是否可行吗?
非常感谢
问题是这样的:
DO $$
declare PARAGRAPH character varying(4000);
begin
PARAGRAPH := 'Very large text goes in here.';
ALTER TABLE USERS
ADD COLUMN NOTES_TEXT character varying(4000) DEFAULT PARAGRAPH NOT NULL;
END $$;
ERROR: cannot use column reference in DEFAULT expression
CONTEXT: SQL statement "ALTER TABLE USERS
ADD COLUMN NOTES_TEXT character varying(4000) DEFAULT PARAGRAPH NOT NULL"
PL/pgSQL function inline_code_block line 6 at SQL statement
这里的解决方案Dynamic SQL:
DO $$
declare PARAGRAPH character varying(4000);
begin
PARAGRAPH := 'Very large text goes in here.';
EXECUTE 'ALTER TABLE USERS ' ||
'ADD COLUMN NOTES_TEXT character varying(4000) DEFAULT' ||quote_literal(PARAGRAPH) || 'NOT NULL';
END $$;
\d users
...
notes_text | character varying(4000) | | not null | 'Very large text goes in here.'::character varying
我想更改现有的 table 以添加一个列,该列将大字符串定义为 Postgres 数据库中的默认值。
我试过以下方法:
DO $$
declare PARAGRAPH character varying(4000):= 'Large text in here, around 4000 characters';
begin
ALTER TABLE USERS
ADD COLUMN NOTES_TEXT character varying(4000) DEFAULT PARAGRAPH NOT NULL;
END $$;
我发现的另一种方法如下:
DO $$
declare PARAGRAPH character varying(4000);
begin
select 'Very large text goes in here.' into PARAGRAPH;
ALTER TABLE USERS
ADD COLUMN NOTES_TEXT character varying(4000) DEFAULT PARAGRAPH NOT NULL;
END $$;
但是,我在两次尝试中都遇到了与无法识别的变量相关的错误。
你知道这在 Postgres 中是否可行吗?
非常感谢
问题是这样的:
DO $$
declare PARAGRAPH character varying(4000);
begin
PARAGRAPH := 'Very large text goes in here.';
ALTER TABLE USERS
ADD COLUMN NOTES_TEXT character varying(4000) DEFAULT PARAGRAPH NOT NULL;
END $$;
ERROR: cannot use column reference in DEFAULT expression
CONTEXT: SQL statement "ALTER TABLE USERS
ADD COLUMN NOTES_TEXT character varying(4000) DEFAULT PARAGRAPH NOT NULL"
PL/pgSQL function inline_code_block line 6 at SQL statement
这里的解决方案Dynamic SQL:
DO $$
declare PARAGRAPH character varying(4000);
begin
PARAGRAPH := 'Very large text goes in here.';
EXECUTE 'ALTER TABLE USERS ' ||
'ADD COLUMN NOTES_TEXT character varying(4000) DEFAULT' ||quote_literal(PARAGRAPH) || 'NOT NULL';
END $$;
\d users
...
notes_text | character varying(4000) | | not null | 'Very large text goes in here.'::character varying