sql server - How does T-SQL implicit conversion / overload resolution work? -
i've been toying around t-sql in attempt understand implicit conversion , overload resolution rules, somehow seems work bit strange...
context:
- data type conversion: https://msdn.microsoft.com/en-us/library/ms191530.aspx
- data type precedence: https://msdn.microsoft.com/en-us/library/ms190309.aspx
- abs: https://msdn.microsoft.com/en-us/library/ms189800.aspx
basically latter tells abs
work on int, float, decimal, etc. let's see how works:
declare @foo2 sql_variant; set @foo2 = abs(4); select sql_variant_property(@foo2, 'basetype') -- result: int. ok, apparently have int overload. expected. declare @foo2 sql_variant; set @foo2 = abs(cast(4.0 float)); select sql_variant_property(@foo2, 'basetype') -- result: float. ok, apparently have float overload. expected.
now, according implicit type conversion table, allowed implicitly convert stuff. we're going check converting varbinary int, should happen according type precedence rules:
declare @foo varbinary(4); set @foo = cast(4 varbinary(4)); select @foo + 2; -- result: int. ok, expected.
from result expect following work well:
declare @foo varbinary(4); set @foo = cast(4 varbinary(4)); select abs(@foo); -- result: error: operand type clash: varbinary incompatible float
stuff don't understand here (the question):
- why implicit conversion pick 'float' overload of 'abs'? random overload? or perhaps overload that's highest in precedence list (which happens 'float')?
- why isn't implicit conversion applied varbinary -> int? after all, it's valid conversion.
from msdn abs:
arguments numeric_expression expression of exact numeric or approximate numeric data type category.
i guess calling abs( varbinary ) try convert varbinary exact numeric or approximate numeric data type.
float @ top of data type precedence these types there problem guess.
update logic
declare @foo varbinary(4);
declare varbinary variable.
set @foo = cast( 4 varbinary(4));
set variable value performing explicit cast int varbinary doable.
select sql_variant_property(@foo, 'basetype')
this shows variable of type varbinary.
select abs(@foo);
try run abs on varbinary. error message clear:
operand type clash: varbinary incompatible float
so guess abs trying implicit convert varbinary first of data type precedence exact numeric or approximate numeric data types float.
this conversion fails according cast , convert
chart.
Comments
Post a Comment