Search code examples
database-designarchitecturetypesentity-attribute-value

Best way to store muti-type field


Let's say we have a field that can be in more than one type, for instance: string or date or XML datatypes.

Now we have two methods to store this in a database

1- using a string typed field + field defining type: losing "type-aware" sorting capabilities, needs casting

2- separate tables (StringValues,DateValues,Decimal,XML ...etc):a foreign key pointing to a value + field defining type : somehow complicated, performance

the second method may have an extra advantage if only unique values were stored: it will work as an index.

do you have something in mind ?


Note1: Preferably, consider project based on MS SQL Server 2008 and Linq2SQL


Note2: Maybe we will discuss how to implement EAV in another question, I'm asking about EAV in a relational storage.


Note3: Types can change, but not frequently


Solution

  • I'm not sure this is enough detail to answer the question well. If you are literally asking about the two type case, you might also consider a table with a column for each type and a discriminator. The "right" answer may depend on specifics such as number of distinct types to be supported, speed vs. space constraints, etc.

    Some might argue that the least expensive approach is the best one. Specifically, the approach that you believe will require the least cost to understand and maintain (often ~60% of TCO).

    With regard to all the advice about not doing this, I agree if possible. On the other hand, SharePoint is one example that shows it's not impossible. Good luck!