sql server - Scalar function as a part of computed column -
i using sql server 2012. want create table computed column. column sum of columns in table, need multiply sum vat rate vat table gross value including tax. vat values inserted vat table every month , stored in column stawka smallint (in english means "rate"). values table prąd inserted every month need use current vat rate column stawka in vat table.
so if tax rate (columnn stawka in vat table) 23%, it's simple math: (y+z) + 23% * (y+z) =( y+z) * (1 + 0.23) = (y+z) * 1.23 y+z sum of decimal columns before last 1 in table prąd.
row example table prąd. below in last column (computed column) sum of 0.2661 + 0.2103. above, first need sum 0.2103 , 0.2661 , multiply sum 1.23:
id data rok kwartał miesiąc dzień jednostka odczyt zużycie energia elektryczna czynna opłata dystrybucyjna zmienna stawka jednostkowa energii 1 2015-01-01 2015 1 1 1 kwh 300 20 0.2661 0.2103 0.4764
i cannot hard-code value 1.23 because vat rate can change i've decided create vat table don't know how use these values in column stawka inside computed column.
i tried use tips found here , use scalar function current vat value , concatenate seems cannot use part of whole calculation. code below:
table computed column i'm trying create(error invalid column "stawka" pops while creating table):
create table dbo.prąd ( id int not null identity (1,1), data date not null, rok year(data) persisted not null, kwartał datepart(q,data) persisted not null, miesiąc month(data) persisted not null, dzień day(data) persisted not null, jednostka varchar (5) null, odczyt smallint not null, zużycie smallint not null, [energia elektryczna czynna] decimal (9,4) null, [opłata dystrybucyjna zmienna] decimal (9,4) null, [stawka jednostkowa energii] cast (([energia elektryczna czynna] + [opłata dystrybucyjna zmienna])*('1.' + dbo.fnvat(id)) decimal (9,4)) persisted not null )
vat table:
create table dbo.vat ( id int not null identity (1,1), data date not null, stawka smallint not null, );
scalar function:
create function fnvat (@vat smallint) returns smallint begin select @vat = stawka vat v join prąd p on v.id = p.id return @vat end
since vat depends on contents of other table, don't think it's possible create column persisted. means every time select column, scalar function called separately every row in select. can bad performance , can't recommend it, if want it, way it:
create function fnvat (@date date) returns decimal(3,2) begin declare @vat smallint select top 1 @vat = vat vat date <= @date order date desc return 1 + 0.01 * @vat end; alter table prad add vat (value1 + value2) * dbo.fnvat(date)
my example made using table:
create table prad ([id] int, [date] date, [value1] decimal (9,4), [value2] decimal (9,4))
since thought lot easier me not use polish(?) column names.
example in sql fiddle
like said, in trigger, should lot better performance wise since fetch done once, , since vat doesn't change might best idea.
Comments
Post a Comment