I'm trying to keep a list of current content and archived content in my PHP Internet application. I want to be able to identify the content that as archived as having an enddate, and the content that is not archived as having no enddate. It would be ideal if I could create more paths, but I'm hoping to just start here.
The first thing I'm noticing is that I'm getting a syntax error at the " on line 1, but there is no double quote where I create the table. The second issue I'm having is the use of TIMESTAMP as a datatype. I tried to use CURRENT_TIMESTAMP for the startdate, and it returned syntax errors. The final problem I am having is with the trigger construction. I'm not able to get down far enough to troubleshoot it. As soon as I get past the references, I'll also try to troubleshoot that.
CREATE TABLE plan(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(32),
startdate TIMESTAMP NOT NULL,
enddate TIMESTAMP);
CREATE TABLE level(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(32),
description VARCHAR(500),
startdate TIMESTAMP NOT NULL,
enddate TIMESTAMP);
CREATE TABLE planIDxlevelID(
planID INT NOT NULL REFERENCES plan(id),
levelID INT NOT NULL REFERENCES level(id),
arXORcur ENUM('archive', 'current');
);
delimiter |
CREATE TRIGGER testref BEFORE INSERT ON plan
FOR EACH ROW BEGIN
INSERT INTO plan(id, plan, startdate, enddate)
SET id = LAST_INSERT_ID( id + 1), name = NEW.name, startdate = NEW.UTC_TIMESTAMP, enddate = NULL;
UPDATE plan(enddate) WHERE plan.id = OLD.id
SET enddate = UTC_TIMESTAMP;
INSERT INTO planIDxlevelID(planID, levelID, arXORcur)
SET planID = NEW.planID, levelID = OLD.levelID, arXORcur = current;
UPDATE planIDxlevelID(planID, levelID, arXORcur) WHERE planID = OLD.planID
SET planID = OLD.planID, levelID = OLD.levelID, arXORcur = archive;
END;
|
delimiter ;
INSERT INTO plan (name) VALUES
"Frogs", "Toys", "Trucks", "Nature", "Seasons",
"Construction", "Candy", "Rainbows", "Telephone", "Breakfasts";
TIMESTAMP vs DATETIME
This is a classic gotcha: TIMESTAMP is a special datatype that
is updated with "now" every time the row is touched, whether you update it to another value or leave it alone. What you want is DATETIME.
Next, you have numerous syntax and other errors. The following executes without error, however it may not now have the logic you want, but you can edit it to fix that:
CREATE TABLE plan (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(32),
startdate DATETIME NOT NULL, -- changed TIMESTAMP to DATETIME
enddate DATETIME -- changed TIMESTAMP to DATETIME
);
CREATE TABLE level (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(32),
description VARCHAR(500),
startdate DATETIME NOT NULL, -- changed TIMESTAMP to DATETIME
enddate DATETIME -- changed TIMESTAMP to DATETIME
);
CREATE TABLE planIDxlevelID (
planID INT NOT NULL REFERENCES plan(id),
levelID INT NOT NULL REFERENCES level(id),
arXORcur ENUM('archive', 'current')
);
DROP TRIGGER IF EXISTS test_insert;
delimiter |
CREATE TRIGGER test_insert BEFORE INSERT ON plan
FOR EACH ROW BEGIN
INSERT INTO plan (id, plan, startdate)
values (LAST_INSERT_ID() + 1, NEW.name, NEW.UTC_TIMESTAMP());
INSERT INTO planIDxlevelID (planID, levelID, arXORcur)
values (NEW.ID, null, arXORcur = current);
END;|
delimiter ;
DROP TRIGGER IF EXISTS test_update;
delimiter |
CREATE TRIGGER test_update BEFORE UPDATE ON plan
FOR EACH ROW BEGIN
UPDATE plan SET
enddate = UTC_TIMESTAMP
WHERE plan.id = OLD.id;
UPDATE planIDxlevelID SET
planID = NEW.ID,
levelID = null,
arXORcur = archive
WHERE planID = OLD.ID;
END;|
delimiter ;
INSERT INTO plan (name) VALUES
("Frogs"), ("Toys"), ("Trucks"), ("Nature"), ("Seasons"),
("Construction"), ("Candy"), ("Rainbows"), ("Telephone"), ("Breakfasts");
Related
DROP TABLE IF EXISTS Sales;
CREATE TABLE Sales (
id INT AUTO_INCREMENT,
product VARCHAR(100) NOT NULL,
quantity INT NOT NULL DEFAULT 0,
fiscalYear SMALLINT NOT NULL,
fiscalMonth TINYINT NOT NULL,
CHECK(fiscalMonth >= 1 AND fiscalMonth <= 12),
CHECK(fiscalYear BETWEEN 2000 and 2050),
CHECK (quantity >=0),
UNIQUE(product, fiscalYear, fiscalMonth),
PRIMARY KEY(id)
);
DROP TABLE IF EXISTS log;
CREATE TABLE log (
id INT AUTO_INCREMENT PRIMARY KEY,
timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ,
text VARCHAR(100)
);
Triggers
CREATE DEFINER=`root`#`localhost` TRIGGER `sales_AFTER_UPDATE` AFTER UPDATE ON `sales`
FOR EACH ROW
BEGIN
INSERT INTO log VALUES(NOW(),CONCAT('Update Student Record ', OLD.quantity));
END
UPDATE test for.sales SET quantity = 36
WHERE (id = 1);
ERROR 1136: 1136: Column count doesn't match value count at row 1
Iam new in mySQL Please help
You should specify columns in INSERT statement in your trigger explicitly, as you do not set all values in a row (auto incremented column excluded).
So it would be
INSERT INTO log(timestamp, text) VALUES (NOW(),CONCAT('Update Student Record ', OLD.quantity));
You have some errors.
First based on your trigger you need another column on log table which is as following
quantity INT NOT NULL DEFAULT 0
Second , do not use Keywords and Reserved Words like text and timestamp, it is a bad practice. If you do please put it inside backticks
Third your insert statement should be
INSERT INTO log(`timestamp`,`text`,quantity) VALUES(NOW(),'Update Student Record', OLD.quantity);
there is no need for CONCAT.
Fourth,
`sales`
table is not the same as Sales table, because you have used backticks.
Full working trigger below:
DELIMITER //
CREATE TRIGGER `sales_AFTER_UPDATE` AFTER UPDATE ON Sales
FOR EACH ROW
BEGIN
INSERT INTO log(`timestamp`,`text`,quantity) VALUES(NOW(),'Update Student Record', OLD.quantity);
END//
DELIMITER ;
Check working demo:
https://www.db-fiddle.com/f/iqwShcHK3AGJvU4MDbxDku/0
This procedure takes a brand name and matches it with the brandnames in the product table and creates a campaign.
When I call this procedure BrandNameCampaign with an input of a brandname that does NOT exist in the product table it is still creating a campaign. I know it's because I have kept the insertion query outside of the loop where it is checking whether camp_c cursor has null values or not.
However, if I put the query inside the repeat loop of the cursor, it generates an error code: 1062 duplicate entry 'x' (x being an int) for key 'campaign.PRIMARY'.
How do I fix my code so that a new campaign does not get inserted into the table without creating/firing a trigger. I want it to work within this procedure.
Table code
create table Product (
ProductID int not null,
ProductType varchar (20) not null,
PackageType varchar(20) not null,
YearProduced int not null,
Price float not null,
Brand varchar(255) not null,
PRIMARY KEY (ProductID)
)
create table Campaign (
CampaignID int not null,
CampaignStartDate date not null,
CampaignEndDate date,
PRIMARY KEY (CampaignID)
)
create table DiscountDetails (
ProductID int not null,
CampaignID int not null,
MembershipLevel varchar(20) not null,
Discount int not null,
primary key (ProductID, CampaignID, MembershipLevel),
foreign key (ProductID) references Product (ProductID),
foreign key (CampaignID) references Campaign (CampaignID)
)
Procedure code
create procedure BrandNameCampaign (in brandname varchar(50))
begin
declare v_finished int default 0;
declare prod_id int;
declare newcampid int;
declare camp_brand varchar(255);
declare camp_c cursor for
select productid, brand
from product
where brandname = brand
order by price desc limit 5;
declare continue handler for not found set v_finished = 1;
SELECT
MAX(CampaignID)
INTO newcampid FROM
campaign;
set newcampid = 1 + newcampid;
insert into `Campaign`(`CampaignID`,`CampaignStartDate`,`CampaignEndDate`) values
(newcampid,date_add(curdate(), interval 4 week), date_add( curdate(), interval 8 week));
-- working with cursor
open camp_c;
repeat
fetch camp_c into prod_id, camp_brand;
if not (v_finished = 1) then
insert into discountdetails values (prod_id, newcampid, 'S', 20);
insert into discountdetails values (prod_id, newcampid, 'G', 30);
insert into discountdetails values (prod_id, newcampid, 'P', 40);
end if;
until v_finished
end repeat;
close camp_c;
end//
One solution would be to use:
insert ignore into `Campaign` ...
The ignore means do not generate an error if the insert results in a duplicate key or other type of error.
A different solution might be to use a boolean variable:
declare v_do_insert tinyint(1) default true;
...
repeat
insert into `Campaign`(`CampaignID`,`CampaignStartDate`,`CampaignEndDate`)
select newcampid, date_add(curdate(), interval 4 week), date_add( curdate(), interval 8 week)
from dual where v_do_insert=true;
set v_do_insert = false;
...
until v_finished
end repeat;
In this example, the insert...select would insert one row the first time through the loop, but then on subsequent iterations of the loop, v_do_insert is now false, so the insert...select would insert zero rows.
I am trying to calculate the differential column of the score table upon inserting into a MySQL 8.0 database using a before trigger. The calculation uses the coursetee table as well. The trigger works fine on all but the first record in the table, which doesn't get updated. Is there something that I am missing? All relevant code is below.
CREATE TABLE coursetee (
teeID INT UNSIGNED AUTO_INCREMENT,
tee_name VARCHAR(20) NOT NULL,
course_rating DECIMAL(3,1) NOT NULL,
slope_rating INT UNSIGNED NOT NULL,
par INT UNSIGNED,
CONSTRAINT pk_coursetee PRIMARY KEY (teeID),
CREATE TABLE score (
roundID INT UNSIGNED AUTO_INCREMENT,
teeID INT UNSIGNED,
round_score INT UNSIGNED NOT NULL,
round_date DATETIME NOT NULL,
entry_date DATETIME DEFAULT NOW() NOT NULL,
differential DECIMAL(3,1),
CONSTRAINT pk_score PRIMARY KEY (roundID),
CONSTRAINT fk_score_coursetee FOREIGN KEY (teeID) REFERENCES coursetee(teeID));
DELIMITER $$
CREATE TRIGGER calculate_differential
BEFORE INSERT ON score
FOR EACH ROW
BEGIN
SET NEW.differential = (SELECT ROUND((113/ct.slope_rating)*(NEW.round_score-ct.course_rating),1)
FROM score, coursetee as ct
WHERE NEW.teeID = ct.teeID AND differential IS NULL);
END$$
DELIMITER ;
INSERT INTO coursetee
(courseID,tee_name,course_rating,slope_rating,par)
VALUES
(1,'Back',74.7,143,72),
(1,'Middle',72.6,136,72),
(1,'Front',71.3,132,72),
(2,'Back',76.8,155,72),
(2,'Middle',73.9,146,72),
(2,'Front',65.3,125,72);
INSERT INTO score
(playerID,teeID,round_score,round_date)
VALUES
(1,2,79,'2019-07-25');
INSERT INTO score
(playerID,teeID,round_score,round_date)
VALUES
(2,2,80,'2019-07-25');
INSERT INTO score
(playerID,teeID,round_score,round_date)
VALUES
(1,2,77,'2019-08-06');
The query returns:
image of query not returning calculated record for row 1
CREATE TRIGGER calculate_differential
BEFORE INSERT
ON score
FOR EACH ROW
SET NEW.differential = ( SELECT ROUND((113/ct.slope_rating)*(NEW.round_score-ct.course_rating),1)
FROM coursetee ct
WHERE NEW.teeID = ct.teeID);
fiddle
The problem was in using score table as a source of the subquery. And the hope that differential BEFORE inserting the first record will give anything except NOT FOUND. And testing the field of the record BEFORE INSERT for NULL makes no sense.
My assumption is about the FROM clause of the differential query in the trigger. i'd suggest you to try change the order of the tables -
FROM score, coursetee as ct
to
FROM coursetee as ct, score
Seems like its trying to extract nothing for the first insert...
I am working with an overlap super/subtype relationship dealing with person(s) in my DB. What I would like to do is have the overlapping subtypes insert new rows when the supertype gains a new row. I have attached my LRD to clarify the relationship. LRD
I would like to create a trigger that inserts new person rows into the correct subtype based on the attributes employee/user in the person table.
The code I have attempted so far gives me an error upon inserting rows into person noting "employee column does not exist". I would assume this is because this code is trying to use the if statement for the subtypes where it is in fact absent.
I would appreciate any feedback.
Table Details
CREATE TABLE PERSON
(person_id int(10) not null AUTO_INCREMENT,
first_name varchar(15) not null,
last_name varchar(15) not null,
employee char(1),
participant char(1),
CONSTRAINT person_pk PRIMARY KEY (person_id))
ENGINE=InnoDB;
CREATE TABLE EMPLOYEE
(eperson_id int(10) not null AUTO_INCREMENT,
enterprise_email varchar(30),
manager_id int(10),
CONSTRAINT employee_pk PRIMARY KEY (eperson_id),
CONSTRAINT employee_fk1 FOREIGN KEY(eperson_id) REFERENCES PERSON(person_id) ON update cascade,
CONSTRAINT employee_fk2 FOREIGN KEY(manager_id) REFERENCES EMPLOYEE(eperson_id) ON update cascade)
ENGINE=InnoDB;
CREATE TABLE PARTICIPANT
(pperson_id int(10) not null AUTO_INCREMENT,
city varchar(30),
state varchar(2),
zip int(5),
sign_up_date date,
termination_date date,
CONSTRAINT participant_pk PRIMARY KEY (pperson_id),
CONSTRAINT participant_fk FOREIGN KEY(pperson_id) REFERENCES PERSON(person_id) ON update cascade)
ENGINE=InnoDB;
Trigger Code
DELIMITER //
CREATE TRIGGER subtype_creator
AFTER INSERT ON PERSON
FOR EACH ROW
BEGIN
IF (employee = āeā ) THEN
INSERT INTO EMPLOYEE
SET eperson_id = NEW.person_id,
last_name = NEW.last_name,
enterprise_email = NULL,
manager_id = NULL;
IF (participant = āpā )THEN
INSERT INTO PARTICIPANT
SET pperson_id = NEW.person_id,
city=NULL,
state = NULL,
zip = NULL,
sign_up_date =NULL,
termination_date = NULL;
END IF;
END IF;
END//
DELIMITER ;
This may work for you.
First off, I think to have the AUTO_INCREMENT attribute on columns EMPLOYEE.eperson_id and PARTICIPANT.pperson_id is not needed.
Since both of those columns are FOREIGN KEYS and are referencing back to the person_id column of table PERSON, they need to have, and will be getting, their values from that column through the TRIGGER anyway so no need to autoincrement them in the tables.
So I would change that.
This TRIGGER should work with populating both tables EMPLOYEE and PARTICIPANT after INSERT on table PERSON:
DELIMITER //
CREATE TRIGGER subtype_creator
AFTER INSERT ON PERSON
FOR EACH ROW
BEGIN
INSERT INTO EMPLOYEE(eperson_id, enterprise_email, manager_id)
VALUES(NEW.person_id, NULL, NULL);
INSERT INTO PARTICIPANT(pperson_id, city, state, zip, sign_up_date, termination_date)
VALUES(NEW.person_id, NULL, NULL, NULL, NULL, NULL);
END//
DELIMITER ;
Hope this helps you.
I ended up figuring out two methods to solve my issue. I ended up altering my 'employee' and 'participant' into boolean/tinyint data types.
CREATE TABLE PERSON
(person_id int(10) not null AUTO_INCREMENT,
first_name varchar(15) not null,
last_name varchar(15) not null,
employee tinyint(1),
participant tinyint(1),
CONSTRAINT person_pk PRIMARY KEY (person_id))
ENGINE=InnoDB;
After that alteration I decided to try and break up the one trigger into two. This was successful.
Type 1
DELIMITER //
CREATE TRIGGER employee_creator
AFTER INSERT ON PERSON
FOR EACH ROW
BEGIN
IF (NEW.employee = 1 ) THEN
INSERT INTO EMPLOYEE
SET eperson_id = NEW.person_id,
last_name = NEW.last_name,
enterprise_email = NULL,
manager_id = NULL;
END IF;
END//
DELIMITER ;
DELIMITER //
CREATE TRIGGER participant_creator
AFTER INSERT ON PERSON
FOR EACH ROW
BEGIN
IF (NEW.participant =0 )THEN
INSERT INTO PARTICIPANT
SET pperson_id = NEW.person_id,
city=NULL,
state = NULL,
zip = NULL,
sign_up_date =NULL,
termination_date = NULL;
END IF;
END//
DELIMITER ;
After inplementing that first option I realized the ELSEIF would allow me to not split the two and create a single trigger.
Type 2
DELIMITER //
CREATE TRIGGER employee_creator
AFTER INSERT ON PERSON
FOR EACH ROW
BEGIN
IF (NEW.employee = 1 ) THEN
INSERT INTO EMPLOYEE
SET eperson_id = NEW.person_id,
last_name = NEW.last_name,
enterprise_email = NULL,
manager_id = NULL;
ELSEIF (NEW.participant =0 )THEN
INSERT INTO PARTICIPANT
SET pperson_id = NEW.person_id,
city=NULL,
state = NULL,
zip = NULL,
sign_up_date =NULL,
termination_date = NULL;
END IF;
END//
DELIMITER ;
I have a table defined in MySQL as following. Now I want to create this table in oracle.
But how can I convert on update trigger in to oracle?
create table test(
userid INTEGER(10) NOT NULL AUTO_INCREMENT,
CONSTRAINT PRIMARY KEY (userid),
fullname VARCHAR(200) NOT NULL,
email VARCHAR(50) NOT NULL,
createdat DATETIME NOT NULL DEFAULT NOW(),
updatedat DATETIME ON UPDATE NOW()
);
For a example, so:
CREATE TABLE test
(
userid INTEGER PRIMARY KEY
, fullname VARCHAR2(200) NOT NULL
, email VARCHAR2(50) NOT NULL
, createdat DATE DEFAULT CURRENT_DATE NOT NULL
, updatedat DATE
);
CREATE SEQUENCE test_seq START WITH 1 INCREMENT BY 1;
CREATE OR REPLACE TRIGGER test_insert
BEFORE INSERT
ON test
FOR EACH ROW
BEGIN
SELECT test_seq.NEXTVAL
INTO :new.userid
FROM DUAL;
END;
CREATE OR REPLACE TRIGGER test_update
BEFORE UPDATE
ON test
FOR EACH ROW
BEGIN
SELECT CURRENT_DATE
INTO :new.updatedat
FROM DUAL;
END;
Triggers may BEFORE UPDATE, AFTER UPDATE, and INSTEAD. Choose that you want. For more information read docs http://docs.oracle.com/cd/B19306_01/server.102/b14200/statements_7004.htm
Since Oracle 12c, you can avoid using SEQUENCE in using IDENTITY as done in standard SQL.
The solution to your problem is following
CREATE TABLE test
( userid INTEGER PRIMARY KEY GENERATED ALWAYS AS IDENTITY
, fullname VARCHAR2(200) NOT NULL
, email VARCHAR2(50) NOT NULL
, createdat DATE DEFAULT CURRENT_DATE NOT NULL
, updatedat DATE
);
CREATE OR REPLACE TRIGGER test_update
BEFORE UPDATE
ON test
FOR EACH ROW
BEGIN
SELECT CURRENT_DATE
INTO :new.updatedat
FROM DUAL;
END;