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.