16

I have created table Employee

Create table Employee
(   
    FName varchar(20) Not Null,
    LName varchar(20) Not Null,
    SSN int Not Null,
    BDate Datetime,
    Address varchar(50),
    Sex char(1),
    Salary money,
    Super_SSN int,
    Primary Key(SSN),
    Foreign Key(Super_SSN) references Employee(SSN)
)

When i try to insert first row to ,

insert into Employee(FName,LName,SSN,BDate,Address,Sex,Salary,Super_SSN)
values('John','Smith',12345,'1965-01-09','Houston,TX','M',30000,33344) 

I am getting the error like..

Error:

The INSERT statement conflicted with the FOREIGN KEY SAME TABLE constraint "FK_Employee_Employee". The conflict occurred in database "Company", table "dbo.Employee", column 'SSN'.

8
  • Does the SSN of 33344 (taken from your example) exist in the table already? (edits were done to your question for formatting)
    – Twelfth
    Commented Jul 17, 2014 at 19:50
  • No, This is the first row in that table
    – SanjayDVG
    Commented Jul 17, 2014 at 19:51
  • Can the super_ssn column be null or does it have to be filled always?
    – juergen d
    Commented Jul 17, 2014 at 19:52
  • 2
    Well then of course it fails. Your foreign key constraint says that the value there must be in the table. It can't be in the table because you are inserting the first row.
    – Sean Lange
    Commented Jul 17, 2014 at 19:53
  • 4
    Please tell that SSN is some very poor abbreviation of a value that is NOT a social security number. And even more so, please tell me that the social security number is NOT the primary key.
    – Sean Lange
    Commented Jul 17, 2014 at 19:54

2 Answers 2

24

You need to first INSERT record for SSN '33344' with Super_SSN value as NULL.

INSERT INTO  Employee(FName,LName,SSN,BDate,Address,Sex,Salary,Super_SSN)
VALUES (<FName>,<LName>,'33344',<BDate>,<Address>,<Sex>,<Salary>,NULL)

After that insert

INSERT INTO Employee (FName,LName,SSN,BDate,Address,Sex,Salary,Super_SSN)
VALUES ('John','Smith',12345,'1965-01-09','Houston,TX','M',30000,33344)

If SSN '33344' have any Super_SSN, update the SSN value (this record should be available in table).

6

The error is likely thrown because there is a foreign key from Super_SSN to SSN column. You cannot insert a value of 33344 into Super_SSN unless that value already exists in SSN. Try inserting null into Super_SSN or inserting user 33344 first.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.