select top 1000 id,username,usercode,isnull (dCompDt,convert(smalldatetime,'2078-06-06')) as newCompDt from tablename order by  get_newCompDt desc 
==========================
dCompDt是完成時間,已完成的(有時間)排在後面用倒序排,沒完成的排在前面(都是null值),
用上面的newCompDt方式來排好慢啊,運行要8秒左右,數據有30萬條記錄,已經top 1000了啊。
請問可以改成什麼樣的寫法會更快?

解决方案 »

  1.   


    上面寫錯名稱應該是order by newCompDt desc 
      

  2.   

    你都没where语句,当然慢拉,全表扫描的。把get_newCompDt做个降序的聚集索引,可以减少order by 的开销。
      

  3.   

    select top 1000 id,username,usercode
    from tablename 
     order by case when dCompDt=null then 0 else 1 end,dCompDt desc  
      

  4.   

    select top 1000 id,username,usercode,isnull (dCompDt,convert(smalldatetime,'2078-06-06')) as newCompDt from tablename order by 
    case when dCompDt is null then 0 else 1 end ,dCompDt desc
      

  5.   


    用=號會出錯,改成order by case when dCompDt is null then 0 else 1 end,dCompDt desc 後速度沒有改善啊。
      

  6.   

    id 主键+dCompDt 索引语句改成 
    select top 1000 id,username,usercode,isnull (dCompDt,convert(smalldatetime,'2078-06-06')) as newCompDt from tablename
    case when dCompDt is  null then 0 else 1 end,dCompDt desc
      

  7.   


    我的sql是寫在網頁裡的,數據庫我動不了
      

  8.   

    你签入到网页里面,每次执行都要编译,性能肯定会低。我相信绝大部分应用都不需要在30万数据全表扫描的,你要想办法加入where条件筛选。全表扫描就算加了top也一定会快不了多少。再想想是否可以where中加上日期限定?或者加上用户限定等等条件。
      

  9.   

    那你单纯从sql语句写法上没什么好优化的了
      

  10.   

    謝謝,我看看能加入什麼where條件,默認只顯示null的記錄,需要的時間再讓用戶自己選擇全部搜索好了