优化更新语句

时间:2012-06-11 18:24:37

标签: sql

我目前正在尝试优化sql代码。我想知道是否有另一种编写这些语句的方法,因为它似乎需要花费大量时间才能完成。

Update #TMP---updates  webid when its null in tmp table
Set #TMP.webid_Val='NOT COMPLIANT'
Where  #TMP.webid is null

Update #TMP---updates  PID when its null in tmp table
Set #TMP.PID_Val='NOT COMPLIANT'
Where  #TMP.Pid is null

Update #TMP---Shifts multiple fob situations into storewide
Set #TMP.GMM ='Storewide'
Where  #TMP.gmm like '%, %';

Update #TMP-----Shifts marketing into multiple fob situation
Set #TMP.GMM ='Storewide'
Where  #TMP.gmm like 'Marketing%'


Update #TMP
Set #TMP.OVERALL_Val='NOT COMPLIANT'
Where  #TMP.webid is null

这确实有超过22,000个条目。

2 个答案:

答案 0 :(得分:3)

不是肯定的,这会更快,因为它取决于数据,但单个更新语句可能表现最佳。

Update #TMP
Set #TMP.webid_Val=
        CASE
            WHEN #TMP.webid is null THEN 'NOT COMPLIANT'
            ELSE #TMP.webid_Val
        END
     ,#TMP.PID_Val=
        CASE
            WHEN #TMP.Pid is null THEN 'NOT COMPLIANT'
            ELSE #TMP.PID_Val
        END
     ,#TMP.GMM=
        CASE
            WHEN (#TMP.GMM like '%, %' OR #TMP.gmm like 'Marketing%') THEN 'Storewide'
            ELSE #TMP.GMM
        END
    ,#TMP.OVERALL_Val=
        CASE
            WHEN (#TMP.webid is null) THEN 'NOT COMPLIANT'
            ELSE #TMP.OVERALL_Val
        END
WHERE #TMP.webid is null
OR #TMP.Pid is null
OR #TMP.gmm like '%, %'
OR #TMP.gmm like 'Marketing%'

答案 1 :(得分:1)

我看到的第一篇文章是你可以将这两个更新语句结合起来:

Update #TMP---updates  webid when its null in tmp table
Set #TMP.webid_Val='NOT COMPLIANT'
Where  #TMP.webid is null

Update #TMP
Set #TMP.OVERALL_Val='NOT COMPLIANT'
Where  #TMP.webid is null

分为:

Update #TMP---updates  webid when its null in tmp table
Set #TMP.webid_Val='NOT COMPLIANT',
    #TMP.OVERALL_Val='NOT COMPLIANT'
Where  #TMP.webid is null

您可以将两个GMM更新合并到以下内容中:

Update #TMP---Shifts multiple fob situations into storewide
Set #TMP.GMM ='Storewide'
Where  LEFT(#TMP.gmm, 9) = 'Marketing'
OR #TMP.gmm like '%, %';

执行LEFT而不是LIKE匹配应该更高效一点(注意:不确定,你必须对其进行测试以验证)。