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.
A Foreign Key is used for referential integrity, to make sure that a value exists in another table. The Foreign key needs to reference the primary key in another table. If you want to have a foreign key that is also unique, you could make a FK constraint and add a unique index/constraint to that same field.
Yes, it can.
Yes. You would do this for instance if you wanted to enforce that all employees are users, and some users can be employees.
Yes of course you can have PK and FK at the same time. PK & FK at the same time means that you want to index on the primary key, but at the same time you want to restrict the values of the PK based on values that exist in another attribute.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With