Syntax error unexpected ON - mysql

DELIMITER $$
SET TERMOUT ON
PROMPT Building Tutorial System. Please wait.
-- SET TERMOUT OFF
-- Drop Tables
DROP TABLE Enrollment CASCADE CONSTRAINTS;
DROP TABLE Attendance;
DROP TABLE Student CASCADE CONSTRAINTS;
DROP TABLE Tutorial CASCADE CONSTRAINTS;
-- Create Tables
CREATE TABLE Student(
id NUMBER(10) PRIMARY KEY NOT NULL,
name VARCHAR(255)
);
CREATE TABLE Tutorial(
id NUMBER(10) PRIMARY KEY NOT NULL,
name VARCHAR(255),
tutor VARCHAR(255),
room VARCHAR(255),
day NUMBER(10),
time DATE,
end_date_of_tutorial DATE,
type NUMBER(1)
);
CREATE TABLE Enrollment(
id NUMBER(10) PRIMARY KEY NOT NULL,
student_id NUMBER(10),
tutorial_id NUMBER(10),
enrollment_date_of_tutorial DATE,
FOREIGN KEY(student_id) REFERENCES Student(id),
FOREIGN KEY(tutorial_id) REFERENCES Tutorial(id)
);
CREATE TABLE Attendance(
enrollment_id NUMBER(10),
att_date DATE,
attendance CHAR(1),
FOREIGN KEY(enrollment_id) REFERENCES Enrollment(id)
);
I am getting red errors marks in MySQL workbench source code editor on line 1 "SET TERMOUT ON" Syntax error unexpected ON been trying to resolve this issue however no progress so if someone could help me out.

First of all, the correct SET syntax is
SET var = value
See http://dev.mysql.com/doc/refman/5.7/en/set-statement.html
Also, with the SET command you can either change a system variable or initialize a user variable. AFAIK TERMOUT is not a system variable so you should use:
SET #TERMOUT = ON
Finally, I am not sure that "ON" is a valid value for a user variable so you probably should use
SET #TERMOUT = 1

Related

MySQL Error Code: 1824. Failed to open the referenced table

When I try to create the 'Project table I get this error Code: 1824. Failed to open the referenced table 'Employee'.
My syntax:
CREATE DATABASE IF NOT EXISTS Test;
USE Test;
CREATE TABLE IF NOT EXISTS Customer (
CustomerID VARCHAR(7) NOT NULL,
CustomerName VARCHAR(50),
CustAdress VARCHAR(70),
CustEmail VARCHAR(50),
PRIMARY KEY (CustomerID)
);
CREATE TABLE IF NOT EXISTS Employee (
EmpID VARCHAR(7) NOT NULL,
EmpName VARCHAR(50),
Position VARCHAR(30),
EmpTimePrice INT(4),
PRIMARY KEY (EmpID)
);
CREATE TABLE IF NOT EXISTS Project (
ProjectNo VARCHAR(7),
ProjectName VARCHAR(50),
StartDate DATE,
ProjTimePrice INT(6),
CustomerID VARCHAR(7),
EmpID VARCHAR(7),
PRIMARY KEY (ProjectNo),
FOREIGN KEY (EmpID) REFERENCES Employee (EmpID),
FOREIGN KEY (CustomerID) REFERENCES Customer (CustomerID)
);
CREATE TABLE IF NOT EXISTS ProjectWork (
ProjectNo VARCHAR(7),
EmpID VARCHAR(7),
PWDATE DATE,
HoursWorked INT(5),
FOREIGN KEY (ProjectNo) REFERENCES Project (ProjectNo),
FOREIGN KEY (EmpID) REFERENCES Employee (EmpID)
);
The names look correct to me and I have referenced the foreign key so I don't understand why I get this error. Any help would be appreciated, thanks.
This normally happens when the two tables have different Table engines. so check both tables if they have same table engines. for example MYISAM do not support Foreign Keys
Just edited EmpID to empID and it worked for some reason.
One of the easiest ways to get this error is referencing a table that doesn't exist yet. Eg if you run the following code on a new schema:
create table ttest (bob varchar(10) not null,
constraint fkbob foreign key (bob) references other(bob) );
... you will get the MySQL error:
Error Code: 1824. Failed to open the referenced table 'other'
Because the other table doesn't exist.
The code in the question above creates Employee before referencing it. However, note that the CREATE DATABASE and CREATE TABLE statements have IF EXISTS, but there are no DROP IF EXISTS statements, as when creating a new database. If you were debugging a table creation script, changing and fixing things as you go, it would have been pretty easy to get into an inconsistent state where the tables were out of synch with the code. This would also explain why other people could run the code cleanly, because these tables didn't exist in their schema yet.

