1

在下面的表格我存儲這樣一些條件:sp_executesql的VS用戶定義的標量函數

enter image description here

然後,通常,在第二表中,我有以下記錄:

enter image description here

我需要的是使用正確的條件來比較這些值並存儲結果(假設'0'爲false,'1'爲true則在附加列中)。

我打算在存儲過程中這樣做,基本上我會比較幾個到幾百個記錄。

什麼是可能的解決方案是使用sp_executesql爲每行構建動態語句,另一種是創建我自己的標量函數,並使用交叉應用爲eacy行調用它。

任何人都可以告訴哪個更有效的方法嗎?

注意:我知道最好的解決方法是做出兩個解決方案並進行測試,但我希望基於其他內容(如緩存和SQL內部優化等)可以解決這個問題。將爲我節省很多時間,因爲這只是更大問題的一部分。

回答

2

在這種情況下,我看不到需要使用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