简体   繁体   中英

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

I'm getting this error: Conversion failed when converting date and/or time from character string when I try to run the following query in SQL server 2008 R2:

    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

This query runs fine if I comment out WHERE datediff(DAY, cast(replace (left (left(t.name, len(t.name) - len('_data')), 10), '_', '') as datetime), @Time) <= 1 , then I wonder if it is the problem of the cast function. But the t table will have the table names like '2011_07_13_DM_VT_I2_Data' you can see in the @TestTime the cast function works fine with this format. I don't know what is the wrong with the WHERE condition.

Thank you for any help.

You need to split your query into two because it looks like the query optimizer has decided to apply the where clause from the outer query before it has filtered down the rows from sysobjects in the sub query.

You could try something like this.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM