Sunday, February 19, 2012

database: mssql

I am conducting a database design and I managed to reach the 3rd normal form. My question is, if i change my primary key, for example '0001' to '0002', is it possible to propagate the change/update to the other linked table.
if you require more info, please let me know. Thank you in advance.If I understand correctly then yes -
If you have 2 tables:
Customer - With Field CustomerId
And Order with Field OrderId and CustomerId
And you want to change the CustomerId Field then you would do the following:
SET IDENTITY_INSERT [dbo].[Customer] ON
GO
ALTER TABLE [dbo].[Order] NOCHECK CONSTRAINT ALL
GO
-- Add a column to hold the old ID
ALTER TABLE CUSTOMER WITH CHECK ADD OldID INT
GO
UPDATE CUSTOMER SET OldID = CustomerId
GO
-- Add Code to Change CustomerId Here
UPDATE O
Set O.CustomerId = C.CustomerId
From Order O
INNER JOIN Customer C
ON O.CustomerId = C.OldId
GO
SET IDENTITY_INSERT [dbo].[Customer] OFF
GO
ALTER TABLE [dbo].[Order] CHECK CONSTRAINT ALL
GO
|||

You can use declarative referential integrity and cascade updates popagate the changes. Sample code below.

Regards

set nocount on
go

use tempdb
go

create table parent(p int constraint p_pk primary key)
go

create table child(
c int constraint c_pk primary key
, p int constraint c_fk foreign key references parent(p) on update cascade
)
go

insert into parent values (1)
go
insert into child values (1,1)
go

update parent set p = 2 where p = 1
go

select * from child
go

drop table child
go
drop table parent
go

|||Hi,
In addition to that. If your using sql2k you could just create a diagram and link the tables that you want in Enterprise Manager...
cheers,
Paul June A. Domag