Updating Trigger Table Values Oracle SQL - sql

I am not able to update a table after the following trigger added. Here is what I have so far:
CREATE TABLE ITEM(
item_id DECIMAL(10) NOT NULL,
description VARCHAR(30),
price DECIMAL(10),
PRIMARY KEY (item_id));
CREATE TABLE Item_price_history (
history_id DECIMAL(10) NOT NULL,
item_id DECIMAL(10) NOT NULL,
line_price DECIMAL(10,2),
new_line_price DECIMAL(10,2),
modified DATE,
PRIMARY KEY (HISTORY_ID),
FOREIGN KEY (ITEM_ID) REFERENCES item);
CREATE OR REPLACE TRIGGER Item_price_history
AFTER UPDATE OR INSERT ON ITEM
FOR EACH ROW
BEGIN
INSERT INTO item_price_history(item_id, line_price,
new_line_price,modified)
select item_id,:OLD.price,:New.price, SYSTIMESTAMP from item;
END;
Now if I use the following Update commands, I get this error:
UPDATE item_price_history
SET line_price = 4
WHERE ITEM_ID=ITEM.ITEM_ID and ITEM.DESCRIPTION='Spoon';
*Error report -
SQL Error: ORA-00904: "ITEM"."DESCRIPTION": invalid identifier
00904. 00000 - "%s: invalid identifier"
*Cause:
Action:
Any help or suggestions or advice?

Could you please try this:
UPDATE item_price_history
SET line_price = 4
WHERE item_id IN (SELECT item_id
FROM ITEM
WHERE description = 'Spoon');

You can try the below Merge as well. This will not update anything as there are no records in item table with Spoon Description and item_id.
Not sure what you wanted to achieve. I see you created a trigger. The trigger fires only when there is an insert/update on item not on item_price_history.
merge INTO item_price_history tgt USING
(SELECT item_id, description FROM item
) src ON (tgt.item_id = src.item_id AND src.description = 'Spoon')
WHEN matched THEN
UPDATE SET line_price = 4;
--Updates zero records

Try this...
update ITEM_PRICE_HISTORY SET line_price = 4
WHERE item_id IN (SELECT i.item_id FROM ITEM WHERE i.description = 'Spoon');

Related

Postgresql INSERT ON CONFLICT syntax

Greetings with the following test table:
CREATE TEMP SEQUENCE pid start 10000;
SELECT nextval ('pid');
CREATE TEMP TABLE project_test (
id int DEFAULT nextval('pid') primary key,
project_id int UNIQUE NOT NULL
);
I am attempting to make a statement that either inserts a new value for project_id returning the id or returns the id if the project_id exists.
I have attempted the following:
INSERT INTO project_test(project_id) VALUES(50) RETURNING id
ON CONFLICT (project_id) DO UPDATE project_test SET project_id = 50 WHERE project_id = 50 RETURNING id;
I have read the documentation here:
https://www.postgresql.org/docs/13/sql-insert.html
I am on Postgres 13
I am getting a syntax error
ERROR: syntax error at or near "ON"
Thanks in advance for any tips
INSERT INTO project_test(project_id) VALUES(50)
ON CONFLICT (project_id) DO UPDATE SET project_id = 50 WHERE project_test.project_id = 50 RETURNING id;
The problem was the RETURNING id needs to go at the end, and then it thought column reference "project_id" was ambiguous, which is odd.
Thanks all

PL/SQL: NO DATA FOUND while updating another table based on conditions

