[英]Conversion failed when converting date and/or time from character string
我收到此錯誤:當我嘗試在 SQL 服務器 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
這個查詢運行良好WHERE datediff(DAY, cast(replace (left (left(t.name, len(t.name) - len('_data')), 10), '_', '') as datetime), @Time) <= 1
,那么我想知道這是否是cast
function 的問題。 但是t
表將具有像'2011_07_13_DM_VT_I2_Data'
這樣的表名,您可以在@TestTime
中看到強制cast
function 可以正常使用這種格式。 我不知道WHERE
條件有什么問題。
感謝您的任何幫助。
您需要將查詢分成兩部分,因為看起來查詢優化器已決定應用外部查詢中的 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.