I am having trouble updating a column that is found in multiple tables with this script. I would like to use this to prevent duplicate UnitId's throughout the DB. I keep getting this error messages:
The UPDATE statement conflicted with the FOREIGN KEY constraint "Ppt${FA40D62B-B45A-46B2-A5C5-24BA8E5B6318}". The conflict occurred in database "MQS-demo", table "dbo.Unit", column 'UnitID'.
and
The DELETE statement conflicted with the REFERENCE constraint "Ppt${FA40D62B-B45A-46B2-A5C5-24BA8E5B6318}". The conflict occurred in database "MQS-demo", table "dbo.Ppt", column 'UnitID'.
Here is the query
declare @oldUnitID as int=0;
declare @newUnitID as int=0;
declare @temp as TABLE
(
bincode nvarchar(200),
cnt int
)
insert into @temp
select bincode, Count(*)
from unit
group by bincode -- HAVING count(*)=2
--select * from @temp
WHILE (SELECT Count(*) from @temp) > 0 BEGIN
DECLARE @bincodetodedup as nvarchar(200);
select top(1) @bincodetodedup = bcode
from @temp;
DECLARE @unitstodedup as TABLE
(
unitid int,
num int
)
insert into @unitstodedup
select distinct UnitID, ROW_NUMBER() OVER(ORDER BY unitid) as num
from unit
where bincode = @bincodetodedup
order by unitid
WHILE (SELECT Count(*) from @unitstodedup) > 0 BEGIN
SELECT TOP(1) @oldUnitID = Unitid
from @unitstodedup
where num = 1
SELECT TOP(1) @newUnitID = Unitid
from @unitstodedup
where num > 1
update Compatibility
set UnitID = @newUnitID
where UnitID = @oldUnitID
update PriceList
set UnitID = @newUnitID
where UnitID = @oldUnitID
update Project
set UnitID = @newUnitID
where UnitID = @oldUnitID
update ProjectNum
set UnitID = @newUnitID
where UnitID = @oldUnitID
update Rate
set UnitID = @newUnitID
where UnitID = @oldUnitID
update Resolve
set UnitID = @newUnitID
where UnitID = @oldUnitID
update Services
set UnitID = @newUnitID
where UnitID = @oldUnitID
update TrainingDate
set UnitID = @newUnitID
where UnitID = @oldUnitID
update Form
set UnitID = @newUnitID
where UnitID = @oldUnitID
update Ppt
set UnitID = @newUnitID
where UnitID = @oldUnitID
--update Unit set UnitID=@newUnitID where UnitID=@oldUnitID
update Manager
set UnitID = @newUnitID
where UnitID = @oldUnitID
END
DELETE FROM unit
where unitid = @oldUnitID
DELETE TOP(1) from @unitstodedup
DELETE TOP(1) from @temp
END
Why do not you do the delete at the end with the variables you are assigning?
DELETE from @temp where bcode = @bincodetodedup
DELETE from @unitstodedup where num=1
DELETE from @unitstodedup where num>1