Error when link 2 table in sql server - sql-server

I am trying to link 2 table in sql server let's assume one of them called customer and the other is product.
customer has custID as primary key and i want to link it with custID in product table as foreign key, and its give me this error:
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_product_customer". The conflict occurred in database "xyz", table "dbo.customer", column 'custID #'.
Is there anyone know, how can I fix the issue?

This could have many reasons.
Do you have a type missmatch between those columns?
Is every customer in products also in your customer table?
You can check the second part by using this:
SELECT DISTINCT p.customer_id
FROM products as p
LEFT JOIN customers as c ON p.customer_id = c.customer_id
WHERE c.customer_id is null
Hope this give you a hint.

Related

SQL Server foreign key contsraint preventing insert, where no conflict exits

I have 2 tables, and I have just done an insert of about 1,000,000 rows. I turned off foreign key constraints , but I have an error when I try and reinstate them with
ALTER TABLE ForexRebatesNow.dbo.Transactions WITH CHECK CHECK CONSTRAINT ALL
I get the following error:
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_Transactions_RebateAccounts". The conflict occurred in database "ForexRebatesNow", table "dbo.RebateAccounts", column 'Id'.
So I go to look for RebateAccountId that does not have a corresponding Id in the RebateAccounts table
SELECT Id
FROM ForexRebatesNow.dbo.RebateAccounts
WHERE Id NOT IN (SELECT RebateAccountId
FROM ForexRebatesNow.dbo.Transactions)
But this returns zero rows, so in my mind that conflict does not exist.
Am I missing something here?
EDIT
The relationship between RebateAccounts and Transactions is One to Many. RebateAccountId is a Nullable int on Transactions table as not allTransactions will have an associated RebateAccount, but any RebateAccount can have many Transactions
As you have not provided the relations between the two tables, I assume that there is a One-to-Many relation between RebateAccounts and Transactions Table. If I'm right then I guess you are checking the conflict in an opposite way. Your foreign key in in the dbo.Transactions table but you are checking it with the dbo.RebateAccounts table.
Try the following query to find the conflict.
SELECT * FROM Transactions WHERE RebateAccountId NOT IN (SELECT Id FROM RebateAccounts)
If any row shows up then that row has an account id that does not belong to any account. That's where your conflict is.
Hope it helps.

How to create connection between two tables in SQL Server 2008?

