使用用户定义的类型列插入到 DB2 中

INSERT into DB2 with a user defined type column

您好,我正在尝试使用用户定义的类型探索 DB2 我已经创建了一个类型和一个 table,但我现在无法将数据插入 table。我在数据库中的用户定义类型如下:

CREATE TYPE pizza AS
(type varchar(50),
size INTEGER,
topping varchar(50))
MODE DB2SQL@

然后我创建了一个table如下:

CREATE TABLE orders
(id  INT NOT NULL PRIMARY KEY,
customer VARCHAR(50),
pizza_row pizza)@

然后当我尝试插入时出现错误,这是我的插入语句:

INSERT into orders (id,customer,pizza_row) 
VALUES (1,'Larry', pizza('margarita',10,'kebab'))@

收到错误:

No authorized routine named "PIZZA" of type "FUNCTION" having compatible arguments was found.. SQLCODE=-440

插入到我的架构中的正确语法是什么?

DB2 在创建结构化类型时自动生成的默认构造函数没有参数:pizza()。如果你想用一些值实例化你的类型,你需要创建你自己的构造函数来调用默认构造函数,然后为类型的字段分配适当的值,如下所示:

create or replace function pizza (
 p_type varchar(50),
 p_size INTEGER,
 p_topping varchar(50)
)
returns pizza
begin atomic
  declare t pizza;
  set t = pizza();
  set t..type = p_type;
  set t..size = p_size;
  set t..topping = p_topping;
  return t;
end

PS。代码未经测试。

在 IBM DB2 中,您可以使用 MUTATORS 和 OBSERVERS 来插入和检索值。

当您创建结构化类型时,DB2 会自动为该类型生成一个构造函数方法,并为该类型的属性生成 mutator 和 observer 方法。您可以使用这些方法创建结构化类型的实例并将这些实例插入到 table.

的列中

参考:https://www.ibm.com/support/knowledgecenter/SSEPGG_9.7.0/com.ibm.db2.luw.admin.structypes.doc/doc/t0006627.html

插入

INSERT INTO 订单 VALUES (1, 'Larry', pizza()..type('margarita')..size(10)..topping('mushrooms'))@

SELECT

SELECT id, customer, pizza..type AS type, pizza..size AS size, pizza..topping AS topping FROM orders@