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
如果上述逻辑应该应用于许多地方,而不仅仅是一张桌子,那么是的,你可能会考虑功能。虽然我宁愿使用内联表值函数(不是scalar),因为使用用户定义的标量函数(调用和返回,要处理的行越多,浪费的时间越多)会产生开销。
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