INSERT conflicted with FOREIGN KEY constraint

Asked

Viewed 1,670 times

-2

I have a problem when performing INSERT in a table in my BD because whenever I try to perform INSERT SQL Server return me this :

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_PEDIDO". The conflict occurred in the database "Company", table "dbo.ORDER", column 'COD_PEDIDO'.

I have read the queries several times and even then I do not find my error, follow the queries of the involved Tables :

Table request

-- Criando tabela PEDIDO
CREATE TABLE PEDIDO

(COD_PEDIDO INT NOT NULL PRIMARY KEY IDENTITY (1001,1),

DATA_VENDA DATE NOT NULL,

COD_CLIENTE INT NOT NULL,

COD_VENDEDOR INT NOT NULL,

CONSTRAINT FK_VENDEDOR FOREIGN KEY (COD_VENDEDOR) REFERENCES VENDEDOR

(COD_VENDEDOR),

CONSTRAINT FK_CLIENTE FOREIGN KEY (COD_CLIENTE) REFERENCES CLIENTE

(COD_CLIENTE));

-- Inserindo dados na tabela PEDIDO

INSERT INTO PEDIDO

VALUES

    ('2019/11/15', 1, 12),

    ('2019/11/10', 2, 12),

    ('2019/11/20', 3, 11),

    ('2019/11/22', 3, 13),

    ('2019/11/20', 4, 14),

    ('2019/11/25', 2, 10);


Table ITEM_PEDIDO

-- Criando tabela

CREATE TABLE ITEM_PEDIDO(

COD_ITEM INT PRIMARY KEY NOT NULL IDENTITY (200,1),

COD_PEDIDO INT NOT NULL,

COD_PROD INT NOT NULL,

QTDE_VENDIDO INT NOT NULL,

PRECO_VENDA FLOAT NOT NULL,

CONSTRAINT FK_PRODUTO FOREIGN KEY (COD_PROD) REFERENCES PRODUTO (COD_PROD),

CONSTRAINT FK_PEDIDO FOREIGN KEY (COD_PEDIDO) REFERENCES PEDIDO (COD_PEDIDO));


--Inserindo dados na tabela Item_Pedido
INSERT INTO ITEM_PEDIDO

VALUES

    (1048, 100, 1, 2500.00),

    (1044, 101, 1, 1500.00),

    (1045, 102, 1, 1500.00),

    (1046, 103, 1, 300.00),

    (1047, 104, 1, 700.00);

Att

  • Do cod_pedido 1048, 1044, 1045, 1046 and 1047 records exist in the requested table? You’re probably dealing with these errors because you’re referencing an item in your order to a non-existent order...

1 answer

1

Your error occurs because you are trying to insert a record into the table ITEM_PEDIO with the COD_PEDIDO: 1048, 1044, 1045, 1046 and 1047, but they do not exist in the table REQUEST, making it impossible for the database to reference between the two tables, as your Foreign key expects an existing record from the table REQUEST.

Make sure these COD_PEDIDO actually exist in the table REQUEST:

SELECT * FROM PEDIDO

Just go to your query of INSERT ITEM_PEDIDO order code in the table REQUEST that everything will take place as expected.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.