how to update 2 linked tables in sql server 2016 - sql

I have two tables, there is a foreign key relationship defined between the two tables. If I attempt to update the second table, I receive the following error:
The UPDATE statement conflicted with the REFERENCE constraint
"FK__T2__owner__48CFD27E". The conflict occurred in database "MY_DB",
table "dbo.T2", column 'T2.colomn1'.
How can I update the column in the second table that references the first table?

It probably isn't necessary to update both tables, in fact there's a good chance you don't want to. Based on your comment, I'm assuming you have a postal_code table? It seems less likely that you would have a foreign key on address but I suppose it's possible. The reason you don't want to update both is that other rows in your post_office table may use the same postal_code.
Simply add your new postal code to the postal_code table. (I've guessed at the name.)
INSERT INTO postal_code
VALUES ('1234567891')
Then do your update.
UPDATE post_office
SET address = 'Tehran p 190', postal_code = '1234567891'
WHERE social_id = '0020366760'
If you don't think any other post offices use the old postal_code you can always clean up after yourself.
DELETE FROM postal_code
WHERE id = 'someid'

When you are trying to update the entry in table T1, make sure that the value with which we are updating in a column that has foreign key reference, you update with values that are there in the referenced foreign keys table(Unless the column is nullable).
The value with which you are trying to update T2,column1 should be already present in T1.column2.

Related

SSMS will not let me create a PK FK relationship

First, let me say that I am a newbie and that I have read many other posts with the same problem. I have a table called "AllPeople", and in that table I have an integer column called "Ethnicity", which I want to be a foreign key that points at a record in my "RefEthnicities" table. I keep getting the following message:
Unable to create relationship 'FK_AllPeople_RefEthnicities'.
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_AllPeople_RefEthnicities". The conflict occurred in database "MVC-Cemeteries-Dev", table "dbo.RefEthnicities", column 'ID'.
I set up the relationship in the "AllPeople" table and told it that the primary key is the ID column in the "RefEthnicities" and the foreign key is the "Ethnicity" column in the "AllPeople" table. What am I doing wrong? My RefEthnicities table is new; no data in it.
While in design mode I set the ID field in the "RefEthnicities" table set as primary key by clicking the small box to the left of the name "ID", and down below in this same window in the column properties tab, I told it to set the index specification to "yes".
I am sure it is something simple that I am doing but I can't figure it out.
Error Message
Constraint Folder
Setting Up PK FK Link
As my limited information in the question, there 2 possibilities
NULL or Blank '' value for column Ethnicity in table AllPeople
SELECT A.Ethnicity,A.*
FROM dbo.AllPeople A
WHERE ISNULL(A.Ethnicity,'')=''
Some values column Ethnicity in table AllPeople don't have parent in column ID in table RefEthnicities
SELECT A.Ethnicity,R.ID, *
FROM dbo.AllPeople A
LEFT JOIN RefEthnicities R
ON A.Ethnicity=R.ID
WHERE R.ID IS NULL
If you get any rows in two queries, then you need to fix data in column Ethnicity in table AllPeople.
Read
Ok this still makes no sense. If I create two brand new tables with the following:
table1
ID primary key int not nullable
value varchar
table2FK
table2
ID primary key int not nullable
value varchar
and in table1 I make a relationship between table2FK and Table2.ID, it works perfect with no data saved in the tables. If I use the exact same process in my AllPeople and RefEthnicicties tables, I get the error. This makes no sense. What am I missing?
adam
That fixed it. many thanks. I had a record in my AllPeople table for ethnicity that had a value of 0. Since I didn't have a record in the RefEthnicity Table with an ID of 0, it was telling me that I couldn't do this.
adam

Error Adding Multiple FK Relationship in SQL Server 2008

Consider we have two tables ProductType and ProductSizeGroup as below
ProductType
Id
Name
MaleSizeGroupId
FemaleSizeGroupId
ChildSizeGroupId
ProductSizeGroup
Id
Name
Each of MaleSizeGroupId, FemaleSizeGroupId and ChildSizeGroupId fields should be FKs to ProductSizeGroup.Id.
I add one using the following statement:
ALTER TABLE [dbo].[ProductType]
WITH CHECK ADD CONSTRAINT
[FK_ProductType_ProductSizeGroup_Male] FOREIGN KEY([MaleGroupId])
REFERENCES [dbo].[ProductSizeGroup] ([Id])
This works fine. I try to add the next using
ALTER TABLE [dbo].[ProductType]
WITH CHECK ADD CONSTRAINT
[FK_ProductType_ProductSizeGroup_Female] FOREIGN KEY([FemaleGroupId])
REFERENCES [dbo].[ProductSizeGroup] ([Id])
But I get the error:
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_ProductType_ProductSizeGroup_Female". The conflict
occurred in database "dbname", table "dbo.ProductSizeGroup", column
'Id'.
So there is conflict.. but what conflict? What should I be looking for?
That just means: there are rows in your table ProductType that have values in the FemaleGroupId column which do not exist in the referenced table (ProductSizeGroup).
It's not a problem per se - you can totally have multiple columns going from one table to another.
The problem is with the existing data - you have data in there that doesn't live up to that FK constraint. Fix that data and you should be fine.
To find those offending rows, use a query like this:
SELECT *
FROM [dbo].[ProductType]
WHERE FemaleGroupId NOT IN (SELECT DISTINCT Id FROM [dbo].[ProductSizeGroup])
That will list all offending rows - update their attribute and get going again!

How to update 2 columns in 2 tables that have foreign key

I know the question of how to update multiple tables in SQL has been asked before and the common answer seems to be do them separately in a transaction.
However, the 2 columns I need to update have a foreign key so cannot be updated separately.
e.g.
Table1.a is a foreign key to Table2.a
One of the entries in the tables is wrong, e.g. both columns are 'xxx' and should be 'yyy'
How do I update Table1.a and Table2.a to be 'yyy'?
I know I could temp remove the key and replace but surely there's another way.
Thanks
You can't do the update simultaneously, however you can force SQL to do the update. You need to make sure your foreign keys have the referential triggered action ON UPDATE CASCADE
e.g.
ALTER TABLE YourTable
ADD CONSTRAINT FK_YourForeignKey
FOREIGN KEY (YourForeignKeyColumn)
REFERENCES YourPrimaryTable (YourPrimaryKeyColumn) ON UPDATE CASCADE
Not being a fan of on update cascade, I would suggest a different route.
First you do not update the Parent table, you add a new record with the value you want (and the same data as the other record for all other fields). Then you have no difficulty updating the child tables to use this value instead of that value. Further you now have the ability to to do the work in batches to avoid locking the system up while the change promulgates through it. Once all the child tables have been updated, you can delete the original bad record.
my answer is based on the following link: http://msdn.microsoft.com/en-us/library/ms174123%28v=SQL.90%29.aspx
You need to make sure that your table_constraint will be defined as ON UPDATE CASCADE
CREATE TABLE works_on1
(emp_no INTEGER NOT NULL,
project_no CHAR(4) NOT NULL,
job CHAR (15) NULL,
enter_date DATETIME NULL,
CONSTRAINT prim_works1 PRIMARY KEY(emp_no, project_no),
CONSTRAINT foreign1_works1 FOREIGN KEY(emp_no) REFERENCES employee(emp_no) ON DELETE CASCADE,
CONSTRAINT foreign2_works1 FOREIGN KEY(project_no) REFERENCES project(project_no) ON UPDATE CASCADE)
and then when you will change the value of your primary key
see the following quote:
For ON DELETE or ON UPDATE, if the CASCADE option is specified, the
row is updated in the referencing table if the corresponding
referenced row is updated in the parent table. If NO ACTION is
specified, SQL Server Compact Edition returns an error, and the update
action on the referenced row in the parent table is rolled back.
For example, you might have two tables, A and B, in a database. Table
A has a referential relationship with table B: the A.ItemID foreign
key references the B.ItemID primary key.
If an UPDATE statement is executed on a row in table B and an ON
UPDATE CASCADE action is specified for A.ItemID, SQL Server Compact
Edition checks for one or more dependent rows in table A. If any
exist, the dependent rows in table A are updated, as is the row
referenced in table B.
Alternatively, if NO ACTION is specified, SQL Server Compact Edition
returns an error and rolls back the update action on the referenced
row in table B when there is at least one row in table A that
references it.

ON UPDATE CASCADE with two columns in a single table in SQL Server [duplicate]

I have a database table called Lesson:
columns: [LessonID, LessonNumber, Description] ...plus some other columns
I have another table called Lesson_ScoreBasedSelection:
columns: [LessonID,NextLessonID_1,NextLessonID_2,NextLessonID_3]
When a lesson is completed, its LessonID is looked up in the Lesson_ScoreBasedSelection table to get the three possible next lessons, each of which are associated with a particular range of scores. If the score was 0-33, the LessonID stored in NextLessonID_1 would be used. If the score was 34-66, the LessonID stored in NextLessonID_2 would be used, and so on.
I want to constrain all the columns in the Lesson_ScoreBasedSelection table with foreign keys referencing the LessonID column in the lesson table, since every value in the Lesson_ScoreBasedSelection table must have an entry in the LessonID column of the Lesson table. I also want cascade updates turned on, so that if a LessonID changes in the Lesson table, all references to it in the Lesson_ScoreBasedSelection table get updated.
This particular cascade update seems like a very straightforward, one-way update, but when I try to apply a foreign key constraint to each field in the Lesson_ScoreBasedSelection table referencing the LessonID field in the Lesson table, I get the error:
Introducing FOREIGN KEY constraint 'c_name' on table 'Lesson_ScoreBasedSelection' may cause cycles or multiple cascade paths.
Can anyone explain why I'm getting this error or how I can achieve the constraints and cascading updating I described?
You can't have more than one cascading RI link to a single table in any given linked table. Microsoft explains this:
You receive this error message because
in SQL Server, a table cannot appear
more than one time in a list of all
the cascading referential actions that
are started by either a DELETE or an
UPDATE statement. For example, the
tree of cascading referential actions
must only have one path to a
particular table on the cascading
referential actions tree.
Given the SQL Server constraint on this, why don't you solve this problem by creating a table with SelectionID (PK), LessonID, Next_LessonID, QualifyingScore as the columns. Use a constraint to ensure LessonID and QualifyingScore are unique.
In the QualifyingScore column, I'd use a tinyint, and make it 0, 1, or 2. That, or you could do a QualifyingMinScore and QualifyingMaxScore column so you could say,
SELECT * FROM NextLesson
WHERE LessonID = #MyLesson
AND QualifyingMinScore <= #MyScore
AND #MyScore <= QualifyingMaxScore
Cheers,
Eric

Update primary key from table in another database

I have two identical tables in two different databases with the same data but they have different primary keys, I need to update these so they have the same key, so what I did was making sure that none of the tables had any key in common and that there were no duplicates
UPDATE db1.dbo.Table
SET db1.dbo.Table.pcol = rightPcol.pcol
FROM db1.dbo.Table
JOIN db2.dbo.Table AS rightPcol ON db1.dbo.Table.2ndIdent = db2.dbo.Table.2ndIdent
this however results in "Violation of PRIMARY KEY Constraint. Cannot insert duplicate key in object"
when adding a where clause to not update any db1 pcol value that existed in the db2 pcol it didn't update anything at all, it does look like it tries to update with the primary key in db1 instead of db2.
any and all help is greatly appreciated!
//fixed minor spelling error :)
To be honest there isn't much to say - the error message pretty much describes what is it wrong.
You are trying to update a PK Column to a value that already exists.
I would double check to make sure that
by joining on 2ndIdent you are not creating any duplicates.
there really aren't any duplicates in the tables on DB1 and
DB2
Your SQL looks fine so it must be an issue with the data.
To check for duplicates you could use something like this:
Select 2ndIndent
From Table
Group By 2ndIdent
Having Count(2ndIndent) > 1
The "pcol" is the primary key column?
You get "Violation of primary key constraint" when the primary key from "rightPcol" is duplicate with any row in table in "db1". You should select duplicatetion from the two tables and resolve the conflict (how it reselove depends on others thing, which you didn't specified).
So the first you should select the duplications:
SELECT T1.pcol
FROM db1.dbo.Table.pcol AS T1
INNER JOIN db2.dbo.Table.pcol AS T2
ON T1.pcol = T2.pcol