在這種情況下,我看不到需要使用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 @[email protected] then 1
when ct.Abbreviation='>' and @v1>@v2 then 1
when ct.Abbreviation='>=' and @v1>[email protected] then 1
when ct.Abbreviation='<=' and @v1<[email protected] 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