是这样,一个表,我开始没有用日期这个字段,反而用了这样的, year1,month1,day1,分别代表年月日,是int类型的,可是现在要做查询了,就出问题了,
我想查两个时间段的数据,好不容易在access里面行得通了.可是转到sqlserver里面,就又不行了.不知怎么办才好.access里是这样的,sql=sql&" and cdate(cstr(year1)&'-'&cstr(month1)&'-'&cstr(day1)) between "&date1&" and "&date2 date1,date2从界面上的日历选择器取得的,我不想拆开这个日期成,想组合数据库里year1,month1,day1这三个字段来查询.
我用过cast等,但好像提示说类型不正确,真的不知怎么办了.
我想查两个时间段的数据,好不容易在access里面行得通了.可是转到sqlserver里面,就又不行了.不知怎么办才好.access里是这样的,sql=sql&" and cdate(cstr(year1)&'-'&cstr(month1)&'-'&cstr(day1)) between "&date1&" and "&date2 date1,date2从界面上的日历选择器取得的,我不想拆开这个日期成,想组合数据库里year1,month1,day1这三个字段来查询.
我用过cast等,但好像提示说类型不正确,真的不知怎么办了.
你的date1,date2变量本身就带了access的日期定界符 # 吧.sql serversql=sql&" and rtrim(year1) + '-' + rtrim(month1) + '-' +rtrim(day1) between '"&date1&"' and '"&date2 & "'"你的date1,date2变量不能带# 或 ', 只能是纯的日期,比如 2007-1-1
sql server
select * from tablename where rtrim(year1) + '- ' + rtrim(month1) + '- ' +rtrim(day1)
between date1 and date2
select * from tablename where cast(year1 as char(5)) + '- ' + cast(month1 as char(5)) + '- ' +cast(day1 as char(5))
between date1 and date2
'2007-10 -1'实际上应该是 '2007-10-1'
如果不用cast,那么实际上是字串比较,
'2007-10- 15' between '2007-10 -1' and ' 2007-10 -20 '
这种比较得不出来结果的.用 cast 对第一个操作数,进行转换为 datetime, 那么 sql会自动为 2007-10- 15去空格,转换为日期, 同时, 因为后面两个值是跟他进行 between and 比较, 所以会隐式转换为 datetime. 所以就排除了空格的问题.