索引對查詢條件順序的影響

來源:互聯網
上載者:User

原帖地址:
http://community.csdn.net/Expert/FAQ/FAQ_Index.asp?id=207897

環境:Sql Server2000 +sp4

問題:
select datediff(day,'20040910','20040920')  --這句可以執行

--而下面這句不能執行(有時也可以執行)
--sub_para為varchar(8),錯誤資訊是:從字串轉換為 datetime 時發生語法錯誤。
select * from T_SUB
where item_local_code='03004'
 and  datediff(day,sub_para,getdate())=29
 and (sub_del_flag<>1)

--而且不能執行的時候,這個語句不會返回任何記錄集
select * from t_sub
where  item_local_code='03004'
 and isDate(sub_para)=0

-------------------------------------------------------------------------
--原因,表中建立的索引影響了條件的執行順序
--導致先執行了 datediff(day,sub_para,getdate())

--下面的測試說明了這個問題
--測試表及資料
create table tb(
item_local_code char(5),
sub_del_flag int,
sub_para varchar(10),
constraint PK_t primary key(sub_para,item_local_code)
)
insert tb select '03004',1,'2003-1-1'
union all select '03005',1,'2003a1-1'
go

--查詢語句
select * from (
 select * from tb
 where item_local_code='03004'
  and sub_del_flag<>0
  and isdate(sub_para)=1
) A where datediff(day,sub_para,getdate())>29
go

--刪除測試
drop table tb

/*--測試結果

item_local_code sub_del_flag sub_para  
--------------- ------------ ----------
03004           1            2003-1-1

伺服器: 訊息 241,層級 16,狀態 1,行 3
從字串轉換為 datetime 時發生語法錯誤。

--*/

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.