无法从具有Between条件的数据库中获取记录

时间:2016-03-05 12:01:35

标签: sql sql-server

日期在我的数据库中以这种格式播出。

04 Feb 2016
04 Mar 2016
04 Mar 2016
04 Mar 2016
04 Mar 2016

我正在使用

 select CONVERT(VARCHAR(20),Convert(datetime,CREATEDATE),106)
 from job
 where CONVERT(VARCHAR(20),Convert(datetime,CREATEDATE),106) 
 between     Convert(VARCHAR(20),Convert(datetime,getdate())-25,106)
         AND CONVERT(VARCHAR(20),Convert(datetime,GETDATE()),106)

从数据库获取结果的SQL语句。但是我无法获得任何记录。

2 个答案:

答案 0 :(得分:0)

停止dates存储和解析为VARCHAR。将日期存储在DATETIMEDATE数据类型而不是Varchar,这将有助于您避免所有这些转换

现在回到问题所在,您正在尝试比较VarcharVarchar1之间的Varchar2 DateDate1之间Date2CREATEDATE之间的datetime 1}}。

Between转换为;WITH job AS (SELECT * FROM (VALUES (Cast('04 Feb 2016' AS VARCHAR(50))), (Cast('04 Mar 2016' AS VARCHAR(50))), (Cast('04 Mar 2016' AS VARCHAR(50))), (Cast('04 Mar 2016' AS VARCHAR(50))), (Cast('04 Mar 2016' AS VARCHAR(50)))) cs (CREATEDATE)) SELECT CREATEDATE FROM job WHERE CONVERT(DATETIME, CREATEDATE) BETWEEN Getdate() - 25 AND Getdate() 并与func (s intSlice) chanIter() chan int { c := make(chan int) go func() { for _, i := range s { select { case c <- i: case <-c: close(c) return } } close(c) }() return c } 子句中的日期进行比较

s := intSlice{1, 2, 3, 4, 5, 11, 22, 33, 44, 55}
c := s.chanIter()
for i := range c {
    fmt.Println(i)
    if i > 30 {
        // Send to c to interrupt
        c <- 0
    }
}

答案 1 :(得分:0)

为什么要反向转换回varchar?它没有工作正常:

declare @job table (CREATEDATE varchar(50));
insert into @job values
('04 Feb 2016'),
('04 Mar 2016'),
('04 Mar 2016'),
('04 Mar 2016'),
('04 Mar 2016');

select Convert(datetime,CREATEDATE,106)
 from @job t
 where Convert(datetime,CREATEDATE,106) 
 between     Convert(datetime,getdate()-25,106)
         AND Convert(datetime,getdate(),106)
;