如何将datetime转换为datetime2?

时间:2014-03-21 15:38:24

标签: sql sql-server datetime

我遇到了一个查询问题,目前在WHERE子句中使用不同表中的两个字段来过滤数据。由于一个是datetime而另一个是datetime2,我得到了

"Conversion failed when converting date and/or time from character string" error.

以下是查询:

/*| 1) SELECT - ABSENCES AND SCHEDULES |*/
------------------------------------------
    -- Retrieve data of absences
DECLARE @SADate AS DATETIME2(7)
SET @SADate = '2012-12-02'

    -- Retrieve absences that have a supply teacher and are within the current date.
SELECT SAStaffID
       ,LastName + ', ' + FirstName AS FullName
       ,SADate
       ,SSPeriod
       ,SSCourseCode
       ,SSRoom
    FROM tblOCStaffAbsent -- Join the staff schedule of the absent teacher that has a supply.
    INNER JOIN tblOCStaffSchedule S
        ON tblOCStaffAbsent.SAStaffID = S.SSStaffID
           AND @SADate BETWEEN S.SSStartDt AND S.SSEndDt
    INNER JOIN tblStaff SF
        ON SF.StaffID = SAStaffID
    INNER JOIN tblUsers U
        ON U.UserID = SF.StaffUserID
    WHERE SASupplyID IS NOT NULL
        AND SADate = @SADate

--------------------------------
/*| 2) SELECT - SUPERVISIONS |*/
--------------------------------
    --Union the supervisions
UNION ALL
SELECT SSupStaffID
       ,SupervisionDt
       ,CASE WHEN SSupPeriodHalf IS NOT NULL THEN SSupPeriod + '-' + SSupPeriodHalf
             ELSE SSupPeriod
        END AS FullPeriod
       ,'(SP) ' + SSupLocation
       ,NULL AS SSupRoom
       ,SSupMIDent
    FROM tblOCStaffSupervisions
    WHERE SupervisionDt = @SADate

SADate是tblOCStaffAbsent中的datetime字段,SupervisionDt是tblOCStaffSupervisions中的datetime2字段。

2 个答案:

答案 0 :(得分:1)

来自tblOCStaffSupervisions表的SupervisionDt的值可以是DateTime数据类型。 @SADate ='2012-12-02'是一个字符串。应该在DateTime数据类型中设置@SADate。

答案 1 :(得分:0)

如果仔细查看错误消息,那么将DATETIMEDATETIME2进行比较并不是问题,这可以由sql server完成而没有任何问题。

您将某些内容存储为字符串,但您尝试将其转换为DATETIME2

转换为DATETIME2与其他转换CONVERT (DATETIME2, MyDatetimeField)

一样

只知道DATETIME2的精度高于DATETIME。您的数据不会更改,只有以更高精度添加的新信息才会使用它。

请看以下示例。两行都会产生相同的结果。

DECLARE @Datetime DATETIME = '03/21/2014 15:23:34.444'

SELECT @Datetime
UNION ALL
SELECT CONVERT(DATETIME2, @Datetime)

但在以下情况

DECLARE @datetime2 DATETIME2 = SYSDATETIME();

SELECT @datetime2
UNION ALL
SELECT CONVERT(DATETIME, @datetime2)

首先选择将产生比第二个更高的精度点