SQL exception due to foreign key constraint trying to create tables - sql

I was trying to create a set of tables using the following script:
DROP TABLE ORDERS IF EXISTS;
DROP TABLE INVOICE IF EXISTS;
CREATE TABLE ORDERS(
ORDER_ID BIGINT NOT NULL PRIMARY KEY IDENTITY,
...
INVOICE_ID BIGINT,
...
);
CREATE TABLE INVOICE(
INVOICE_ID BIGINT NOT NULL PRIMARY KEY IDENTITY,
...
ORDER_ID BIGINT,
...
FOREIGN KEY(ORDER_ID) REFERENCES ORDERS(ORDER_ID)
);
ALTER TABLE ORDERS ADD FOREIGN KEY(INVOICE_ID) REFERENCES INVOICE(INVOICE_ID);
This causes sql exception
java.sql.SQLException: is referenced by FOREIGN KEY constraint:
PUBLIC.INVOICE.SYS_FK_10079 in statement [ DROP TABLE ORDERS IF
EXISTS]
I couldn't figure out how to solve this ..I need invoiceId in ORDERS table and OrderID in INVOICE table as foreign keys..That is why I used the ALTER TABLE statement..Still ,it seems wrong..
(btw I am using hsqldb)
I would like to know how to do this properly..Any help most welcome..

Drop the foreign key on orders first:
ALTER TABLE ORDERS DROP FOREIGN KEY(INVOICE_ID) REFERENCES INVOICE(INVOICE_ID);
Then run your commands.

Related

Database contains foreign key that doesn exist even though there is a foreign key constraint?

I am working with a database where there is a foreign key ID that doesn't exist even though there is a foreign key constraint.
There is a table called "Workplace" with a foreign key column called "AddressID" pointing to another table called "Address"
The foreign key is as follows:
ALTER TABLE [dbo].[Workplace] WITH NOCHECK ADD CONSTRAINT [FK_Workplace_Address] FOREIGN KEY([AddressID])
REFERENCES [dbo].[Address] ([ID])
GO
ALTER TABLE [dbo].[Workplace] CHECK CONSTRAINT [FK_Workplace_Address]
GO
For one particular row in the Workplace table, the AddressID has a value of "1".
When I run select * from Address where ID = 1 there is no result.
Then I ran update Workplace set AddressID = 3 where Workplace.ID = 20 the value changed to 3 and I have verified that an Address with ID 3 exists.
Then I ran update Workplace set AddressID = 1 where Workplace.ID = 20 again and I get the error
The UPDATE statement conflicted with the FOREIGN KEY constraint "FK_Workplace_Address". The conflict occurred in database db_name, table "dbo.Address", column 'ID'.
I don't understand how the value 1 could have been put there in the first place. The Address with ID=1 couldn't have been deleted after the constraint was put in place. The constraint creation would also fail if the record was deleted in the first place. Does anyone know how this could be possible?
This is a database on Windows Server 2016, SQL Server 12.0.4237.0
You create your FOREIGN KEY with NOCHECK, as a result the values that already exist in the table are not checked. This can be replicated with the following:
CREATE TABLE dbo.Address (ID int NOT NULL CONSTRAINT PK_Address PRIMARY KEY);
GO
CREATE TABLE dbo.Workplace (ID int NOT NULL CONSTRAINT PK_Workplace PRIMARY KEY,
AddressID int)
GO
INSERT INTO dbo.Workplace
VALUES(1,3); --Works
GO
ALTER TABLE dbo.WorkPlace WITH NOCHECK ADD CONSTRAINT FK_Workplace_Address FOREIGN KEY (AddressID) REFERENCES dbo.Address(ID);
GO
ALTER TABLE dbo.Workplace CHECK CONSTRAINT FK_Workplace_Address;
GO
INSERT INTO dbo.Workplace
VALUES(2,3); --Fails
GO
UPDATE dbo.Workplace
SET AddressID = 2
WHERE ID = 1; --Fails
GO
DROP TABLE dbo.Workplace;
DROP TABLE dbo.Address;
As you can see, only rows that are INSERTed or UPDATEd after the constraint was created (with NOCHECK) are validated; the first row INSERTed is left as it was, with a reference to a row that does not exist.
Instead, create the key without NOCHECK defined, or with CHECK, and the statement will fail when you try to create it:
CREATE TABLE dbo.Address (ID int NOT NULL CONSTRAINT PK_Address PRIMARY KEY);
GO
CREATE TABLE dbo.Workplace (ID int NOT NULL CONSTRAINT PK_Workplace PRIMARY KEY,
AddressID int)
GO
INSERT INTO dbo.Workplace
VALUES(1,3); --Works
GO
ALTER TABLE dbo.WorkPlace WITH CHECK ADD CONSTRAINT FK_Workplace_Address FOREIGN KEY (AddressID) REFERENCES dbo.Address(ID); --Fails
GO
DROP TABLE dbo.Workplace;
DROP TABLE dbo.Address;
This generates the error below:
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_Workplace_Address". The conflict occurred in database "Sandbox", table "dbo.Address", column 'ID'.
Alternatively, create the key when you create the tables; though it's likely too late for that now.
CREATE TABLE dbo.Address (ID int NOT NULL CONSTRAINT PK_Address PRIMARY KEY);
GO
CREATE TABLE dbo.Workplace (ID int NOT NULL CONSTRAINT PK_Workplace PRIMARY KEY,
AddressID int CONSTRAINT FK_Workplace_Address FOREIGN KEY REFERENCES dbo.Address(ID));
GO
INSERT INTO dbo.Workplace
VALUES(1,3); --Fails
GO
DROP TABLE dbo.Workplace;
DROP TABLE dbo.Address;