I have database that has Student table with information about each student in the system. Each record in that table has unique identifier that was created with NEWID() in SQL 2008. Then I have three other tables that use the same ID to link the student and the record. I'm wondering if I need to set any kind of property that will link these tables/records. Here is example of my Student table:
st_id -> Auto increment id
st_studentGUID -> Primary key
st_firstName
st_lastName
st_dob
st_gender
st_uid
st_udt
st_utime
And here is example of my other three tables:
Table 1 Table 2 Table 3
tb1_id -> auto increment tb2_id -> auto increment tb3_id -> auto increment
tb1_studentGUID tb2_studentGUID tb3_studentGUID
I have tried to create foreign key for each Table 1,2 and 3 on studentGUID but I got an error:
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_Table1_Student". The conflict occurred in database "testDB", table "Student", column 'st_studentGUID'.
After I have done some research seems like this error occurred because Table 1 doesn't have all st_studentGUID. This make sense because student record might exist in Table 3 but not in Table 1. I'm wondering if there is any other sort of relation that I can set between the tables? Should I maybe use the Indexes on studentGUID fields? This is the reason why I'm asking this, in one of my update queries I use auto incremented id in where clause and for some reason I received an error that looks like this:
ErrorCode 1205
Message [Macromedia][SQLServer JDBC Driver][SQLServer]Transaction (Process ID 111) was deadlocked on lock | communication buffer resources with another process and has been chosen as the deadlock victim. Rerun the transaction.
SQLState 40001
and error was pointing to the line that is end of the update query that looks like this:
<cfquery name="updateTable1" datasource="testDB">
UPDATE Table1
SET
tb1_testdt = <cfqueryparam value="#FORM.frm_testdt#" cfsqltype="cf_sql_date" maxlength="10" null="#yesNoFormat(!len(FORM.frmhs_testdtgr))#" />
FROM Table1 AS Table
LEFT OUTER JOIN studentLocked AS Locked
ON Locked.lk_studentGUID = Table.tb1_studentGUID
WHERE tb1_id = <cfqueryparam value="#FORM.frm_id#" cfsqltype="cf_sql_integer" />
AND lk_active = '1'
AND lk_staffID = <cfqueryparam value="#trim(appStaff)#" cfsqltype="cf_sql_char" maxlength="10" />
</cfquery>
Query above is checking if studentGUID exists in Lock table, reason why I'm doing this is because we do not want two different users updating the same record at the same time. Query updates single record and should be pretty fast. I'm confused whit the error message above deadlock victim. Is there something in my database design that is off or my update query is causing this error? I couldn't find anything on the web that could help me fix this issue. if anyone has experience with this kind of problem please let me know.
If all StudentGUIDs exist in the Student table, then the correct design is to have the StudentGUID in Table1, Table2 and Table3 be a Foreign Key to the Student table.
Now that you've sorted out your foreign key issue with the missing record from Student, try setting up your FKs on all of your tables, then re-try your update query.
If the deadlock issue persists and is reproducible, submit a new question for that, including the schema for the table you're updating and the values you're trying to pass.
Here's a script that demonstrates you can create the relationships you described provided all the keys are present in the students table:
CREATE TABLE students (st_id AS NEWID(),
st_studentGUID UNIQUEIDENTIFIER PRIMARY KEY)
INSERT INTO students (st_studentGUID) VALUES ('3B9F59DD-BF0A-4A09-BF4E-A396E2978B24')
INSERT INTO students (st_studentGUID) VALUES ('7CC5FF67-DAB8-426A-B9F7-E9F041718B6B')
INSERT INTO students (st_studentGUID) VALUES ('84B80D3E-44C4-4291-857D-B6CA6552369D')
CREATE TABLE t1 (tb1_id AS NEWID(), tb1_studentGUID UNIQUEIDENTIFIER)
ALTER TABLE t1
ADD CONSTRAINT FK_t1_tbl_studentGUID FOREIGN KEY (tb1_studentGUID) REFERENCES students(st_studentGUID)
INSERT INTO t1 (tb1_studentGUID) VALUES ('3B9F59DD-BF0A-4A09-BF4E-A396E2978B24')
CREATE TABLE t2 (tb2_id AS NEWID(), tb2_studentGUID UNIQUEIDENTIFIER)
ALTER TABLE t2
ADD CONSTRAINT FK_t2_tbl_studentGUID FOREIGN KEY (tb2_studentGUID) REFERENCES students(st_studentGUID)
INSERT INTO t2 (tb2_studentGUID) VALUES ('7CC5FF67-DAB8-426A-B9F7-E9F041718B6B')
CREATE TABLE t3 (tb3_id AS NEWID(), tb3_studentGUID UNIQUEIDENTIFIER)
ALTER TABLE t3
ADD CONSTRAINT FK_t3_tbl_studentGUID FOREIGN KEY (tb3_studentGUID) REFERENCES students(st_studentGUID)
INSERT INTO t3 (tb3_studentGUID) VALUES ('84B80D3E-44C4-4291-857D-B6CA6552369D')
Now create a 4th table, add a UUID that isn't in the students table, and try to create the foreign key constraint:
CREATE TABLE t4 (tb4_id AS NEWID(), tb4_studentGUID UNIQUEIDENTIFIER)
INSERT INTO t4 (tb4_studentGUID) VALUES ('897925F1-BE92-44EB-82C3-88E1C33C7792')
ALTER TABLE t4
ADD CONSTRAINT FK_t4_tbl_studentGUID FOREIGN KEY (tb4_studentGUID) REFERENCES students(st_studentGUID)
Which reproduces your error message:
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_t4_tbl_studentGUID". The conflict occurred in database "IconERP", table "dbo.students", column 'st_studentGUID'.

SQL Server : copy table data with FK Constraint

