I am new at scripting and am trying to create a table and insert values into the table below using DB Browser (SQLite).
BEGIN TRANSACTION;
CREATE TABLE IF NOT EXISTS "Doctor" (
"Doctorid" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
"DoctorName" TEXT NOT NULL,
"DoctorSpecialty" TEXT NOT NULL,
"ConsultationFee" NUMERIC NOT NULL
);
INSERT INTO Doctor
(Doctorid,DoctorName,DoctorSpecialty,ConsultationFee) VALUES
(1,'Wells','Respiritory Therapy',300),
INSERT INTO Doctor
(Doctorid,DoctorName,DoctorSpecialty,ConsultationFee) VALUES
(2,'Rose','Cardiology',375),
INSERT INTO Doctor
(Doctorid,DoctorName,DoctorSpecialty,ConsultationFee) VALUES
(3,'Johnson','Neurology',250),
INSERT INTO Doctor
(Doctorid,DoctorName,DoctorSpecialty,ConsultationFee) VALUES
(4,'Leath','Pharmacy',400),
INSERT INTO Doctor
(Doctorid,DoctorName,DoctorSpecialty,ConsultationFee) VALUES
(5,'Anderson','Anesthesiology',500),
INSERT INTO Doctor
(Doctorid,DoctorName,DoctorSpecialty,ConsultationFee) VALUES
(6,'Copeland','Radiology',550),
INSERT INTO Doctor
(Doctorid,DoctorName,DoctorSpecialty,ConsultationFee) VALUES
(7,'Macklin','Orthopedic Surgeon',575),
INSERT INTO Doctor
(Doctorid,DoctorName,DoctorSpecialty,ConsultationFee) VALUES
(8,'Witherspoon','Immunizations',100),
INSERT INTO Doctor
(Doctorid,DoctorName,DoctorSpecialty,ConsultationFee) VALUES
(9,'Pope','Billing',50),
INSERT INTO Doctor
(Doctorid,DoctorName,DoctorSpecialty,ConsultationFee) VALUES
(10,'Cockfield','Pediatrics',100);
COMMIT;
Once I run the script, I receive an error:
Result: near "INSERT": syntax error
At line 7:
INSERT INTO Doctor
(Doctorid,DoctorName,DoctorSpecialty,ConsultationFee) VALUES
(1,'Wells','Respiritory Therapy',300),
INSERT
Line 7 is: );
Im not sure what im doing wrong, can someone please help. Thanks.
remove Doctorid at insert time because it is AUTOINCREMENT.
INSERT INTO Doctor
(DoctorName,DoctorSpecialty,ConsultationFee) VALUES
('Wells','Respiritory Therapy',300);
and put the semicolon (;) end of the query
Inserting multiple values should be like this. You don't need to repeat INSERT statement.
INSERT INTO Doctor
(Doctorid,DoctorName,DoctorSpecialty,ConsultationFee) VALUES
(1,'Wells','Respiritory Therapy',300),
(2,'Rose','Cardiology',375),
(3,'Johnson','Neurology',250),
(4,'Leath','Pharmacy',400);
or change the comma to semi colon in each INSERT statement.
INSERT INTO Doctor
(Doctorid,DoctorName,DoctorSpecialty,ConsultationFee) VALUES
(1,'Wells','Respiritory Therapy',300);
INSERT INTO Doctor
(Doctorid,DoctorName,DoctorSpecialty,ConsultationFee) VALUES
(2,'Rose','Cardiology',375);
Related
I'm trying to create TRIGGERS in MySQL but I got a syntax error message. Here's my code for creating the tables and inserting the values:
The first table:
CREATE TABLE widgetSale (
id INTEGER auto_increment,
item_id INT,
customer_id INT,
quan INT,
price INT,
reconciled INT,
primary key (id));
INSERT INTO widgetSale (item_id, customer_id, quan, price, reconciled) VALUES (1, 3, 5, 1995, 0);
INSERT INTO widgetSale (item_id, customer_id, quan, price, reconciled) VALUES (2, 2, 3, 1495, 1);
INSERT INTO widgetSale (item_id, customer_id, quan, price, reconciled) VALUES (3, 1, 1, 2995, 0);
SELECT * FROM widgetSale;
My first trigger for the first table:
delimiter //
CREATE TRIGGER updateWidgetSale BEFORE UPDATE ON widgetSale for each row
BEGIN
IF NEW.reconciled = 1 THEN
SIGNAL SQLSTATE VALUE '45000'
SET MESSAGE_TEXT = 'cannot update table "widgetSale" after it has been reconciled';
END IF;
END
//
And here are my tables to create trigger for timestamps:
DROP TABLE IF EXISTS widgetSale;
CREATE TABLE widgetCustomer(
id integer auto_increment,
name TEXT,
last_order_id INT,
stamp TEXT,
primary key(id) );
CREATE TABLE widgetSale (
id integer auto_increment,
item_id INT,
customer_id INTEGER,
quan INT,
price INT,
stamp TEXT,
primary key(id) );
CREATE TABLE widgetLog (
id integer auto_increment,
stamp TEXT,
event TEXT,
username TEXT,
tablename TEXT,
table_id INT,
primary key(id));
INSERT INTO widgetCustomer (name) VALUES ('Bob');
INSERT INTO widgetCustomer (name) VALUES ('Sally');
INSERT INTO widgetCustomer (name) VALUES ('Fred');
SELECT * FROM widgetCustomer;
delimiter //
CREATE TRIGGER stampSale before insert on widgetSale for each row
BEGIN
SET NEW.stamp = CURDATE();
update widgetCustomer set last_order_id = new.item_id where widgetCustomer.id = new.customer_id;
update widgetCustomer set stamp = new.stamp;
INSERT INTO widgetLog (stamp, event, username, tablename, table_id) VALUES (NEW.stamp, 'INSERT ', 'TRIGGER', 'widgetSale', NEW.customer_id);
END
//
INSERT INTO widgetSale (item_id, customer_id, quan, price) VALUES (1, 3, 5, 1995);
INSERT INTO widgetSale (item_id, customer_id, quan, price) VALUES (2, 2, 3, 1495);
INSERT INTO widgetSale (item_id, customer_id, quan, price) VALUES (3, 1, 1, 2995);
SELECT * FROM widgetSale;
SELECT * FROM widgetCustomer;
SELECT * FROM widgetLog;
So my problem is:
I could not create the first trigger because it seems the raise function does not exist in MySQL. I was advised to use Signal statement but I don't know what syntax should I put?
I was able to create the trigger for timestamps but I got error code 1442. I don't know what went wrong with my syntax?
*Updated: I was able to solve my problems now, for the second trigger, turns out I need to CREATE TRIGGER BEFORE INSERT, not AFTER INSERT (because otherwise I cannot update the table), and wrote two UPDATE statements to update the widgetCustomer table in which I want to update the id and the stamp column, and I have to do that by writing two separate UPDATE statements.
Summary of errors from above comment thread:
You need to use DELIMITER when defining stored routines in the MySQL client. See https://dev.mysql.com/doc/refman/8.0/en/stored-programs-defining.html
Use the SIGNAL statement to raise errors in a MySQL stored routine. See https://dev.mysql.com/doc/refman/8.0/en/signal.html
Your condition appears to be reconciled = 1, and you reference that column in the row that spawned the trigger as NEW.reconciled. You don't need to SELECT from the table to get that column.
delimiter //
CREATE TRIGGER updateWidgetSale BEFORE UPDATE ON widgetSale
BEGIN
IF NEW.reconciled = 1 THEN
SIGNAL SQLSTATE VALUE '45000'
SET MESSAGE_TEXT = 'cannot update table "widgetSale" after it has been reconciled';
END IF;
END
//
User blabla_bingo noticed you had mistakenly referenced reconciled in some INSERT statements where it didn't belong. I guess it was the result of copy & paste of some lines of code.
Re error 1442: MySQL does not allow you to INSERT/UPDATE/DELETE the same table for which the trigger was spawned. In other words, if the trigger is for an operation ON widgetSale, then you can't UPDATE widgetSale in that trigger.
But you don't need to UPDATE the table to change one column in current row for which the trigger spawned. You simply reference the columns of current row with NEW.columnName like the following to set one column to a scalar value:
SET NEW.stamp = CURDATE();
CURDATE() is an equivalent way of writing DATE(NOW()).
CREATE TABLE Movies (
ID int PRIMARY KEY,
Title varchar(50),
Director varchar(50),
Year int ,
Length_minutes decimal(5,2)
);
Here is the insert statement:
INSERT INTO Movies VALUES (1,'Toy Story','John Lasseter',1995,81) ;
INSERT INTO Movies VALUES (2,'A Bug\'s life','John Lasseter',1998,95) ;
INSERT INTO Movies VALUES (3,'Toy','John Lasseter',1999,93) ;
INSERT INTO Movies VALUES (4,'Monsters,Inc','Pete Docter',2001,92) ;
INSERT INTO Movies VALUES (5,'Finding Nemo','Andrew Stanton',2003,107) ;
Schema Error: Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INSERT INTO Movies VALUES (3,'Toy Story 2 ','John Lasseter',1999,93) ; INSERT I' at line 4
The insert statements after id2 don't work.
Primary Keys cannot be repeated. If you are inserting the same one again that is an issue.
MySQL table creation
CREATE TABLE movies(
id INT UNSIGNED AUTO_INCREMENT, PRIMARY KEY(id),
title VARCHAR(250),
director VARCHAR(250),
year TINYINT,
minutes TINYINT
)ENGINE=InnoDB;
Since the id is a PRIMARY KEY that AUTO_INCREMENTs, you will have to label all of your fields.
MySQL insertion (only use on first insert)
INSERT movies (title, director, year, minutes) VALUES('Toy Story 2', 'John Lasseter', 1999, 93);
MySQL update
UPDATE movies SET title='Toy Story 2', director='John Lasseter', year=1999, minutes=93 WHERE id=3;
I see the issue from the INSERT statement is here:
INSERT INTO Movies VALUES (2,'A Bug\'s life','John Lasseter',1998,95) ;
There are two ways you can do this either escaping the single quote with another single quote like '' or replace the opening and closing single quotes to double quotes. Look at this two example:
INSERT INTO Movies VALUES (2,'A Bug''s life','John Lasseter',1998,95) ;
INSERT INTO Movies VALUES (6,"A Bug's life","John Lasseter",1998,95) ;
Fiddle: https://www.db-fiddle.com/f/DfwTYpTr8Xj3McLi9KZNZ/2
Try :
INSERT INTO Movies (ID, Title, Director, Year, Length_minutes) VALUES (3,'Toy Story 2','John Lasseter',1999,93) ;
I am trying to insert 50 values into a DB, the table has two column names, one is an ID column set to auto increment and the other is for a code.
When I attempt to do the insert I get a error.
This is my SQL code:
INSERT INTO Names (Id, Code)
VALUES (NULL, 'CodeHere', NULL, 'CodeHere', NULL, 'CodeHERE' );
Don't include the ID column if it is auto increment and split the input to one one value per time
INSERT INTO Names (Code)
VALUES ('CodeHere'),('CodeHere'),('CodeHERE' );
INSERT INTO Names VALUES ('CodeHere'),('2CodeHere'),('3CodeHere'),('4CodeHere')
just ignore auto increment column.
Use this
INSERT INTO Names (Id, Code)
VALUES (NULL, 'CodeHere'), (NULL, 'CodeHere') ,( NULL, 'CodeHERE' );
I'm using MYSQL script and I want to insert some values in a table.
INSERT INTO `testType` (`name`) VALUES ('URL');
INSERT INTO `testType` (`name`) VALUES ('xD');
INSERT INTO `testType` (`name`) VALUES ('LOL');
But I only want to insert if the table is empty in the first place.
I'm not a SQL guy but basically
if(testType.length() == 0 {
INSERT INTO `testType` (`name`) VALUES ('URL');
INSERT INTO `testType` (`name`) VALUES ('xD');
INSERT INTO `testType` (`name`) VALUES ('LOL');
}
How can I do this the simplest and smallest way possible? Thank you.
EDIT: my question is different. I want to insert ALL THE DATA if the table is empty. not only one insert at the time
First, I would suggest doing this in one step:
INSERT INTO testType(name)
VALUES ('URL'), ('xD'), ('LOL');
Then, you can express this without IF:
INSERT INTO testType(name)
SELECT t.name
FROM (SELECT 'URL' as name UNION ALL
SELECT 'xD' as name UNION ALL
SELECT 'LOL' as name
) t
WHERE NOT EXISTS (SELECT 1 FROM testType);
Finally, if you want to insert these values if each doesn't exist, then you can let the database do the work. First, define a unique constraint/index on the name (if name is not already the primary key), and then use ON DUPLICATE KEY UPDATE:
CREATE UNIQUE INDEX unq_testtable_name ON testtable(name);
INSERT INTO testType(name)
VALUES ('URL'), ('xD'), ('LOL')
ON DUPLICATE KEY UPDATE name = VALUES(name);
You can use stored procedure
DELIMITER //
CREATE PROCEDURE `proc1` ()
BEGIN
SELECT COUNT(*) INTO variable1 FROM testType;
IF variable1 = 0 THEN
INSERT INTO `testType` (`name`) VALUES ('URL');
INSERT INTO `testType` (`name`) VALUES ('xD');
INSERT INTO `testType` (`name`) VALUES ('LOL');
END WHILE;
END //
Try this:
DECLARE #ExistCount INT;
SET #ExistCount = (SELECT COUNT(1) FROM `testType`);
IF #ExistCount<1
THEN
INSERT INTO `testType` (`name`) VALUES ('URL'),('xD'),('LOL');
END IF;
I have created two tables which i want to insert similar data in.
CREATE TABLE one(
one_id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(50) NOT NULL,
PRIMARY KEY (one_id)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE two(
two_id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(50) NOT NULL,
PRIMARY KEY (two_id)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
every time in run insert.
To do that,i am using transactions
START TRANSACTION;
SET #name = uuid();
INSERT INTO one(one_id,name) VALUES (Null,#name);
INSERT INTO two(two_id, name) VALUES (Null, #name);
COMMIT;
This does not produce new values on new inserts.It however inserts the same data in the field name as i wanted.
How can i make this work?.
I don't see a need to move to transactions in order to do that, just add an before insert trigger to the table .
Something like :
CREATE TRIGGER `ONE_TABLE_TRIGG` BEFORE INSERT ON `one`
FOR EACH
ROW BEGIN
SET NEW.name= UUID( );
END ;
You can check if it's null before doing that. do this on both tables and you're good or add insert to the other table on 1 trigger.
I solved it without much complexities by having several having several transaction statements in the same file
START TRANSACTION;
SET #name = uuid();
INSERT INTO one(one_id,name) VALUES (Null,#name);
INSERT INTO two(two_id, name) VALUES (Null, #name);
COMMIT;
START TRANSACTION;
SET #name = uuid();
INSERT INTO one(one_id,name) VALUES (Null,#name);
INSERT INTO two(two_id, name) VALUES (Null, #name);
COMMIT;
/*
Etc
*/