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

前端 未结 4 1815
日久生厌
日久生厌 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 03:59

    If you change the type to sql_variant, you will have to use the IDataRecord.GetValue method. It will preserve the type all the way.

    So in .NET it will allow you to have this kind of code:

    // read an object of SQL underlying data type 'int' stored in an sql_variant column
    object o = myReader.GetValue(); // o.GetType() will be System.Int32
    
    // read an object of SQL underlying data type '(n)varchar' or '(n)char' stored in an sql_variant column
    object o = myReader.GetValue(); // o.GetType() will be System.String
    
    // read an object of SQL underlying data type 'datetime' stored in an sql_variant column
    object o = myReader.GetValue(); // o.GetType() will be System.DateTime
    
    etc...
    

    Of course, it supposes you do the same when saving. Just set SqlParameter.Value to the opaque value, don't use the DbType.

    EAV with various (standard) types as value is the one case where I personally think sql_variant is interesting.

    Of course "SQLServer-focused guys" (read: DBAs) don't like it at all :-) On the SQL Server side, sql_variant is not very practical to use (as noted in the comments), but if you keep it as an opaque "thing" and don't have to use it in SQL procedure code, I think it's ok. So, it's more an advantage on the .NET/OO programming side.

提交回复
热议问题