sql server - SQL function performance -


i have function used on view.

function [dbo].[calculateamount] ( @id int, @price decimal(24,4))   declare @computedvalue decimal(24,4)  set @computedvalue = case when  (select table1.id dbo.[table1] table1 join dbo.[table2] table2 on table2.id = table1.id table1.id = @id // conditions here // null @price  else @price * cast('1.0368' decimal(24,4)) end 

so basically, wanted check if id passed parameter existing on table1. if returned row, multiply price 1.0368, if not price remain is.

my problem here performance. using on view returns 17000 rows. view running, 45 minutes on 12000th row.

any ideas or suggestion improve performance of view?

edit

i calling on view this:

[dbo].[calculateamount](id, price) price 

along select statement.

if place use function in view, why not encapsulate logic in view:

alter view dbo.yourview     select  <columns>,             calculatedprice = case when t1.id null <tables>.price                                      else 1.0368 * <tables>.price                                  end        <tables>             outer apply             (   select  top 1 t1.id                    dbo.table1 t1                         inner join dbo.table2 t2                             on t2.id = t1.id                   t1.id = <tables>.id                 --      more conditions             ) t1       <predicates>; 

the outer apply same check function see if record exists, in select statement, when match not found price multiplied constant, otherwise multiplied 1.

you create inline table valued function this. unlike scalar udf not executed rbar, query plan expanded out outer query:

create function dbo.calculateamount (@id int, @price decimal(24, 4) returns table return (   select  price = case when count(*) = 0 @price                         else @price * 1.0368                     end        dbo.table1 t1             inner join dbo.table2 t2                 on t2.id = t1.id       t1.id = @id ); 

then call as:

select  <columns>,         calculatedprice = ca.price    <tables>         outer apply dbo.calculateamount(id, price) ca   <predicates>; 

Comments

Popular posts from this blog

Ansible - ERROR! the field 'hosts' is required but was not set -

customize file_field button ruby on rails -

SoapUI on windows 10 - high DPI/4K scaling issue -