将自定义类型的数组插入postgresql中的表中

时间:2015-12-01 11:18:55

标签: sql arrays postgresql types

我正在使用PostgreSQL学习SQL,但现在我遇到了一个无法解决的问题。我有一种我称之为电话的类型:

CREATE TYPE Phone as 
(
  DDD varchar(3),
  Number Varchar(10),
  TypeOf Varchar(15)
)

我必须在表格中创建一个电话阵列学生:

CREATE TABLE Students
(
   Id INT NOT NULL,
   PRIMARY KEY (Id),
   name Varchar(50),
   status Char,
   codCourse int,
    FOREIGN KEY (codCourse )  REFERENCES Course (IdCourse) ON DELETE CASCADE,
   phones Phone[] 
)

我创造了。 但是,当我尝试像学生一样插入学生表时:

INSERT INTO Students (Id, name, status, codCourse , phones) 
VALUES (
    00001, 'Joaquim Soares Fernando', 'I', 4,       
    Array[('22','33548795','Telefone')])

我收到了错误消息

ERROR: column "phones" is of type phone[] but expression is of type record[]
SQL state: 42804
Hint: You will need to rewrite or cast the expression.
Character: 118"

我该如何插入?

1 个答案:

答案 0 :(得分:0)

您必须显式地将数组转换为phone[]类型:

INSERT INTO students (id, name, status, codcourse , phones) 
VALUES (
    00001, 'Joaquim Soares Fernando', 'I', 4, 
    array[('22','33548795','Telefone')]::phone[]);