从字符串转换日期和/或时间时转换失败

时间:2011-07-13 06:30:50

标签: sql sql-server sql-server-2008-r2

当我尝试在SQL Server 2008 R2中运行以下查询时,我收到此错误:Conversion failed when converting date and/or time from character string

    DECLARE @Time datetime = N'7/13/2011'
    DECLARE @str as varchar(100) = '2011_07_13_DM_VT_I2_Data'
    DECLARE @TestTime datetime =  cast(replace (left (left(@str, len(@str) - len('_data')), 10), '_', '') as datetime)
    DECLARE @r int = datediff(d, @TestTime, @Time)

    SELECT t.name FROM
    (
    SELECT 
         name
    FROM 
        sysobjects 
    WHERE 
        (type = 'U') AND ((name LIKE '%[_]I2[_]Data') or (name LIKE '%[_]R4[_]Data') or (name LIKE '%[_]R8[_]Data'))
    ) t

    WHERE
        datediff(DAY, cast(replace (left (left(t.name, len(t.name) - len('_data')), 10), '_', '') as datetime), @Time) <= 1

    ORDER BY 
        cast(replace (left (left(t.name, len(t.name) - len('_data')), 10), '_', '') as datetime) desc

如果我注释掉WHERE datediff(DAY, cast(replace (left (left(t.name, len(t.name) - len('_data')), 10), '_', '') as datetime), @Time) <= 1,此查询运行正常,那么我想知道它是否是cast函数的问题。但是t表格会有'2011_07_13_DM_VT_I2_Data'这样的表格,你可以在@TestTime中看到cast函数可以正常使用这种格式。我不知道WHERE条件有什么问题。

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

您需要将查询拆分为两个,因为看起来查询优化器决定在外部查询中应用where子句,然后从子查询中的sysobjects中过滤掉行。

你可以尝试这样的事情。

DECLARE @Time datetime = N'7/13/2011'
DECLARE @str as varchar(100) = '2011_07_13_DM_VT_I2_Data'
DECLARE @TestTime datetime =  cast(replace (left (left(@str, len(@str) - len('_data')), 10), '_', '') as datetime)
DECLARE @r int = datediff(d, @TestTime, @Time)

SELECT name INTO #TMP
FROM 
    sysobjects 
WHERE 
    (type = 'U') AND ((name LIKE '%[_]I2[_]Data') or (name LIKE '%[_]R4[_]Data') or (name LIKE '%[_]R8[_]Data'))

SELECT *
FROM #TMP as t
WHERE
    datediff(DAY, cast(replace (left (left(t.name, len(t.name) - len('_data')), 10), '_', '') as datetime), @Time) <= 1

ORDER BY 
    cast(replace (left (left(t.name, len(t.name) - len('_data')), 10), '_', '') as datetime) desc

DROP TABLE #TMP
相关问题