So I have a column on my PAYMENT table that is called Status.. It has a foreign key of another table called reservation with Reservation_ID. The Reservation Table also has a status column and it will only get updated when there is a value in the status column of payment table. So If my status field in payment table has the value "Confirmed", the value for that particular Reservation_ID is supposed to turn to 1.. Otherwise 22. This is how I made the trigger:
CREATE OR REPLACE TRIGGER stats BEFORE INSERT OR DELETE OR UPDATE ON PAYMENT FOR EACH ROW
DECLARE
V_STATUS VARCHAR2(20);
BEGIN
SELECT Status INTO V_STATUS FROM PAYMENT INNER JOIN RESERVATION ON PAYMENT.Reservation_ID=RESERVATION.Reservation_ID WHERE PAYMENT.Reservation_ID=:NEW.Reservation_ID;
IF INSERTING AND V_STATUS='CONFIRMED' THEN
UPDATE RESERVATION SET status=1 WHERE Reservation_ID=:new.Reservation_ID;
ELSIF UPDATING AND V_STATUS='CONFIRMED' THEN
UPDATE RESERVATION SET status=1 WHERE Reservation_ID=:new.Reservation_ID;
ELSE
UPDATE RESERVATION SET status=22 WHERE Reservation_ID=:new.Reservation_ID;
END IF;
END;
So the trigger basically gets compiled but when I try inserting values inside Payment Table, I get the following error:
Error report -
ORA-01403: no data found
ORA-06512: at "ME.STATS", line 4
ORA-04088: error during execution of trigger 'ME.STATS'
create statments for both tables:
CREATE TABLE RESERVATION(RESERVATION_id NUMBER(10) NOT NULL, MEMBER_ID NUMBER(10) CONSTRAINT RE_MEM_fk REFERENCES MEMBER(MEMBER_ID) ON DELETE SET NULL,status NUMBER(10) CONSTRAINT RES_status_fk REFERENCES STATUS(RESERVATION_status_id) ON DELETE SET NULL, CONSTRAINT PK_BOOK PRIMARY KEY(RESERVATION_id));
CREATE TABLE PAYMENT(Payment_ID NUMBER(10) NOT NULL ,RESERVATION_id NUMBER(10) CONSTRAINT Pay_RES_fk REFERENCES RESERVATION(RESERVATION_id) ON DELETE SET NULL, TicketPrice NUMBER(10), ExtraFaciliFees Number(10),TOTAL_AMOUNT Number(10), PromotionalCode VARCHAR2(10), CONSTRAINT PK_PAY PRIMARY KEY(Payment_ID));
First :
CREATE TABLE RESERVATION(
Status NUMBER(10));
SELECT Status INTO V_STATUS
IF INSERTING AND V_STATUS='CONFIRMED'
Could you explain me how you expect a NUMBER to match a string ?
Next (from http://www.dba-oracle.com/sf_ora_01403_no_data_found.htm )
SELECT INTO clauses are standard SQL queries which pull a row or set
of columns from a database, and put the retrieved data into variables
which have been predefined.
If the SELECT INTO statement doesn't return at least on e row,
ORA-01403 is thrown.
So this :
SELECT
Status INTO V_STATUS
FROM PAYMENT p
INNER JOIN RESERVATION r
ON p.Reservation_ID = r.Reservation_ID
WHERE p.Reservation_ID = :NEW.Reservation_ID;
Is likely to output no row at all...
Agree with #Blag, below statement is giving the no data found exception.
In general if you want to know the exact line number the error is pointing to you can refer to the object via DBA_SOURCE or ALL_SOURCES.
SELECT
Status INTO V_STATUS
FROM PAYMENT p
INNER JOIN RESERVATION r
ON p.Reservation_ID = r.Reservation_ID
WHERE p.Reservation_ID = :NEW.Reservation_ID;

DB2SQL Trying to create a trigger with function (Calculate days)

So for now, I created 2 tables, Booking and BookingDetails, I want to create a trigger when I key in the details of BookingDetails it will automatically update totaldays inside the Booking table. Below is my code:
BookingDetails:
create table BookingDetail (
BD_ID int primary key not null,
Date_In date,
Date_Out date,
BK_ID int,
Room_ID int,
foreign key(BK_ID) references Booking(BK_ID),
foreign key(Room_ID) references Room(Room_ID)
)
And also Booking
create table Booking (
BK_ID int primary key not null,
BK_Date Date,
BK_TotalDays int,
BK_PayStatus char(6),
Cus_ID int,
Emp_ID int,
foreign key(Cus_ID) references customer(Cus_ID),
foreign key(Emp_ID) references Employee(Emp_ID)
)
With the function and trigger created:
create function countdays(t1 date, t2 date)
returns INT
return (timestampdiff(16, char(timestamp(t2) - timestamp(t1))))
create trigger totaldays
after insert on bookingdetail
referencing new as n
for each row mode db2sql
update booking
set bk_totaldays =
countdays((select date_in from bookingdetail), (select date_out from
bookingdetail))
where booking.bk_id = n.bk_id;
I have no problem executing these syntax, but when I try to input a new record inside Booking Detail to let the trigger triggers in Booking, errors occured, may I ask why? Thanks in advance.
Look at the information provided by the SQL error:
db2 ? SQL0811
SQL0811N The result of a scalar fullselect, SELECT INTO statement, or
VALUES INTO statement is more than one row.
So this part of your trigger expressions returns more than 1 row
set bk_totaldays = countdays((select date_in from bookingdetail),
(select date_out from bookingdetail))
Fix this to return a single row.
#MichaleTiefenbacher is correct about the cause of the error, but he's wrong about what to do about it. Let's take another look at your trigger again:
create trigger totaldays
after insert on bookingdetail
referencing new as n -- wait, what's this?
for each row mode db2sql
update booking
set bk_totaldays =
countdays((select date_in from bookingdetail), (select date_out from bookingdetail))
where booking.bk_id = n.bk_id;
You have a reference to the value you just inserted! When using FOR EACH ROW, the table reference NEW refers to the singular row just inserted. So you don't even need to look at the full table, just use what you just worked with:
create trigger totaldays
after insert on bookingdetail
referencing new as n
for each row mode db2sql
update booking
set bk_totaldays = countdays(n.date_in, n.date_out)
where booking.bk_id = n.bk_id;
(As I mentioned in my comment to your question, you'll likely want to change how you calculate the days, but that's irrelevant for this)

PL SQL UPDATE STATEMENT

create table item_stock
( itemcode varchar2(11) not null,
name varchar(27) not null,
des varchar2(30),
pcs number(11),
unit varchar(7),
qty number(11),
stkdate date,
constraint itemcodef_pk primary key(itemcode, name)
);
BEGIN
update table item_stock
set 'item_stock.itemcode' = 'item_stock.itemcode';
END;
Error 103 at line 2, column 14
Encountered the sysmbol "ITEM_STOCK" when expecting one of the following.
Can anybody help me to resolve this error.
This one:
Update item_stock A
Set A.itemcode = item_stock.itemcode;
Note:
The data type of the item_stock.itemcode must be same as A.itemcode.

Why do I keep getting this error message when I try to insert something into a table

Here is the question that I have to answer:
Create a trigger named Products_INSERT that inserts the current date for the DateAdded column of the Products table if the value for that column is null.
Test this trigger with an appropriate INSERT statement.
Here is the code that I have:
CREATE TRIGGER Products_INSERT
ON Products
AFTER INSERT
AS
UPDATE Products
SET DateAdded = GETDATE()
WHERE DateAdded IS NULL OR
DateAdded IN (SELECT DateAdded FROM inserted);
Here is my insert statement:
INSERT INTO Products
VALUES (4, 'LK-5300', 'Likeable Keyboard 5300',
'This keyboard is so cool, you just might flip!',
699.99, 30.00, NULL)
And here is the error I keep getting:
Msg 547, Level 16, State 0, Line 1
The INSERT statement conflicted with the FOREIGN KEY constraint "FK__Products__Catego__145C0A3F". The conflict occurred in database "MyGuitarShop", table "dbo.Categories", column 'CategoryID'.
The statement has been terminated.
I know that the error has something to do with the foreign key but I'm not entirely sure. Any help would be appreciated.
EDIT:
CREATE TABLE Products (
ProductID INT PRIMARY KEY IDENTITY,
CategoryID INT REFERENCES Categories (CategoryID),
ProductCode VARCHAR(10) NOT NULL UNIQUE,
ProductName VARCHAR(255) NOT NULL,
Description TEXT NOT NULL,
ListPrice MONEY NOT NULL,
DiscountPercent MONEY NOT NULL DEFAULT 0.00,
DateAdded DATETIME DEFAULT NULL
);
Here is the Products table
You don't need to include the productID because its auto generated
Thank's #Turophile here a what I ended up doing to my INSERT statement after I read your post:
INSERT INTO Products (CategoryID, ProductCode, ProductName, Description, ListPrice,DiscountPercent, DateAdded)
VALUES (44444, 'LK-5300', 'Likeable Keyboard 5300',
'This keyboard is so cool, you just might flip!',
699.99, 30.00, NULL)
Your INSERT should be:
INSERT INTO Products
( CategoryID,
ProductCode,
ProductName,
Description,
ListPrice,
DiscountPercent,
DateAdded
)
VALUES (4, 'LK-5300', 'Likeable Keyboard 5300',
'This keyboard is so cool, you just might flip!',
699.99, 30.00, NULL)
Your INSERT was missing a value to go into the ProductID column, since it is auto-generated because it is defined as IDENTITY but to get that to work, you need to name the columns, leaving out ProductID.