gpt4 book ai didi

postgresql - 列类型不一致 : character varying and character varying(30)

转载 作者:行者123 更新时间:2023-11-29 13:11:11 25 4
gpt4 key购买 nike

对于我的应用程序,我创建了一个 SQL 文件补丁以将列 user_name 添加到现有表中:

CREATE OR REPLACE FUNCTION add_col(
_tbl VARCHAR, -- Table
_col VARCHAR, -- Column to add
_type regtype -- Type of that column
) RETURNS BOOL AS $$
BEGIN
-- Returns true if column has been added; false otherwise.
IF EXISTS (SELECT DISTINCT column_name
FROM information_schema.columns
WHERE table_schema LIKE current_schema and table_name LIKE _tbl and column_name LIKE _col
)
THEN
-- Column already exists in that table of that schema: do nothing.
RETURN false;
END IF;

-- Add column
EXECUTE 'ALTER TABLE ' || _tbl || ' ADD COLUMN ' || _col || ' ' || _type;

RETURN true;
END; $$ language 'plpgsql';

SELECT add_col('ack_event', 'user_name', 'VARCHAR(30)');

如果我执行它并执行 SELECT 以显示 ack_event 内容,我们会看到添加了列 user_name 但具有“character varying”类型:

| id     | user_name         |
| bigint | character varying |
|--------+-------------------+
| | |

但是,如果 ack_event 列是直接使用 user_name 列创建的,则 user_name 的类型是“character_varying(30)”:

CREATE TABLE ACK_EVENT(
ID int8 not null,
USER_NAME VARCHAR(30),

CONSTRAINT PK_ACK_EVENT PRIMARY KEY (ID)
);

结果:

| id     | user_name             |
| bigint | character varying(30) |
|--------+-----------------------+
| | |

为什么会出现这种不一致?有没有办法纠正它并在两种情况下都改变字符 (30)?

最佳答案

这可能会引入一些验证问题,但如果您将 _type 的数据类型从 regtype 更改为文本数据类型,我认为它会更直接地输入您的 DDL:

CREATE OR REPLACE FUNCTION add_col(
_tbl VARCHAR,
_col VARCHAR,
_type text -- this was previously regtype
) RETURNS varchar AS $$

关于postgresql - 列类型不一致 : character varying and character varying(30),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54482583/

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