Are there any benefits to using sql_variant over varchar in SQL Server?

前端 未结 4 1796
日久生厌
日久生厌 2021-02-19 03:29

I currently have a database table setup as follows (EAV - business reasons are valid):

  • Id - int (PK)
  • Key - unique, varchar(15)
  • Value - varchar(10
4条回答
  •  我在风中等你
    2021-02-19 04:11

    I don't see that it has been mentioned yet, so I'll mention that a fairly common approach to this problem is a table like this:

    • Id - int (PK)
    • Key - unique, varchar(15)
    • ValueType - Integer (0 - String, 1 - Integer, 3 - Float) (optional)
    • StringValue - varchar(1000)
    • IntValue - Integer
    • FloatValue - Double

    Advantages:

    • Data is saved in its appropriate form (storing ints as strings wastes a lot of bits)
    • You can do fancy queries like WHERE left(key,5) = 'SHOES', and IntValue>5
    • The ValueType column is only useful you are using prefix/suffixes on your keys (to retrieve sets of keys) and the set could be of mixed type. i.e. WHERE left(key,4) = 'Size' and ValueType = 1

    Disadvantages:

    • Everywhere where you use this table you have to ensure that you/get/set the correct Value column
    • If you decide you need/want the ValueType column, you have to ensure that you get/set it correctly.

提交回复
热议问题