現在我正在編寫一個具有PostgreSQL數據庫的應用程序。 我的任務是編寫根據new.id
執行SQL語句的觸發器。基於NEW.id的動態SUM基於觸發函數
只有一個問題,即觸發器不執行查詢。它只是插入任何東西。
CREATE OR REPLACE FUNCTION bill_creator()
RETURNS TRIGGER AS $build_bill$
declare
summ INTEGER;
BEGIN
SELECT SUM(ITEMS.PRICE) INTO summ
FROM ITEMS
INNER JOIN PARTS
ON PARTS.ITEM_ID = ITEMS.ID AND PARTS.ORDER_ID = NEW.ID;
INSERT INTO BILLS (
created,
summary,
cashier_id,
customer_id,
order_id,
created_at,
updated_at,
options
)
VALUES (
current_date,
summ,
1,
new.customer_id,
new_id,
current_timestamp,
current_timestamp,
'None'
);
RETURN NEW;
END;
$build_bill$ LANGUAGE plpgsql;
CREATE OR REPLACE TRIGGER build_bill AFTER INSERT ON ORDERS
FOR EACH ROW EXECUTE PROCEDURE bill_creator();
我使用Rails,所以表格由ActiveRecords創建的,但它們存儲在架構。
create_table "bills", force: :cascade do |t|
t.datetime "created"
t.string "options"
t.integer "summary"
t.integer "cashier_id"
t.integer "customer_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "order_id"
end
create_table "orders", force: :cascade do |t|
t.integer "customer_id"
t.integer "waiter_id"
t.integer "manager_id"
t.integer "chef_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "parts", force: :cascade do |t|
t.integer "order_id"
t.integer "item_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "items", force: :cascade do |t|
t.integer "price"
t.string "description"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "menu_id"
end
add_index "parts", ["item_id"], name: "index_parts_on_item_id", using: :btree
add_index "parts", ["order_id"], name: "index_parts_on_order_id", using: :btree
嘗試設置數據庫作用域 – MHSFisher
請爲所涉及的所有表顯示「create trigger」語句和「create table」。 –
請用文本格式替換您的實際「數據庫輸出」鏈接。外部鏈接對此沒有好處。 –