2014-05-20 19 views
1

我使用的数据类型包含字符(6)字段。我想将其更改为varchar(7)字段。不幸的是,我在使用PostgreSQL 8.3.8的服务器上,而当时ALTER TYPE没有太多的功能。这个列也被多个函数使用,所以它不会让我删除该属性,并用正确的参数放入一个新的属性。PostgreSQL中的改变类型8.3.8

这里就是我的意思是:

mydb=# \d t_emp_start_stop_2 
Composite type "public.t_emp_start_stop_2" 
    Column |  Type 
--------------+-------------- 
employee_id | character(6) 
normal_start | integer 
normal_stop | integer 
normal_lunch | integer 

我想用一个varchar(7)现场更换EMPLOYEE_ID。有没有办法做到这一点干净?

+0

8.3x是生命的尽头...所以考虑更新(独立于您的问题...) – frlan

回答

0

如果您可以接受更改类型名称,并且可以更改所有相关功能的类型,那么您可能会转移到新类型。

-- create a new type 
CREATE TYPE public.t_emp_start_stop_2_new AS (
    employee_id VARCHAR(7), 
    normal_start INTEGER, 
    normal_stop INTEGER, 
    normal_lunch INTEGER 
); 

-- create a function that takes the old type and outputs the new type 
CREATE OR REPLACE FUNCTION t_emp_start_stop_2_new_converter(value1 t_emp_start_stop_2) 
RETURNS t_emp_start_stop_2_new AS $$ 
DECLARE 
    newtype t_emp_start_stop_2_new; 
BEGIN 
    newtype.employee_id = value1.employee_id; 
    newtype.normal_start = value1.normal_start; 
    newtype.normal_stop = value1.normal_stop; 
    newtype.normal_lunch = value1.normal_lunch; 
    return newtype; 
END; 
$$ LANGUAGE plpgsql IMMUTABLE STRICT; 

-- create a cast from the old to new type 
CREATE CAST (t_emp_start_stop_2 AS t_emp_start_stop_2_new) 
WITH FUNCTION t_emp_start_stop_2_new_converter(t_emp_start_stop_2); 

-- update table to use new type 
ALTER TABLE abc 
ALTER xyz TYPE t_emp_start_stop_2_new 
USING xyz::t_emp_start_stop_2_new; 

-- UPDATE ALL EXISTING FUNCTIONS TO USE NEW TYPE HERE 

-- drop old cast, function and type 
DROP CAST (t_emp_start_stop_2 AS t_emp_start_stop_2_new); 
DROP FUNCTION t_emp_start_stop_2_new_converter(t_emp_start_stop_2); 
DROP TYPE t_emp_start_stop_2;