在查询的where子句中强制转换datetime


SELECT *
FROM tblClassAppointments
INNER JOIN tblClassGroups ON tblClassAppointments.GroupID = tblClassGroups.GroupID
WHERE (
        ('2015-07-13' >= StartTime)
        AND ('2015-07-13' <= EndTime)
        AND ('2015-07-13' > StartTime)
        AND ('2015-07-13' >= EndTime)
        )
    OR (
        ('2015-07-13' >= StartTime)
        AND ('2015-07-13' < EndTime)
        AND ('2015-07-13' > StartTime)
        AND ('2015-07-13' <= EndTime)
        )
    OR (
        ('2015-07-13' <= StartTime)
        AND ('2015-07-13' < EndTime)
        AND ('2015-07-13' >= StartTime)
        AND ('2015-07-13' <= EndTime)
        )
    OR (
        ('2015-07-13' <= StartTime)
        AND ('2015-07-13' >= EndTime)
        )

我使用上面的查询来获取在特定时间段内放置的类约会。我需要将StartTime(tblClassAppointments.StartTime)EndTime(tblClassAppointments.EndTime)转换为yyyy-mm-dd

我尝试了什么:

I tried

 CONVERT(char(10), StartTime, 126) 

CONVERT(char(10), EndTime, 126) 

代替StartTimeEndTime.给出错误。

我需要什么:

我如何将StartTimeEndTime转换为yyyy-mm-dd在where子句本身?(两个字段都是datetime类型)

请给我建议。由于

你的WHERE子句太混乱了,我根本不明白,我会尽量使用BETWEEN。

我敢打赌你会得到截断错误,因为你试图将日期时间数据类型转换为char(10),这太小了。如果您只关心日期部分,则强制转换为date数据类型。

下面是一个示例:

; with CTE1 as (
    SELECT *
    , cast(StartTime as date) as StartTime2
    , cast(EndTime as date) as EndTime2
    FROM tblClassAppointments
    INNER JOIN tblClassGroups ON tblClassAppointments.GroupID = tblClassGroups.GroupID
)
select *
from CTE1
WHERE
    ('2015-07-13' between StartTime2 and EndTime2)
OR (
    ('2015-07-13' <= StartTime2)
    AND ('2015-07-13' < EndTime2)
    AND ('2015-07-13' >= StartTime2)
    AND ('2015-07-13' <= EndTime2)
    )
OR (
    ('2015-07-13' <= StartTime2)
    AND ('2015-07-13' >= EndTime2)
    )

这对于注释来说太长了,并且没有直接解决字符串的任何格式问题。你的约会比较很复杂。如果StartTimeEndTime有时间组件,并且您想知道'2015-07-13'的整个一天是否被覆盖,则使用:

WHERE StartTime <= '2015-07-13' and EndTime >= '2015-07-14'

即从一天开始前开始,到一天开始后结束。

如果您想知道日期是否覆盖了的任何部分:

WHERE StartTime < '2015-07-14' and EndTime >= '2015-07-13'

即从一天结束前开始到一天开始后开始。

如果你不喜欢'2015-07-14'在逻辑中,那么使用DATEADD(day, 1, '2015-07-13')

并且,如果您希望独立于国际化设置,您还可以使用CAST('20150714' as DATE)

相关内容

  • 没有找到相关文章

最新更新