I am looking for a solution for a custom unit conversion in SQL, the database my company used is Microsoft SQL server, I need to write a SQL to return a conversion factor based
I think a recursive table that finds a path from your desired from unit and to the desired to unit would work best. Something like this (This assumes that if there is a path a-->b-->c there is also a path c-->b-->a in the database. If not it could be modified to search both directions).
select 1001 as itemID
,5000 as vendorID
,10 as fromUnit
,500 as toUnit
,cast(1000 as float) as fromQuantity
,cast(1 as float) as toQuantity
into #conversionTable
union
select 1001
,5000
,500
,305
,1
,5
union
select 1001
,5000
,305
,500
,5
,1
union
select 1001
,5000
,500
,10
,1
,1000
declare @fromUnit int
,@toUnit int
,@input int
set @fromUnit = 305 --box
set @toUnit = 10 --gram
set @input = 10
;with recursiveTable as
(
select 0 as LevelNum
,ct.fromUnit
,ct.toUnit
,ct.toQuantity / ct.fromQuantity as multiplicationFactor
from #conversionTable ct
where ct.fromUnit = @fromUnit
union all
select LevelNum + 1
,rt.fromUnit
,ct.toUnit
,rt.multiplicationFactor * (ct.toQuantity / ct.fromQuantity)
from #conversionTable ct
inner join recursiveTable rt on rt.toUnit = ct.fromUnit
)
select @input * r.multiplicationFactor
from
(
select top 1 * from recursiveTable
where (fromUnit = @fromUnit
and toUnit = @toUnit)
) r