Discussion:
Many to Many relationship with GUID and INT
(too old to reply)
Shapper
2012-12-10 01:08:22 UTC
Permalink
Hello,

I have 3 tables: Packs, Posts and PostPacks so I have a Many to Many relation:

create table dbo.Packs
(
Id int identity not null
constraint Packs_Id_PK primary key clustered (Id)
);
create table dbo.Posts
(
Id int identity not null
constraint Posts_Id_PK primary key clustered (Id)
);
create table dbo.PostsPacks
(
PostId int not null,
PackId int not null,
constraint PostsPacks_PostId_PackId_PK primary key clustered (PostId, PackId)
);

How can I make the Packs ID PK a Guid but keeping the Posts ID PK as an Int. Is this possible?

Thank You,

Miguel
rpresser
2012-12-10 03:04:54 UTC
Permalink
Post by Shapper
How can I make the Packs ID PK a Guid but keeping the Posts ID PK as an Int. Is this possible?
ALTER TABLE Packs ADD ID2 UNIQUEIDENTIFIER NULL
GO
UPDATE Packs SET ID2=NEWID()
GO
ALTER TABLE Packs ALTER COLUMN ID2 UNIQUEIDENTIFIER NOT NULL
GO
ALTER TABLE PostsPacks ADD PackID2 UNIQUEIDENTIFIER NULL
GO
UPDATE PostsPacks
SET PackID2 = Packs.ID2
FROM PostsPacks
INNER JOIN Packs ON PostsPacks.ID=Packs.ID
GO
ALTER TABLE PostsPacks ALTER COLUMN PackID2 UNIQUEIDENTIFIER NOT NULL
GO
ALTER TABLE PostsPacks DROP CONSTRAINT PostsPacks_PostID_PackID_PK
ALTER TABLE Packs DROP CONSTRAINT Packs_Id_PK
GO
ALTER TABLE Packs DROP COLUMN ID
GO
ALTER TABLE Packs ADD CONSTRAINT Packs_ID2_PK PRIMARY KEY CLUSTERED (ID2)
GO
ALTER TABLE PostsPacks DROP COLUMN PacksID
GO
ALTER TABLE PostsPacks ADD CONSTRAINT PostsPacks_PostID_PackID2_PK PRIMARY KEY CLUSTERED (PostID, PackID2)
ALTER TABLE PostsPacks ADD CONSTRAINT PostsPacks_PostID_FK FOREIGN KEY (PostID) REFERENCES Posts (ID)
ALTER TABLE PostsPacks ADD CONSTRAINT PostsPacks_PackID2_FK FOREIGN KEY (PackID2) REFERENCES Packs (ID2)
GO

Continue reading on narkive:
Loading...