Question

Suppose I have a supertype table with many subtype tables. I'm interested in making them disjoint subtypes in that the supertype table only points to one of the possible subtype tables per row. On the web I came across descriptions of the subtype discriminator which is a new column put into the supertype table which is a small code (usually a character) that identifies which subtype the row belongs to.

I couldn't find any actual examples of this in practice. If I were working in C# am I suppose to query the table's subtype discriminator column, then test against some key->value list ([sub type discriminator]->subtype_table_name) to create the right SQL to join the correct table?

Or, is there some view/SQL query syntax already in SQL Server for this purpose?

Basically, I'm wondering at which level I have to actually perform the logic to make the discriminator useful.

Was it helpful?

Solution

Your query would consist of the following:

select *
from Root
left join Child1 on ... AND Root.Discriminator = 'C1'
left join Child2 on ... AND Root.Discriminator = 'C2'

And hopefully SQL Server evaluates the addition join predicate before starting to read from the child tables. This is not guaranteed though.

The nice thing about this pattern is that it generalized to arbitrary queries, even for multiple rows with different subtypes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top