Tsql sp_executesql与用户定义的标量函数

Tsql sp_executesql与用户定义的标量函数,tsql,sql-server-2012,user-defined-functions,cross-apply,sp-executesql,Tsql,Sql Server 2012,User Defined Functions,Cross Apply,Sp Executesql,在下表中,我存储了如下一些条件: 然后,一般来说,在第二个表中,我有以下记录: 我需要的是使用正确的条件来比较这些值,并将结果存储在其他列中(假设“0”表示false,“1”表示true) 我将在一个存储过程中这样做,基本上我将比较几条到数百条记录 可能的解决方案是对构建动态语句的每一行使用sp_executesql,另一种是创建自己的标量函数,并使用交叉应用为每一行调用它 谁能告诉我哪种方法更有效 注意:我知道回答这个问题的最好方法是制作这两个解决方案并进行测试,但我希望基于缓存和SQL内

在下表中,我存储了如下一些条件:

然后,一般来说,在第二个表中,我有以下记录:

我需要的是使用正确的条件来比较这些值,并将结果存储在其他列中(假设“0”表示false,“1”表示true)

我将在一个存储过程中这样做,基本上我将比较几条到数百条记录

可能的解决方案是对构建动态语句的每一行使用sp_executesql,另一种是创建自己的标量函数,并使用交叉应用为每一行调用它

谁能告诉我哪种方法更有效


注意:我知道回答这个问题的最好方法是制作这两个解决方案并进行测试,但我希望基于缓存和SQL内部优化等其他内容,可能会有答案,这将节省我很多时间,因为这只是一个更大问题的一部分。

在这种情况下,我认为没有必要使用
sp_executesql
。您可以在一条语句中一次获得所有记录的结果:

select Result = case
    when ct.Abbreviation='=' and t.ValueOne=t.ValueTwo then 1
    when ct.Abbreviation='>' and t.ValueOne>t.ValueTwo then 1
    when ct.Abbreviation='>=' and t.ValueOne>=t.ValueTwo then 1
    when ct.Abbreviation='<=' and t.ValueOne<=t.ValueTwo then 1
    when ct.Abbreviation='<>' and t.ValueOne<>t.ValueTwo then 1
    when ct.Abbreviation='<' and t.ValueOne<t.ValueTwo then 1
    else 0 end
from YourTable t
    join ConditionType ct on ct.ID = t.ConditionTypeID

;with cte as (
    select t.AdditionalColumn, Result = case
        when ct.Abbreviation='=' and t.ValueOne=t.ValueTwo then 1
        when ct.Abbreviation='>' and t.ValueOne>t.ValueTwo then 1
        when ct.Abbreviation='>=' and t.ValueOne>=t.ValueTwo then 1
        when ct.Abbreviation='<=' and t.ValueOne<=t.ValueTwo then 1
        when ct.Abbreviation='<>' and t.ValueOne<>t.ValueTwo then 1
        when ct.Abbreviation='<' and t.ValueOne<t.ValueTwo then 1
        else 0 end
    from YourTable t
        join ConditionType ct on ct.ID = t.ConditionTypeID
)
update cte
set AdditionalColumn = Result
create function ftComparison
(
    @v1 float,
    @v2 float,
    @cType int
)
returns table
as return
    select
        Result = case
            when ct.Abbreviation='=' and @v1=@v2 then 1
            when ct.Abbreviation='>' and @v1>@v2 then 1
            when ct.Abbreviation='>=' and @v1>=@v2 then 1
            when ct.Abbreviation='<=' and @v1<=@v2 then 1
            when ct.Abbreviation='<>' and @v1<>@v2 then 1
            when ct.Abbreviation='<' and @v1<@v2 then 1
            else 0
        end
    from ConditionType ct
    where ct.ID = @cType
select f.Result
from YourTable t
    cross apply ftComparison(ValueOne, ValueTwo, t.ConditionTypeID) f
select f.Result
from YourAnotherTable t
    cross apply ftComparison(SomeValueColumn, SomeOtherValueColumn, @someConditionType) f