How can I fix this error? there is no unique constraint matching given keys for referenced table "products"

CREATE TABLE order_items
(
order_id int,
product_id int,
quantity int,
CONSTRAINT order_items_pk
PRIMARY KEY(order_id,product_id),
CONSTRAINT order_items_order_id_fk
FOREIGN KEY(order_id) REFERENCES orders(id),
CONSTRAINT order_items_product_id_fk
FOREIGN KEY(product_id) REFERENCES products(id)
);
To create this table, you will first have to create the tables mentioned in the foreign key declarations. Those tables are orders and products.
If you don't create those tables first, the table server cannot handle those constraints.

Foreign key 'fk_orders_SalesRep' references invalid column 'snum' in referencing table 'orders'

What am I doing wrong? I'm trying to add a foreign key to an existing table
ALTER TABLE orders
ADD CONSTRAINT fk_orders_SalesRep
FOREIGN KEY (snum)
REFERENCES SalesRep(snum);
Table information
create table SalesRep(
snum varchar(5) primary key,
sname varchar(10),
hours Int
)
create table orders(
odId varchar(5) primary key,
itId varchar(5) foreign key(itId) references items(itId)
)
Like Martin said add the column first
ALTER TABLE orders
ADD snum varchar(5);
And then add the fk
ALTER TABLE orders
ADD CONSTRAINT fk_orders_SalesRep
FOREIGN KEY (snum)
REFERENCES SalesRep(snum);

Alter Foreign Key Constraint Primary Key Error

I'm trying to drop and recreate a foreign key constraint, but I get an error
There are no primary or candidate keys in the referenced table 'inventory' that match the referencing column list in the foreign key 'fkInventory_VendorsInventory'.
I have already gone into the table design for both tables referenced in the code, and ensured that the column being referenced is a primary key.
ALTER TABLE inventory_vendors
DROP CONSTRAINT fkInventory_VendorsInventory;
ALTER TABLE inventory_vendors
ADD CONSTRAINT fkInventory_VendorsInventory
FOREIGN KEY(itemnum) REFERENCES inventory(itemnum)
ON UPDATE CASCADE
ON DELETE CASCADE
I have done such a drop and recreation before with no problems at all with another set of tables (unfortunately i don't remember which tables they were).
As you mentioned in comments, you have 2 primary key columns in the Inventory table:
one is itemnum, the other is store_id
I prepare a sample SQL here: 2 tables created
CREATE TABLE inventory
(
itemnum INT,
store_id INT,
inventoryDesc char(200),
primary key (itemnum, store_id)
);
CREATE TABLE inventory_vendors
(
inventory_vendors int,
itemnum INT,
store_id INT,
VendorDetails varchar(200),
primary key (inventory_vendors)
);
Create Unique constraint for one of the primary key. Here I am creating UNIQUE constraint for itemnum column
ALTER TABLE inventory
ADD CONSTRAINT [IX_inventory] UNIQUE ( [itemnum] )
GO
Then execute your script for creating the foreign key constraint on inventory_vendors for itemnum column and you can drop them as well.
ALTER TABLE inventory_vendors
ADD CONSTRAINT fk_Inventory_Vendors_Inventory
FOREIGN KEY(itemnum) REFERENCES inventory(itemnum)
ON UPDATE CASCADE
ON DELETE CASCADE
ALTER TABLE inventory_vendors
DROP CONSTRAINT fk_Inventory_Vendors_Inventory;
Hope this might help you..

SQL Server : multi CASCADE Operation

I have two tables, and I want HEDE2 columns as FOREIGN KEY REFERENCES by HEDE table. FOR creating second table it will not allow because its having warning:
More than one key specified in column level FOREIGN KEY constraint, table 'HEDE2'.
But when I tried to ALTER TABLE HEDE2 for FOREIGN KEY it allows me to do that. Is anybody knows WHY this happens. Is this a bug?
CREATE TABLE cascde.HEDE
(
HedeID INT,
HedeID2 INT,
HedeID3 INT
CONSTRAINT PK_HEDE
PRIMARY KEY (HedeID, HedeID2, HedeID3)
)
GO
CREATE TABLE HEDE2
(
Hede2ID INT PRIMARY KEY IDENTITY(1,1) ,
HedeID INT,
HedeID2 INT,
HedeID3 INT
CONSTRAINT FK_HedeID
FOREIGN KEY (HedeID, Hede2ID, HedeID3)
REFERENCES cascde.HEDE (HedeID, HedeID2, HedeID3)
ON UPDATE NO ACTION
ON DELETE NO ACTION
)
Altering table HEDE 2 for foreign key. This allows me to do that:
ALTER TABLE cascde.HEDE2
ADD CONSTRAINT FK_HEDE
FOREIGN KEY(HedeID, HedeID2, HedeID3)
REFERENCES cascde.HEDE (HedeID, HedeID2, HedeID3)
ON UPDATE NO ACTION
ON DELETE NO ACTION
GO
You're missing a comma (,) after HedeID3 INT in the CREATE TABLE version.