当我尝试在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
条件有什么问题。
感谢您的帮助。
答案 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