0

i have code for MySQL but i need to PostgreSQL. Can you help me convert from MySQL to PostgreSQL?

Create TRIGGER date_reservation
BEFORE INSERT ON reservation
FOR EACH ROW 
BEGIN 
IF 
NEW.date_reservation IS NULL OR NEW.date_reservation = ''
THEN 
SET NEW.date_reservation = NOW();
END IF 
END 

3
  • 1
    Title needs rewriting to summarize your specific technical issue. Commented Jan 21, 2020 at 3:57
  • Welcome to SO. You're asking us to convert code for you, but you haven't showed any effort toward solving the problem. SO isn't a code-conversion site, instead, we expect you to research and try, many, many times, and when you can't figure out the solution for days THEN ask. "Writing The Perfect Question" will help. Commented Jan 21, 2020 at 5:21
  • There is nothing unclear about this question. Commented Jan 21, 2020 at 7:18

2 Answers 2

1

In Postgres, your first need to create a function:

CREATE FUNCTION date_reservation_function()
RETURNS trigger AS $$
BEGIN
    IF NEW.date_reservation IS NULL OR NEW.date_reservation = '' THEN
        NEW.date_reservation := NOW();
    END IF;
    RETURN NEW;
END$$ LANGUAGE 'plpgsql'

Then, you create a trigger that invokes the function:

CREATE TRIGGER date_reservation_trigger
BEFORE INSERT ON reservation
FOR EACH ROW
EXECUTE PROCEDURE date_reservation_function()
Sign up to request clarification or add additional context in comments.

Comments

1

In both MySQL and Postgres, I would recommend that you simply do this using a default value:

create table date_reservation (
    . . . 
    date_reservation timestamp default now(),
    . . . 
);

You can actually do something similar in MySQL.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.