datetime,varchar转换问题


Warning: Undefined array key "HTTP_REFERER" in /www/wwwroot/prod/www.enjoyasp.net/wp-content/plugins/google-highlight/google-hilite.php on line 58

declare @temp1 varchar(20)
select @temp1=orderdate from bdorder
where orderno = ‘J090825A001′

print @temp1

select * from bdorder
where orderdate = @temp1

执行上述语句,结果为空!即使@temp1有值
原因:时间类型的优先级高于字符型,所以当比较一个DATETIME类型的数据和一个字符串的时候,字符串首先会转化成DATETIME。
select @temp1=orderdate ,因datetime优先级比@temp1优先级高,为varchar类型@temp1赋值的时候要向下转型,
默认调用convert(varchar(20),orderdate,100) 转换成mon dd yyyy hh:miAM(或 PM)格式。
而当进行比较时where orderdate = @temp1,@temp1因向上转型,保持数据不平(参考int向上转为float),此时@temp1为’04? 6 2010? 8:36AM’,而数据库中的日期为’2010-04-06 08:36:38′, 二者相比当然是得不到结果的。

注:sql server中DateTime默认存储方式为:yyyy-mm-dd hh:mi:ss(24h),当为varchar赋值时,默认转换成了mon dd yyyy hh:miAM(或 PM)格式,二者再进行比较,就会出问题。即:默认存储方式与默认转换方式不同造成的。

解决方案:为varchar赋值时取消默认,即:
select @temp1=convert(varchar(20),orderdate,120) from bdorder where orderno = ‘J090825A001’