I had created a table using StoredProcedure in mysql and i had applied primary key constraint also when i tried to apply foreign key constraint..iam getting error 'Cant create table dbname.tablename'..and here is my Simple StoredProcedure
delimiter |
CREATE PROCEDURE SP_CREATE_TABLE_SAMP()
BEGIN
CREATE TABLE anan_user (
user_id bigint(15) NOT NULL AUTO_INCREMENT,
name varchar(70) DEFAULT NULL,
last_name varchar(70) DEFAULT NULL,
gender varchar(10) DEFAULT NULL,
username varchar(40) DEFAULT NULL,
password varchar(40) DEFAULT NULL,
dateofbirth date DEFAULT NULL,
email varchar(100) DEFAULT NULL,
phone varchar(25) DEFAULT NULL,
mobile varchar(25) DEFAULT NULL,
address varchar(250) DEFAULT NULL,
pincode varchar(15) DEFAULT NULL,
state_id bigint(15) DEFAULT NULL,
district_id bigint(15) DEFAULT NULL,
constituency_id bigint(15) DEFAULT NULL,
profile_Img varchar(100) DEFAULT NULL,
is_pwd_changed varchar(10) DEFAULT 'false',
registered_time timestamp NULL DEFAULT NULL,
updated_date timestamp NULL DEFAULT NULL,
PRIMARY KEY ( user_id )
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
END;
how to give foreign key constraints in stored procedures?
Check your syntax against the MySQL reference on foreign key constraints. It would also be helpful for you to post what you tried, and how you're trying to set the foreign key constraint.
An example constraint definition is:
CREATE TABLE parent (id INT NOT NULL,
PRIMARY KEY (id)
) ENGINE=INNODB;
CREATE TABLE child (id INT, parent_id INT,
INDEX par_ind (parent_id),
FOREIGN KEY (parent_id) REFERENCES parent(id)
ON DELETE CASCADE
) ENGINE=INNODB;
The relevant syntax is the FOREIGN KEY (parent_id) REFERENCES parent(id).
Related
I want to convert below MY SQL query to Oracle SQL query, could someone please help ?
Below instructor table is parent entity, and instructor_detail table child entity.
CREATE TABLE `instructor_detail` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`youtube_channel` varchar(128) DEFAULT NULL,
`hobby` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;
CREATE TABLE `instructor` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`first_name` varchar(45) DEFAULT NULL,
`last_name` varchar(45) DEFAULT NULL,
`email` varchar(45) DEFAULT NULL,
`instructor_detail_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `FK_DETAIL_idx` (`instructor_detail_id`),
CONSTRAINT `FK_DETAIL` FOREIGN KEY (`instructor_detail_id`) REFERENCES `instructor_detail` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;
I have tried below but not working
CREATE TABLE instructor (
id numeric(11) NOT NULL PRIMARY KEY,
first_name varchar(45) DEFAULT NULL,
last_name varchar(45) DEFAULT NULL,
email varchar(45) DEFAULT NULL,
instructor_detail_id numeric(10) not null
);
CREATE TABLE instructor_detail (
id NUMERIC(11) NOT NULL PRIMARY KEY,
youtube_channel varchar(128) DEFAULT NULL,
hobby varchar(45) DEFAULT NULL,
CONSTRAINT fk_instructor
FOREIGN KEY (instructor_detail_id)
REFERENCES instructor(instructor_detail_id)
);
error : Error report -
ORA-00904: "INSTRUCTOR_DETAIL_ID": invalid identifier
00904. 00000 - "%s: invalid identifier"
*Cause:
*Action:
Appreciated
Oracle 11 doesn't support auto-generated primary keys, so you need a trigger for that. And there are some different rules on cascading constraints.
But otherwise:
CREATE TABLE instructor_detail (
id int PRIMARY KEY,
youtube_channel varchar2(128) DEFAULT NULL,
hobby varchar2(45) DEFAULT NULL
) ;
CREATE TABLE instructor (
id int NOT NULL PRIMARY KEY,
first_name varchar2(45) DEFAULT NULL,
last_name varchar2(45) DEFAULT NULL,
email varchar2(45) DEFAULT NULL,
instructor_detail_id int,
CONSTRAINT FK_DETAIL FOREIGN KEY (instructor_detail_id) REFERENCES instructor_detail (id)
) ;
CREATE INDEX idx_instructor_instruct_detail_id ON instructor(instructor_detail_id);
Here is a db<>fiddle.
CREATE TABLE DEPARTMENT ( Dname VARCHAR(15) NOT NULL,
Dnumber INT NOT NULL,
Mgr_ssn CHAR(9) NOT NULL,
Mgr_start_Date DATE,
PRIMARY KEY(Dnumber),
UNIQUE(Dname),
FOREIGN KEY(Mgr_ssn) REFERENCES EMPLOYEE (Ssn)
ON DELETE SET DEFAULT ON UPDATE CASCADE);
I am a beginner in MySQL. The command above gives me this:
Cannot add foreign key constraint
I have tried SHOW ENGINE INNODB STATUS;
I checked EMPLOYEE.Ssn's data type.
Please help.
Edit: My EMPLOYEE table
| employee | CREATE TABLE `employee` (
`Fname` varchar(10) DEFAULT NULL,
`Minit` char(1) DEFAULT NULL,
`Lname` varchar(10) DEFAULT NULL,
`Ssn` char(9) NOT NULL,
`Bdate` date DEFAULT NULL,
`Address` varchar(40) DEFAULT NULL,
`Sex` char(1) DEFAULT NULL,
`Salary` int(11) DEFAULT NULL,
`Super_ssn` char(9) DEFAULT NULL,
`Dno` int(11) DEFAULT NULL,
PRIMARY KEY (`Ssn`),
KEY `Super_ssn` (`Super_ssn`),
CONSTRAINT `employee_ibfk_1` FOREIGN KEY (`Super_ssn`) REFERENCES `EMPLOYEE` (`Ssn`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
According to the MySQL docs at https://dev.mysql.com/doc/refman/5.7/en/create-table-foreign-keys.html , you can't use SET DEFAULT with INNODB :
SET DEFAULT: This action is recognized by the MySQL parser, but both InnoDB and NDB reject table definitions containing ON DELETE SET DEFAULT or ON UPDATE SET DEFAULT clauses
I have two tables which I'd like to connect with foreign key constraint
For some reason, when I try to do it, it fails and and says: #1215 - Cannot add foreign key constraint
Here is my first table:
CREATE TABLE `zmaneyhayom` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`zman_id` varchar(255) NOT NULL,
`tempHour` tinyint(1) NOT NULL,
`tempHourType` varchar(255) NOT NULL,
`tempHourNum` double NOT NULL,
`tempMinutes` tinyint(1) NOT NULL,
`tempMinutesType` varchar(255) NOT NULL,
`tempMinutesNum` double NOT NULL,
`regularMinutes` tinyint(1) NOT NULL,
`regularMinutesNum` double NOT NULL,
`equivalentMinutes` tinyint(1) NOT NULL,
`equivalentMinutesNum` double NOT NULL,
`degreesBelowHorizon` tinyint(1) NOT NULL,
`degreesBelowHorizonNum` double NOT NULL,
`beforeAfter` varchar(6) NOT NULL,
`riseSet` varchar(4) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `zman_id_2` (`zman_id`),
KEY `zman_id` (`zman_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
And this table holds ID and name, which eventually the ID in this table is the name for the previous table (zman_id column):
CREATE TABLE `zmaneyhayomlabels` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
This is the code I'm attempting in order to create the constraint:
ALTER TABLE `zmaneyhayom` ADD FOREIGN KEY ( `zman_id` ) REFERENCES `luah_v2`.`zmaneyhayomlabels` (
`id`
) ON DELETE NO ACTION ON UPDATE NO ACTION ;
I have no idea why it's failing :/
What I want is that whenever I go on phpmyadmin and go to the first table, instead of typing some id in zman_id I will have a select box which I can select a name (which is stored in the second table) but the value it will store will be the ID.
they are not same type id is INT and zman_id is varchar.
you can change this
`zman_id` varchar(255) NOT NULL,
to
`zman_id` int(11) NOT NULL,
I am trying to create a table with a varchar column as foreign key but MySql gives me an error while creating the table. My query is like this:
CREATE TABLE network_classes (
id TINYINT(1) UNSIGNED NOT NULL AUTO_INCREMENT,
category VARCHAR(80) NOT NULL,
PRIMARY KEY(id),
KEY `key_1` (`id`,`category`)
)
ENGINE=InnoDB;
CREATE TABLE networks (
id TINYINT(3) UNSIGNED NOT NULL AUTO_INCREMENT,
name VARCHAR(100) NOT NULL,
category VARCHAR(80) NOT NULL,
director_id TINYINT(3) UNSIGNED NULL,
director_name VARCHAR(100) NULL,
description VARCHAR(1000) NULL,
last_modified TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
user_id SMALLINT UNSIGNED NULL,
PRIMARY KEY(id),
KEY `networks_fk1` (`category`),
CONSTRAINT `networks_fk1` FOREIGN KEY (`category`) REFERENCES `network_classes` (`category`) ON DELETE NO ACTION,
INDEX networks_index2471(name),
INDEX networks_index2472(director_id, director_name)
)
ENGINE=InnoDB;
and I get this error:
[Err] 1215 - Cannot add foreign key constraint
I am using MySQL 5.6.12. How can I rewrite my query to fix it?
You can only have a foreign key referencing a unique field. Modify your network_classes table so that the category field is unique, like below
CREATE TABLE network_classes (
id TINYINT(1) UNSIGNED NOT NULL AUTO_INCREMENT,
category VARCHAR(80) NOT NULL,
PRIMARY KEY(id),
UNIQUE KEY `category_UNIQUE` (`category`),
KEY `key_1` (`id`,`category`)
)
ENGINE=InnoDB;
CREATE TABLE networks (
id TINYINT(3) UNSIGNED NOT NULL AUTO_INCREMENT,
name VARCHAR(100) NOT NULL,
category VARCHAR(80) NOT NULL,
director_id TINYINT(3) UNSIGNED NULL,
director_name VARCHAR(100) NULL,
description VARCHAR(1000) NULL,
last_modified TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
user_id SMALLINT UNSIGNED NULL,
PRIMARY KEY(id),
KEY `networks_fk1` (`category`),
CONSTRAINT `networks_fk1` FOREIGN KEY (`category`) REFERENCES `network_classes` (`category`) ON DELETE NO ACTION,
INDEX networks_index2471(name),
INDEX networks_index2472(director_id, director_name)
)
ENGINE=InnoDB;
You should then be able to add the foreign key you want
column types in the table and the referenced table do not match for
constraint
Why 2 varchar columns with same size not match in type? And of course the answer is obvious collation. Turns out that in the new table the column was UTF-8 instead of ASCII as in the referenced table. Changed to ascii and done.
The target of a FOREIGN KEY constraint needs to be indexed. Usually, it is a PRIMARY KEY so this isn't an issue, but in your case it's not (although it's part of a composite key, that's not enough)
Create an index on your network_classes.category field:
CREATE INDEX category_idx ON network_classes(category);
Then re-create your networks table.
For me, it was the charset that was missing. Just providing an example for reference.
CREATE TABLE `client` (
id int NOT NULL,
name varchar(255) NOT NULL,
email varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
created_at datetime NOT NULL,
created_by varchar(50) NOT NULL DEFAULT 'admin',
updated_at datetime NOT NULL,
updated_by varchar(50) NOT NULL DEFAULT 'admin',
PRIMARY KEY (id),
UNIQUE KEY name_UNIQUE (name),
KEY name_idx (name)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
create table `usecase` (`id` int NOT NULL AUTO_INCREMENT, `client` varchar(255) NOT NULL, `name` varchar(255), `description` varchar(1000), `rule_file` varchar(255), `parsed_rule_file` varchar(255), `archived` BOOLEAN DEFAULT 0, `state` ENUM('INITIATED','PARSED','UPLOADED', 'COMPLETE','FAILED'), `digest` varchar(255), `created_by` varchar(128) DEFAULT NULL, `created_at` datetime(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3), `updated_by` varchar(128) DEFAULT NULL, `updated_at` datetime(3) DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `uniq_usecase_id` (`client`,`name`), FOREIGN KEY (`client`) REFERENCES client(`name`))ENGINE=InnoDB DEFAULT CHARSET=latin1;
I had missed the line
DEFAULT CHARSET=latin1
in
CONSTRAINT `networks_fk1` FOREIGN KEY (`category`)
REFERENCES `network_classess` (`category`) ON DELETE NO ACTION,
you have used network_classess instead of network_classes (as in your create table script), so that table not exists.
EDIT
Name of your constraint is the same of key (networks_fk1) change ones.
I read better your DDL.
Your table network_classes has a primary key ID, so is correct put as foreign key a field to link your id field, the category field mustn't appear in your table network, but I think you must put fk_network_class (as int) linked to id (of network_classes)
I've used the other posts on this topic, but I'm having no luck.
Here's the code I execute:
UPDATE tblOrderItems SET `ItemID` = 0004 WHERE `OrderNum`= 203 AND `OrderItemID` = 26
Here's my error:
Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails (`cai0066`.`tblOrderItems`, CONSTRAINT `ItemID` FOREIGN KEY (`ItemID`) REFERENCES `tblCatalogItems` (`ItemID`))
Notes:
It happens when I either INSERT or UPDATE into tblOrderItems.
tblCatalogItems does have an ItemID of 0004. See: this
Here are the create statements generated by MySQL Workbench:
delimiter $$
CREATE TABLE `tblCatalogItems` (
`ItemID` varchar(10) NOT NULL DEFAULT '',
`ItemName` varchar(50) DEFAULT NULL,
`Wholesale` decimal(10,2) DEFAULT NULL,
`Cost5-10` decimal(10,2) DEFAULT NULL,
`Cost11-19` decimal(10,2) DEFAULT NULL,
`Cost20` decimal(10,2) DEFAULT NULL,
`Retail` decimal(10,2) DEFAULT NULL,
PRIMARY KEY (`ItemID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1$$
delimiter $$
CREATE TABLE `tblItemCosts` (
`Cost` decimal(10,2) DEFAULT NULL,
`VendorID` int(11) NOT NULL,
`ItemID` varchar(10) NOT NULL,
KEY `VendorID_idx` (`VendorID`),
KEY `ItemID_idx` (`ItemID`),
CONSTRAINT `VendorID` FOREIGN KEY (`VendorID`) REFERENCES `tblVendors` (`VendorID`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1$$
delimiter $$
CREATE TABLE `tblOrderItems` (
`OrderItemID` int(11) NOT NULL AUTO_INCREMENT,
`OrderNum` int(11) NOT NULL,
`PayPalTxnID` int(10) DEFAULT NULL,
`Description` varchar(225) DEFAULT NULL,
`Quantity` int(11) DEFAULT NULL,
`UnitPrice` decimal(10,2) DEFAULT NULL,
`ItemStatus` varchar(30) DEFAULT NULL,
`TrackingNumber` varchar(50) DEFAULT NULL,
`ShippingCost` decimal(10,2) DEFAULT NULL,
`ItemID` varchar(50) DEFAULT NULL,
`TotalPrice` decimal(10,2) DEFAULT NULL,
PRIMARY KEY (`OrderItemID`,`OrderNum`),
UNIQUE KEY `PayPalTxnID_UNIQUE` (`PayPalTxnID`),
KEY `PayPalTxnID_idx` (`PayPalTxnID`),
KEY `UnitPrice_idx` (`ItemID`),
KEY `OrderNum_idx` (`OrderNum`),
CONSTRAINT `ItemID` FOREIGN KEY (`ItemID`) REFERENCES `tblCatalogItems` (`ItemID`),
CONSTRAINT `OrderNum` FOREIGN KEY (`OrderNum`) REFERENCES `tblOrders` (`OrderNum`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `UnitPrice` FOREIGN KEY (`ItemID`) REFERENCES `tblCatalogItems` (`ItemID`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=7678 DEFAULT CHARSET=latin1$$
delimiter $$
CREATE TABLE `tblOrderItemStatus` (
`OrderItemID` int(11) NOT NULL,
`OrderDate` varchar(12) DEFAULT NULL,
`DesignProofSent` varchar(12) DEFAULT NULL,
`SubmittedToProduction` varchar(12) DEFAULT NULL,
`InProduction` varchar(12) DEFAULT NULL,
`Shipped` varchar(12) DEFAULT NULL,
PRIMARY KEY (`OrderItemID`),
UNIQUE KEY `OrderItemID_UNIQUE` (`OrderItemID`),
KEY `OrderItemID_idx` (`OrderItemID`),
CONSTRAINT `OrderItemID` FOREIGN KEY (`OrderItemID`) REFERENCES `tblOrderItems` (`OrderItemID`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1$$
delimiter $$
CREATE TABLE `tblOrders` (
`OrderNum` int(11) NOT NULL AUTO_INCREMENT,
`PayPalTxnID` int(10) DEFAULT NULL,
`OrderDate` varchar(50) DEFAULT NULL,
`OrderStatus` varchar(10) DEFAULT 'New',
`RushFlag` bit(1) DEFAULT b'0',
`ShipName` varchar(50) DEFAULT NULL,
`ShipEmail` varchar(100) DEFAULT NULL,
`ShipAddress1` varchar(50) DEFAULT NULL,
`ShipAddress2` varchar(50) DEFAULT NULL,
`ShipCity` varchar(50) DEFAULT NULL,
`ShipState` char(2) DEFAULT NULL,
`ShipZip` varchar(10) DEFAULT NULL,
`ShippingCharge` decimal(10,2) DEFAULT NULL,
`TotalCost` decimal(10,2) DEFAULT NULL,
PRIMARY KEY (`OrderNum`),
UNIQUE KEY `PayPalTxnID_UNIQUE` (`PayPalTxnID`)
) ENGINE=InnoDB AUTO_INCREMENT=346 DEFAULT CHARSET=latin1$$
delimiter $$
CREATE TABLE `tblVendors` (
`VendorID` int(11) NOT NULL,
`VendorName` varchar(50) DEFAULT NULL,
PRIMARY KEY (`VendorID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1$$
I tried the suggestion in this relevant post, but there were no results. This is a new database that hasn't actually been used yet; I've just filled it with fake data. Any ideas would be greatly appreciated.
There is a foreign key constraint on tblOrderItems that its ItemID needs to reference an ItemID that already exists in tblCatalogItems.
CONSTRAINT `ItemID` FOREIGN KEY (`ItemID`) REFERENCES `tblCatalogItems` (`ItemID`),
The message only means that you're trying to update tblOrderItems to reference the item in tblCatalogItems with ItemID= 0004, but that item does not exist.
Since ItemID is a varchar, you probably want to quote the 0004 or it may be converted to an int 4 before conversion to varchar. That may be your problem if the row with ItemID = 0004 actually exists.
UPDATE tblOrderItems SET `ItemID` = '0004' WHERE `OrderNum`= 203 AND `OrderItemID` = 26
Without seeing the table data I can't be sure, but I'm guessing it's because there is no record in tblCatalogItems with an ItemID of '0004'.
Also, you probably need to quote the 0004 in your update statement since the column is defined as character (varchar(10)) not number (int).
There is a foreign key relationship defined between tblCatalogItems.ItemId and tblOrderItems.ItemId which means that any row in tblOrderItems can only have a value for ItemId that matches an ItemId found in tblCatalogItems.
You would therefore need to insert a record into 'tblCatalogItems' with an ItemId of '0004' first, before running your update on tblOrderItems
Alternatively you need to change the SET ItemID = clause in your update to set a value that matches to an ItemId value that actually exists in the tblCatalogItems table
The data type needs to match on both sides of your foreign key constraint. Here you have a varchar(50) referring a varchar(10), which isn't allowed.
CREATE TABLE `tblCatalogItems` (
`ItemID` varchar(10) NOT NULL DEFAULT '',
...
) ENGINE=InnoDB DEFAULT CHARSET=latin1$$
...
CREATE TABLE `tblOrderItems` (
`ItemID` varchar(50) DEFAULT NULL,
...
CONSTRAINT `UnitPrice` FOREIGN KEY (`ItemID`) REFERENCES `tblCatalogItems` (`ItemID`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=7678 DEFAULT CHARSET=latin1$$