Insert error with FK

Asked

Viewed 291 times

2

I have two tables, Client and Plan, which have the relationship 1:1. I have 3 plans registered in the database with their respective data. But when trying to insert a Customer that has a Foreing Key which relates to Id of the chosen plan. When entering the data I have the following error:

The INSERT statement conflicted with the FOREIGN KEY Constraint "Fk_dbo.Cliente.Planos_clienteid". The Conflict occurred in database "Mydatabase ", table "dbo. Planes ", column 'Planoid'. r nThe statement has been terminated.

My query

insert into Clientes values(NEWID(),'Nome do Cliente', '000.000.000-52', '001122','14966034-BC78-4B77-B817-4EC7AC483B05','logradouro','bairro','cep', 'telefone','email');

This is the value of Id of the existing Plan in the database:

14966034-BC78-4B77-B817-4EC7AC483B05

Select bank:

Resultado do Select

  • A question, because you use the NEWID() to fill the KP?

  • the Newid() generates the Id automatically at the time of execution so I don’t need to manually generate, the PK is the type Guid....

  • Jcsaint, there’s a cat... or this one Id did not exist in the table Planos at the time of insertion or the parameters of the insert are in the wrong order (try to specify fields) or have some problem in the Constraint. Can you include a more complete example with the DDL of tables + data? Maybe something from SQL Fiddle

  • Perform a sp_help table plans and see if really the constraint is being filled.

  • @Anthonyaccioly is right. We need more information to be able to help you. Apparently it does seem like a mistake "silly" position of the values for the columns.

  • It is recommended that you specify the fields in insert: insert into Clientes ([campos]) values ([valores]) and if you add new fields to the table, your insert doesn’t stop working.

Show 1 more comment

1 answer

0

When creating the table

CREATE TABLE Clients ( idCliente INT NOT NULL IDENTITY (1, 1) CONSTRAINT Pk_clients PRIMARY KEY (idCliente), Named client VARCHAR(255) )

with IDENTITY (1, 1) Newid() will not be required in Serts

Browser other questions tagged

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