列类型不一致:字符变化和字符变化(30)

时间:2019-02-01 15:35:41

标签: postgresql postgresql-8.4

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

visibility:hidden

如果执行该命令并执行SELECT以显示ack_event内容,我们将看到已添加列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)');

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

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

结果:

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

     CONSTRAINT PK_ACK_EVENT PRIMARY KEY (ID)
);

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

1 个答案:

答案 0 :(得分:1)

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

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