trigger bag in sqlite3

0

Hi,
could you help me to find a mistake?
I have 2 tables

CREATE TABLE "Customers"
(
    "id" integer,
    "name" text not null,
    "surname" text not null,
    "email" text not null unique,
    "orders" text,
    primary key ("id")
);

and

CREATE TABLE "Orders"
(
    "id" integer,
    "order_date" numeric not null default current_timestamp,
    "customer_id" numeric not null,
    "delivery_adress" text not null,
    primary key ("id"),
    foreign key ("customer_id") references "Customers"("id")
);

I wrote a trigger

CREATE TRIGGER "purchase"
AFTER INSERT ON "Orders"
WHEN "customer_id" in (select "id" from "customers")
BEGIN
    UPDATE Customers
    SET orders = orders || ',' || new."id"
    WHERE id = new."customer_id";
END;

it should automatically add the Id of new orders into customer table ( orders column) but it doesn`t work.
Any ideas why?

2

I believe the issue lies in the following line:

SET orders = orders || ',' || new."id"

Customers without any orders probably have their orders column set to NULL value. Therefore, concatenatingNULL with non-null values results in NULL, although SQLite3 is not my primary database engine.

You can give a try:

SET orders = IFNULL(orders,'') || ',' || new."id"

or

SET orders = COALESCE(orders,'') || ',' || new."id"

Furthermore, this is relational db, and you should avoid keeping multiple values within same attribute.

1 użytkowników online, w tym zalogowanych: 0, gości: 1