2016-03-16 221 views
0

我想改變表中的一列從biginteger到varchar的數據類型。在Postgres的ALTER表查詢

myproject-# \d+ product_awbstock 
         Table "public.product_awbstock" 
     Column  |   Type   | Modifiers | Storage | Description 
-------------------+--------------------------+-----------+---------+------------- 
airwaybill_number | bigint     | not null | plain | 
used    | boolean     | not null | plain | 
created   | timestamp with time zone | not null | plain | 
modified   | timestamp with time zone | not null | plain | 
Indexes: 
    "product_awbstock_pkey" PRIMARY KEY, btree (airwaybill_number) 
    "product_awbstock_used" btree (used) 

我正在使用此查詢,錯誤也給出。

alter table product_awbstock ALTER COLUMN airwaybill_number TYPE varchar(15); 

ERROR: foreign key constraint "awbstock_id_refs_airwaybill_number_d438187b" cannot be implemented

DETAIL: Key columns "awbstock_id" and "airwaybill_number" are of incompatible types: bigint and character varying.

+0

該錯誤消息指出該列是從其他表稱爲。您不能在不同類型的列之間進行引用。 –

+1

您應該刪除product_awbstock.airwaybill_number和?.awbstock_id –

+2

之間的約束您還必須將該其他表的列更改爲varchar。但是,當前的bigint數據類型有什麼問題? – jarlh

回答

1

您應該:

  1. 上第一表

ALTER TABLE product_awbstock DROP CONSTRAINT product_awbstock_pkey;

  • 降外鍵約束下降主鍵約束在第二張桌子
  • ALTER TABLE ??? DROP CONSTRAINT awbstock_id_refs_airwaybill_number_d438187b;

  • 改變兩個表列數據類型
  • ALTER TABLE product_awbstock ALTER COLUMN airwaybill_number TYPE varchar(15);

    ALTER TABLE ??? ALTER COLUMN airwaybill_id TYPE varchar(15);

  • 重新創建先前刪除的約束條件
  • ALTER TABLE product_awbstock ADD CONSTRAINT product_awbstock_pkey PRIMARY KEY (airwaybill_number);

    ALTER TABLE ??? ADD CONSTRAINT awbstock_id_refs_airwaybill_number_d438187b FOREIGN KEY (awbstock_id) REFERENCES product_awbstock (airwaybill_number);