I'm pretty sure the answer is No, but I want to double check. If there is a way, you don't actually have to code it, a suggestion on a method might help. I've tried 1 big Select with sub query's, etc. but I can't figure out how to get it to pick the correct record.
The table has to join back itself to get inverse relationships. The code below is just a test sample.
Thank you
create function [dbo].[fnUOMFactor_Inline] (
@ItemID nvarchar(20)
, @FromUnit nvarchar(10)
, @ToUnit nvarchar(10)
)
returns numeric(28,12)
as
begin
declare @Factor numeric(28,12)
if @FromUnit = @ToUnit
set @Factor = 1
-- Simple 1-step
if @Factor is null
select @Factor = factor
from dbo.UnitConvertTest
WHere itemid = @ItemID
and fromunit = @FromUnit
and tounit = @ToUnit
-- Inverted 1-step
if @Factor is null
select @Factor = 1/factor
from dbo.UnitConvertTest
Where itemid = @ItemID
and fromunit = @ToUnit
and tounit = @FromUnit
if @Factor is null
select @Factor = uc1.factor * uc2.factor
from dbo.UnitConvertTest uc1
join dbo.UnitConvertTest uc2 on uc1.itemid = uc2.itemid
and uc1.tounit = uc2.fromunit
where uc1.itemid = @ItemID
and uc1.fromunit = @FromUnit
and uc2.tounit = @ToUnit
and uc1.factor <> 0
and uc2.factor <> 0
-- Inverted 2-step
if @Factor is null
select @Factor = 1 / (uc1.factor * uc2.factor)
from dbo.UnitConvertTest uc1
join dbo.UnitConvertTest uc2 on uc1.itemid = uc2.itemid
and uc1.tounit = uc2.fromunit
Where uc1.itemid = @ItemID
and uc1.fromunit = @ToUnit
and uc2.tounit = @FromUnit
-- Complex 2-step (same fromunit)
if @Factor is null
select @Factor = uc1.factor / uc2.factor
from dbo.UnitConvertTest uc1
join dbo.UnitConvertTest uc2 on uc1.itemid = uc2.itemid
and uc1.fromunit = uc2.fromunit
Where uc1.itemid = @ItemID
and uc1.tounit = @ToUnit
and uc2.tounit = @FromUnit
-- Complex 2-step (same tounit)
if @Factor is null
select @Factor = uc1.factor / uc2.factor
from dbo.UnitConvertTest uc1
join dbo.UnitConvertTest uc2 on uc1.itemid = uc2.itemid
and uc1.tounit = uc2.tounit
Where uc1.itemid = @ItemID
and uc1.fromunit = @FromUnit
and uc2.fromunit = @ToUnit
-- Default
if @Factor is null
set @Factor = 1
return @Factor
end
This is a table with a few records for testing.
CREATE TABLE [dbo].[UnitConvertTest](
[FROMUNIT] [nvarchar](10) NOT NULL,
[TOUNIT] [nvarchar](10) NOT NULL,
[FACTOR] [numeric](28,12) NOT NULL,
[ITEMID] [nvarchar](20) NOT NULL,
) ON [PRIMARY]
insert into dbo.UnitConvertTest (FROMUNIT, TOUNIT, FACTOR, ITEMID)
Values ('CT','PT','40.00','TEST')
, ('RM','CT','10.00','TEST')
, ('RM','PT','400.00','TEST')
Select [dbo].[fnUOMFactor_Inline] ('Test','PT','RM')