是这样,一个表,我开始没有用日期这个字段,反而用了这样的, 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等,但好像提示说类型不正确,真的不知怎么办了.

解决方案 »

  1.   

    access里是这样的,sql=sql&" and cdate(cstr(year1)& '- '&cstr(month1)& '- '&cstr(day1)) between "&date1&" and "&date2  
    你的date1,date2变量本身就带了access的日期定界符 # 吧.sql serversql=sql&" and rtrim(year1) + '-' + rtrim(month1) + '-' +rtrim(day1) between '"&date1&"' and '"&date2  & "'"你的date1,date2变量不能带# 或 ', 只能是纯的日期,比如 2007-1-1
      

  2.   

    rtrim(year1)这个是什么意思,因为类型是int的,以前还提示我int不能和+"-"这样的运算
      

  3.   


    sql server 
    select * from tablename where rtrim(year1) +  '- ' + rtrim(month1) +  '- ' +rtrim(day1) 
    between date1 and date2 
      

  4.   

    int 型不能隐式转换为varchar.rtrim(varchar) 给varchar 去尾部空格. rtrim(int) 因为int型不可能存在尾部空格,而这里的意义在于利用 rtrim函数将int隐式转换为 varchar正规的写法应该用 convert或cast对int型数据转换为varchar我嫌cast和convert写法烦琐,所以一直用rtrim进行int到varchar的转换.
      

  5.   

    sql server 
    select * from tablename where cast(year1 as char(5)) +  '- ' + cast(month1 as char(5)) +  '- ' +cast(day1 as char(5)) 
    between date1 and date2
      

  6.   

    select * from P_List where UserName='abc' and rtrim(year1) + '- ' + rtrim(month1) + '- ' +rtrim(day1) between 2007-10-1 and 2007-10-24 order by year1 desc,month1 desc,day1 desc我把语句写上了Microsoft OLE DB Provider for ODBC Drivers 错误 '80040e07' [Microsoft][ODBC SQL Server Driver][SQL Server]将 varchar 值 '2007- 1- 1' 转换为数据类型为 int 的列时发生语法错误。 /member/hnusr_p_more.asp,行 90 
      

  7.   

    我在一楼的语句写的是, 你写的时候注意一下.between  '"&date1&"and  '"&date2  & " '" 
      

  8.   

    between 单引双引 & date1 & 双引单引 and 单引双引 & date2 & 双引单引双引
      

  9.   

    把语句输出看一下. 注意, ' '定界的值之间的空格.为了让值可能出现的错误暴露出来以便数据检索更准确, 使用以下写法:sql=sql&" and cast(rtrim(year1) +  '- ' + rtrim(month1) +  '- ' +rtrim(day1) as datetime) between  '"&date1&"' and  '"&date2  & "'" 
      

  10.   

    哈哈,对了,就是你的这个,加个cast就对了.呵呵.谢谢了,
      

  11.   

    原因是你写语句时,里面多了空格(csdn的ubb,处理时好像加了空格,很烦).比如
    '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. 所以就排除了空格的问题.