I import data into a SQL Server database from Excel.
The data is inserted into a tmptable which has no primary key defined.
tmptable:
course, trainer, jockey, horse, won, pos, date
I want to copy the data from tmptable into another table mastertable which has a primary key column.
mastertable:
coursefk, trainerfk, jockeyfk, horsefk, won, pos, date.
The columns suffixed 'fk' refer to individual other tables.
My hope is that during the insert into mastertable, the script would take the value of course column from tmptable and refer to the table Courses for the appropriate value to be placed into mastertable. The primary and foreign key relationships between the tables have been created, but I cannot create a script that will achieve what I want.
Can anyone please help.
You can join tmptable with other foreign key tables.
Something like this.
INSERT INTO mastertable(coursefk, trainerfk, jockeyfk, horsefk, won, pos, date)
SELECT mastercourse.coursefk, mastertrainer.trainerfk, masterjockey.jockeyfk, masterhorse.horsefk, won, pos, date
FROM tmptable
LEFT JOIN mastercourse ON mastercourse.course = tmptable.course
LEFT JOIN mastertrainer ON mastertrainer.trainer = tmptable.trainer
LEFT JOIN masterjockey ON masterjockey.jockey = tmptable.jockey
LEFT JOIN masterhorse ON masterhorse.horse = tmptable.horse
Note: Since I do not know structure of other FK tables, Please replace and use appropriate table and column names.

Foreign Key fails to create

I want a foreign key between 2 tables , so i try it like i always do. Now the issue i'm having is he fails to create , and by the looks of it it fails to create because there is already a key but there isnt.
- Unable to create relationship
'FK_tbl_Paramed_RegistratieBehandelingen_Users'.
The ALTER TABLE statement conflicted with the
FOREIGN KEY constraint "FK_tbl_Paramed_RegistratieBehandelingen_Users".
The conflict occurred in database "Nestor_Server",
table "dbo.Users", column 'UserID'.
Ive checked if they have the same type , they do(bigint) so don't get why he won't create it
It is possible that you have records in RegistratieBehandelingen(Not sure about the table name) which is not present in Users Table.
select * from RegistratieBehandelingen a where UserID IS NULL or
not exists (select 1 from Users b where b.UserID= a.UserID)
This means that you have child data with no matching parent ID.
Run the following to see if you get any results:
SELECT *
FROM tbl_Paramed_RegistratieBehandelingen r
LEFT JOIN Users u on r.UserID = u.UserID
WHERE u.UserID IS NULL
(changing table and column names where appropriate)
If you get any results then it should show which records contains UserIDs that don't match to Users.
After the above query, you may want to delete non existing UserId from table tbl_Paramed_RegistratieBehandelingen or insert them in table Users .

Linking ID from one table to data in another table

I have an assignment where I am to create two tables within a database. The tables looks like this;
ContactPerson (ID, Forename, Surname, Email, PhoneNumber)
Company (ID, CompanyName)
Now my problem is that I have to link a ContactPerson to a specific company, but I can't have them in the same table.
I understand that I can use the join statement to show both tables in one query but I need the database to know which person is linked to which company when I implement this databse into my asp.net project.
How do I do this?
You did say "specific" company so I'm assuming you have one company per person.
Put a column in the user table called CompanyID...
ALTER TABLE ContactPerson
ADD CompanyID int
(assuming your ids are ints)
and then create the following foreign key:
ALTER TABLE [dbo].ContactPerson
ADD CONSTRAINT [FK_ContactPerson_Company]
FOREIGN KEY (CompanyID)
REFERENCES Company (ID)
Shark is correct if you want a many to many relationship.
To get all people in a company:
SELECT
*
FROM
ContactPerson
WHERE
CompanyID = x
You don't HAVE to apply the foreign key constraint, but if you don't, you can accidentally put invalid data in. All a "Constraint" does is enforce a rule for you, in other words "making sure sql knows which people are in which company" as your question suggests you need to do.
The above query would work without the Foreign key constraint, but then your database doesn't "know" about the relationship.
..and if I try and insert a person with a companyid that doesn't exist, SQL will throw an error (this is a good thing).
Since this is a one-to-many relationship, I would typically put that data into the ContactPerson table. But because you explicitly say you cannot, then just create a join table:
create table ContactPersonCompany
(
ContactPersonID int not null foreign key references ContactPerson(ID),
CompanyID int not null foreign key references Company(ID)
)
Now you have a relationship between ContactPerson and Company.
Example: select all people from a particular company
select
cp.Surname,
cp.Forename
from ContactPerson cp
inner join ContactPersonCompany cpc
on cp.ID = cpc.ContactPersonID
inner join Company c
on cpc.CompanyID = c.ID
where c.CompanyName = 'Some Company'

Resources