I have these two tables:
CREATE TABLE Student
(
Id uniqueidentifier PRIMARY KEY DEFAULT NEWID(),
UserId uniqueidentifier REFERENCES [User] (Id), --associated user
FirstName nvarchar(50) NOT NULL,
DisplayName nvarchar(30),
LastName nvarchar(30) NOT NULL,
Gender int,
BirthDate date,
);
CREATE TABLE Teacher
(
Id uniqueidentifier NOT NULL PRIMARY KEY DEFAULT NEWID(),
FirstName nvarchar(50),
LastName nvarchar(50),
DisplayName nvarchar(50),
Abbreviation nvarchar(10) NOT NULL UNIQUE,
UserId uniqueidentifier REFERENCES [User] (Id), --associated user
);
In order to ensure that a User
can only be associated two one person, I would like to create a view Person
that displays all the rows from Teacher
and Student
, with all their columns, and a bit
column that indicates whether it is a student or teacher. I would then add a UNIQUE INDEX
on Person
that ensures uniqueness in its UserId
column.
I tried many things, like joins, APPLY
, UNION
; but I can't get it to work.
This does not work because duplicate column names:
CREATE OR ALTER VIEW VI_Person
AS
SELECT *
FROM Student, Teacher
Does not work because tables are not identical:
CREATE OR ALTER VIEW VI_Person
AS
SELECT s.FirstName, s.UserId
FROM Student s
UNION ALL
SELECT * FROM Teacher
Only displays student columns:
CREATE OR ALTER VIEW VI_Person
AS
SELECT s.FirstName, s.UserId
FROM Student s
FULL JOIN Teacher t ON t.FirstName = s.FirstName
AND t.UserId = s.UserId
Displays FirstName
, LastName
, UserId
. bit indicating type and other fields still missing
CREATE OR ALTER VIEW VI_Person
AS
SELECT s.FirstName, s.LastName, s.UserId
FROM Student s
UNION ALL
SELECT t.FirstName, t.LastName, t.UserId
FROM Teacher t