简体   繁体   中英

Update table using query result

I am attempting to add the result of my query into the column of an existing table. Thus far, the query below calculates the CAR_PRICE and displays the value. However, I want to add this value to the CAR_PAYMENT_TBL in the car_price column.

The create table commands below show the relevant table and the relationships between them. Is it possible to update the CAR_PRICE value in the CAR_PAYMENT_TBL ?

SELECT C.TICKET_NO, 
            C.REG_ID,
            C.BOOKING_ID,
            (R.END_DATE-R.START_DATE) AS DAYS_STAYED,
            (R.END_DATE-R.START_DATE)*5 AS CAR_PRICE
            FROM CAR_TBL C
            LEFT JOIN
            ROOM_TBL R
            ON C.BOOKING_ID = R.BOOKING_ID;

TABLE SCHEMA:

CREATE TABLE CAR_PAYMENT_TBL
(
    TICKET_NO INT NOT NULL PRIMARY KEY,
    CAR_PRICE NUMERIC(5,2) 
);

CREATE TABLE CAR_TBL
(
    REG_ID VARCHAR2(7) NOT NULL PRIMARY KEY,
    TICKET_NO INT NOT NULL references CAR_PAYMENT_TBL(TICKET_NO),
    BOOKING_ID INT NOT NULL references BOOKING_TBL(BOOKING_ID)
);

CREATE TABLE ROOM_TBL
(  
    STAY_NO INT NOT NULL PRIMARY KEY,
    ROOM_NO VARCHAR2(4) NOT NULL references ROOM_DETAILS_TBL(ROOM_NO),
    START_DATE DATE NOT NULL,
    END_DATE DATE NOT NULL,
    BOOKING_ID INT NOT NULL references BOOKING_TBL(BOOKING_ID)
);

You cannot reference other tables in an UPDATE statement in Oracle - use a subquery or a MERGE statement:

  UPDATE CAR_PAYMENT_TBL
  SET CAR_PRICE =
  (select (ROOM_TBL.END_DATE - ROOM_TBL.START_DATE)*5 from room_tbl where ... )
  WHERE CAR_PAYMENT_TBL.TICKET_NO = &TICKET_NO;    

You'll also have to provide a sensible WHERE clause for the subquery (assuing &TICKET_NO is really a bind variable and not your join condition for the two tables).

If you want to update all the records of CAR_PAYMENT_TBL based on the values of ROOM_TBL then

UPDATE CAR_PAYMENT_TBL
SET CAR_PRICE = (select (ROOM_TBL.END_DATE – ROOM_TBL.START_DATE)*5
FROM ROOM_TBL WHERE CAR_PAYMENT_TBL.TICKET_NO = ROOM_TBL.TICKET_NO)

If you want to update only specific record of CAR_PAYMENT_TBL then

UPDATE CAR_PAYMENT_TBL
SET CAR_PRICE = (select (ROOM_TBL.END_DATE – ROOM_TBL.START_DATE)*5
FROM ROOM_TBL WHERE CAR_PAYMENT_TBL.TICKET_NO = ROOM_TBL.TICKET_NO)
where CAR_PAYMENT_TBL = &ticket_num;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM