,歡迎訪問網(wǎng)頁設(shè)計愛好者web開發(fā)。
原帖地址:
http://community.csdn.net/expert/faq/faq_manage.asp?id=0&topicid=3390663
環(huán)境:sql server2000 +sp4
問題:
select datediff(day,'20040910','20040920') --這句可以執(zhí)行
--而下面這句不能執(zhí)行(有時也可以執(zhí)行)
--sub_para為varchar(8),錯誤信息是:從字符串轉(zhuǎn)換為 datetime 時發(fā)生語法錯誤。
select * from t_sub
where item_local_code='03004'
and datediff(day,sub_para,getdate())=29
and (sub_del_flag<>1)
--而且不能執(zhí)行的時候,這個語句不會返回任何記錄集
select * from t_sub
where item_local_code='03004'
and isdate(sub_para)=0
-------------------------------------------------------------------------
--原因,表中創(chuàng)建的索引影響了條件的執(zhí)行順序
--導(dǎo)致先執(zhí)行了 datediff(day,sub_para,getdate())
--下面的測試說明了這個問題
--測試表及數(shù)據(jù)
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
/*--測試結(jié)果
item_local_code sub_del_flag sub_para
--------------- ------------ ----------
03004 1 2003-1-1
服務(wù)器: 消息 241,級別 16,狀態(tài) 1,行 3
從字符串轉(zhuǎn)換為 datetime 時發(fā)生語法錯誤。
--*/