Failed to open the referenced table

I am new with SQL and I am not entirely sure why I am getting the error: ERROR 1824 (HY000) at line 5: Failed to open the referenced table 'products'
Operation failed with exitcode 1
Here is my code
drop database if exists cc;
create database cc /*!40100 default character set utf8 */;
use cc;
create table Customers(
CustomerID int not null,
FirstName varchar(255),
LastName varchar(255),
address varchar(255),
phoneNO varchar(11),
prodID int,
quantity int,
primary key (CustomerID),
foreign key (prodID) references Products(itemID)
);
create table Employees(
EmployeeID int not null,
FirstName varchar(255),
LastName varchar(255),
address varchar(255),
phoneNO varchar(11),
ManagerID int not null,
primary key (EmployeeID),
foreign key (managerID) references Managers(mgrID)
);
create table Managers(
mgrID int not null,
salary float,
MaxSupervisingCapacity int,
foreign key (mgrID) references Employees(EmployeeID),
primary key (mgrID)
);
You can't create a foreign key that references another table until after you create that other table. In the Customers table you have
foreign key (prodID) references Products(itemID)
but there's no Products table yet. And in Employees you have
foreign key (managerID) references Managers(mgrID)
but the Managers table is created after it.
You need to reorder your table creations. Create Products before Customers.
Also, you can't have circular foreign key relationships. Employees.managerID references Managers and Managers.mgrID references Employees. This creates a chicken-and-egg problem: how would you create the first employee, since it needs a manager, but you can't create the first manager because it needs to refer to an employee.
You can solve this problem by allowing the foreign keys to be null. So you create the first employee with a null manager, then create the manager, then replace the managerID with this ID.
There's also a chicken-and-egg problem when creating these two tables. You can't reference a table that has yet to be created. So leave out the foreign key specification when creating the table, and add it later with ALTER TABLE.
create table Employees(
EmployeeID int not null,
FirstName varchar(255),
LastName varchar(255),
address varchar(255),
phoneNO varchar(11),
ManagerID int not null,
primary key (EmployeeID)
);
create table Managers(
mgrID int not null,
salary float,
MaxSupervisingCapacity int,
foreign key (mgrID) references Employees(EmployeeID),
primary key (mgrID)
);
alter table Employees add foreign key (managerID) references Managers(mgrID);
You can just surround the whole thing with a
SET #OLD_FOREIGN_KEY_CHECKS=##FOREIGN_KEY_CHECKS;
SET FOREIGN_KEY_CHECKS=0;
## all of your schema and inserts
SET FOREIGN_KEY_CHECKS=#OLD_FOREIGN_KEY_CHECKS;
This change of the check will cause the engine not to do checks on those keys and just add them as is.
I have Just fixed this problem by Cheking both tables Storage Engine same and by settings the same Attributes for reff tables column.
you can try assigning the "ENGINE = INNODB" of the tables when creating them. One of the drawbacks when creating Foreign keys is that, the foreign keys can only be defined for certain storage engines (like InnoDB). The server accepts foreign key definitions for other storage engines but silently ignores them.
Example:
CREATE TABLE `Customers` (
CustomerID int not null,
FirstName varchar(255),
...
)ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
As you can see, when the table is finished, it is assigned the Engine = InnoDB and the default charset.
If you want to alter the table, you can do the following:
ALTER TABLE `Customers` ENGINE = InnoDB ;
If it served you, do not forget to approve the answer, you can make life easier for many developers.
I tried everything and nothing didn´t really work for me until I did the most simple thing. Go to SCHEMAS select the one that has de databases you are trying to work with and with right click, select set as default schema. That´s all, it worked perfectly.
Hope it helps

