Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Would it be possible in SQL Server 2008 to have a table created with 2 columns that are at the same time primary and foreign keys? If yes, how would such a code look like? I've searched and came up with nothing.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
569 views
Welcome To Ask or Share your Answers For Others

1 Answer

Sure, no problem:

CREATE TABLE dbo.[User]
(
  Id int NOT NULL IDENTITY PRIMARY KEY,
  Name nvarchar(1024) NOT NULL
);

CREATE TABLE [Group] 
(
  Id int NOT NULL IDENTITY PRIMARY KEY,
  Name nvarchar(1024) NOT NULL
);

CREATE TABLE [UserToGroup]
(
  UserId int NOT NULL,
  GroupId int NOT NULL,
  PRIMARY KEY CLUSTERED ( UserId, GroupId ),
  FOREIGN KEY ( UserId ) REFERENCES [User] ( Id ) ON UPDATE  NO ACTION  ON DELETE  CASCADE,
  FOREIGN KEY ( GroupId ) REFERENCES [Group] ( Id ) ON UPDATE  NO ACTION  ON DELETE  CASCADE
);

This is quite commonly used to model many-to-many relations.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...