mysql generic syntax error for declaration of variable from LAST_INSERT_ID() - hard to analyse

I am attempting to set a variable based on the insert id of a an insert. So I wrote:
INSERT INTO person (first_name, last_name, middle_names, suffix, title)
VALUES ("Frank", "Thring", "", "", "Mr");
SET #person_frank_thring_id = LAST_INSERT_ID();
INSERT INTO address (line2, line3, postcode, state, suburb)
VALUES ("Dock 3", "22 Boundary Rd", 2088, "NSW", "Mascot");
SET #address_franks_aircraft_maintenance_id = LAST_INSERT_ID();
INSERT INTO contact (email, phone)
VALUES ("info#franks.com", "0245732552");
SET #contact_franks_aircraft_maintenance_id = LAST_INSERT_ID();
INSERT INTO maintainer (abn, address_id, contact_id, nk, name, person_id)
VALUES (73507986550, #address_franks_aircraft_maintenance_id, #contact_franks_aircraft_maintenance_id,
"c49439a4-a24a-4e1b-bc92-ebad6caf5e74", "Frank's Airplane Repairs", #person_frank_thring_id);
SET #maintainer_franks_maint_id = LAST_INSERT_ID();
INSERT INTO approved_process (nk, approval_number, description, expires, maintainer_id)
VALUES ("ee114aab-d201-498d-85a4-2b95e9df8b3d", "13226A", "Welding and Heat Treatment", "2021-05-02", #maintainer_franks_maint_id);
person, address, contact and maintainer are all pre-existing tables. And I ran the first three inserts in isolation, and I checked that the data were inserted into the tables. When I run the whole block I get a very generic error:
[ERROR in query 73] 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 '#maintainer_franks_maint_id' at line 2
Execution stopped!
EDIT - Please see the DROP and CREATE statements below:
DROP TABLE IF EXISTS address;
DROP TABLE IF EXISTS contact;
DROP TABLE IF EXISTS person;
DROP TABLE IF EXISTS maintainer;
CREATE TABLE person (
id BIGINT NOT NULL AUTO_INCREMENT,
first_name varchar(255),
last_name varchar(255),
middle_names varchar(255),
suffix varchar(255),
title varchar(255),
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE address (
id BIGINT NOT NULL AUTO_INCREMENT,
line1 varchar(255),
line2 varchar(255),
line3 varchar(255),
postcode integer,
state varchar(255),
suburb varchar(255),
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE contact (
id BIGINT NOT NULL AUTO_INCREMENT,
email varchar(255),
fax varchar(255),
mobile varchar(255),
phone varchar(255),
address_id bigint,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE maintainer (
id BIGINT NOT NULL AUTO_INCREMENT,
abn bigint,
image varchar(255),
nk varchar(255),
name varchar(255),
address_id bigint,
contact_id bigint,
person_id bigint,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
ALTER TABLE maintainer
ADD CONSTRAINT UK_maintainer_nk unique (nk);
ALTER TABLE maintainer
ADD CONSTRAINT FKs7jo395jusgm3631g7w845wy4 FOREIGN KEY (address_id) REFERENCES address (id);
ALTER TABLE maintainer
ADD CONSTRAINT FKgixmfq21peg70qtff3q4ktq1 FOREIGN KEY (contact_id) REFERENCES contact (id);
ALTER TABLE maintainer
ADD CONSTRAINT FK86boj3163qysduc7x3a2m84mh FOREIGN KEY (person_id) REFERENCES person (id);
and adding approved+process:
CREATE TABLE approved_process (
id BIGINT NOT NULL AUTO_INCREMENT,
nk varchar(255),
approval_number varchar(255),
description varchar(255),
expires date,
maintainer_id bigint,
subcontractor_id bigint,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
I hope this clarifies things.
Sorry everyone, it appears to be user error at some level. There were two problems: One was a strange invisible character at the beginning of the INSERT INTO approved_process line and also, for some reason Sequel Pro couldn't tell the difference between #franks in the email value and #franks at the beginning of the variable declaration.

Liquibase importing sql files for mysql fails on multiple statements

I'm trying to start using Liquibase for a project that already has multiple SQL changelog files (that were previously maintained by hand). Using an advise from somewhere on stackoverflow I added a
<includeAll path="db/initial"/>
directive to my initial change log file, but it was failing with a not very useful
You have an error in your SQL syntax
message. Playing around I figured out that the problem is with multiple sql statements in the file. As long as I supplied a file with only one statement it worked.
So how do I tell Liquibase to execute multiple statements from an sql file?
A bit more searching to figure out that the problem is not with Liquibase but with MySql driver that by default refuses to execute multiple statements.
The key bit was to add allowMultiQueries=true to my connection string:
url: jdbc:mysql://localhost/test_project?allowMultiQueries=true
I would expected that you'd be using a sql_file refactoring to import a SQL file. It supports a "splitStatements" attribute that would solve your issue without the need to make changes to your JDBC settings.
The include statement is normally used to import liquibase changelogs.... Have you adapted your files to be formatted SQL changelogs? It would be well worth trying this out, I've included an example file:
Example
scottTiger.sql
--liquibase formatted sql
--changeset mark:1
CREATE TABLE BONUS (ENAME VARCHAR(10) NOT NULL, JOB VARCHAR(9) NOT NULL, SAL DECIMAL(7, 2), COMM DECIMAL(7, 2));
ALTER TABLE BONUS ADD CONSTRAINT BONUS_PK PRIMARY KEY (ENAME, JOB);
--rollback DROP TABLE BONUS;
--changeset mark:2
CREATE TABLE DEPARTMENT (DEPTNO INT NOT NULL, NAME VARCHAR(14), LOCATION VARCHAR(13), CONSTRAINT DEPT_PK PRIMARY KEY (DEPTNO));
--rollback DROP TABLE DEPARTMENT;
--changeset mark:3
CREATE TABLE EMPLOYEE (EMPNO INT NOT NULL, NAME VARCHAR(10), JOB VARCHAR(9), BOSS INT, HIREDATE VARCHAR(12), SALARY DECIMAL(7, 2), COMM DECIMAL(7, 2), DEPTNO INT, CONSTRAINT EMP_PK PRIMARY KEY (EMPNO));
ALTER TABLE PUBLIC.EMPLOYEE ADD CONSTRAINT BOSS_FK FOREIGN KEY (BOSS) REFERENCES PUBLIC.EMPLOYEE (EMPNO) ON UPDATE RESTRICT ON DELETE RESTRICT;
ALTER TABLE PUBLIC.EMPLOYEE ADD CONSTRAINT DEPARTMENT_FK FOREIGN KEY (DEPTNO) REFERENCES PUBLIC.DEPARTMENT (DEPTNO) ON UPDATE RESTRICT ON DELETE RESTRICT;
--rollback DROP TABLE EMPLOYEE;
--changeset mark:4
CREATE TABLE PROJECT (PROJECTNO INT NOT NULL, DESCRIPTION VARCHAR(100), START_DATE VARCHAR(12), END_DATE VARCHAR(12), CONSTRAINT PROJECT_PK PRIMARY KEY (PROJECTNO));
--rollback DROP TABLE PROJECT;
--changeset mark:5
CREATE TABLE ROLE (ROLE_ID INT NOT NULL, DESCRIPTION VARCHAR(100), CONSTRAINT ROLE_PK PRIMARY KEY (ROLE_ID));
--rollback DROP TABLE ROLE;
--changeset mark:6
CREATE TABLE PROJECT_PARTICIPATION (PROJECTNO INT NOT NULL, EMPNO INT NOT NULL, START_DATE VARCHAR(12) NOT NULL, END_DATE VARCHAR(12), ROLE_ID INT);
ALTER TABLE PROJECT_PARTICIPATION ADD CONSTRAINT PARTICIPATION_PK PRIMARY KEY (PROJECTNO, EMPNO, START_DATE);
ALTER TABLE PUBLIC.PROJECT_PARTICIPATION ADD CONSTRAINT EMPLOYEE_FK FOREIGN KEY (EMPNO) REFERENCES PUBLIC.EMPLOYEE (EMPNO) ON UPDATE RESTRICT ON DELETE RESTRICT;
ALTER TABLE PUBLIC.PROJECT_PARTICIPATION ADD CONSTRAINT PROJECT_FK FOREIGN KEY (PROJECTNO) REFERENCES PUBLIC.PROJECT (PROJECTNO) ON UPDATE RESTRICT ON DELETE RESTRICT;
ALTER TABLE PUBLIC.PROJECT_PARTICIPATION ADD CONSTRAINT ROLE_FK FOREIGN KEY (ROLE_ID) REFERENCES PUBLIC.ROLE (ROLE_ID) ON UPDATE RESTRICT ON DELETE RESTRICT;
--rollback DROP TABLE PROJECT_PARTICIPATION;
--changeset mark:7
CREATE TABLE SALARYGRADE (GRADE INT NOT NULL, LOSAL INT NOT NULL, HISAL INT NOT NULL, CONSTRAINT SALGRADE_PK PRIMARY KEY (GRADE));
--rollback DROP TABLE SALARYGRADE;
Note:
One thing I love about liquibase is its support for rollbacks.

MySQL foreign key constraint error on insert in transaction

I have this error when inserting values into an association table during transaction:
Cannot add or update a child row: a foreign key constraint fails (dev.genre, CONSTRAINT fk_Genre_EntityType1 FOREIGN KEY (idEntityType) REFERENCES entitytype (idEntityType) ON DELETE NO ACTION ON UPDATE NO ACTION)
Here is the part of the schema that describes the tables used:
and here is the create statement of the genre table:
-- -----------------------------------------------------
-- Table `dev`.`Genre`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `dev`.`Genre` (
`idGenre` INT NOT NULL ,
`Name` VARCHAR(45) NULL COMMENT 'musique, spectacle, expo' ,
`idEntityType` INT NOT NULL ,
`idStyle` INT NOT NULL ,
PRIMARY KEY (`idGenre`, `idEntityType`, `idStyle`) ,
INDEX `fk_Genre_EntityType1_idx` (`idEntityType` ASC) ,
INDEX `fk_Genre_Style1_idx` (`idStyle` ASC) ,
CONSTRAINT `fk_Genre_EntityType1`
FOREIGN KEY (`idEntityType` )
REFERENCES `dev`.`EntityType` (`idEntityType` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_Genre_Style1`
FOREIGN KEY (`idStyle` )
REFERENCES `dev`.`Style` (`idStyle` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
To resume, the Genre tables references EntityType and Style, that's all.
The error occurs when I try to create a new Style and then add an association in the Genre table.
Everything is within a transaction, and what I do is:
create the new style in the Style table
get the id of the created style
insert an association in the genre table, and that's when I get the error.
I've searched quite a while on the web, but the only thing I found was this SO post: In MySQL, can I defer referential integrity checks until commit
I'm not sure this is what it is about here, because the error happens on a table that hadn't changed during the transaction (EntityType). Or am I missing something?
Can someone explain me the reason why I have this error please? (I'm stuck here)
Also, if it really have something to do with the SO post I mentioned earlier, is there a "clean" way of doing that kind of inserts without writing my own rollback mechanism?
Thanks for your answers
EDIT
the first query to insert a new style is:
CREATE PROCEDURE `Entity_CreateStyle`
(
IN p_name varchar(45),
OUT op_idStyle int(11)
)
BEGIN
insert into Style(idParentStyle, Name, IsValidated)
values(null, p_name, 0);
SET op_idStyle = LAST_INSERT_ID();
END
the next one, that produces the error:
CREATE PROCEDURE `Entity_AssociateStyleWithEntityType`
(
IN p_idGenre int(11),
IN p_Name varchar(45),
IN p_idEntityType int(11),
IN p_idStyle int(11)
)
BEGIN
insert into Genre(idGenre, Name, idEntityType, idStyle)
values(p_idGenre, p_Name, p_idEntityType, p_idStyle);
END
both are actually stored procedures that we call from C# using MySQL.Net connector
the p_idEntityType comes from the model (MVC) and I checked it's value is correct and exists in EntityType table.
The error message is clear: entitytype is referenced by genre. This means that ALL rows in entitytype must have a match in genre, or can't be inserted. There is a match when genre.entitytype = entitytype.entitytype.