使用这个简单的查询
SELECT dateadd(d,-13,Period_DateEnd) Period
FROM ReportingPeriod_tbl
一旦我添加了更大的查询,我就会收到转换错误,而且我无能为力。
'从字符串转换日期和/或时间时转换失败。'
SELECT PeriodEnding FROM
(
SELECT format(WeekEnd,'d-MMM-yy') PeriodEnding
FROM WeekEnd_tbl WHERE WeekEnd <= (SELECT TOP 1 WeekEnd FROM WeekEnd_tbl A WHERE A.IsCurrentWeek = 1)
UNION ALL
SELECT
format(Period_DateEnd,'MMM-yy') Period
FROM ReportingPeriod_tbl WHERE ReportingPeriod_ID <= (SELECT TOP 1 ReportingPeriod_ID FROM ReportingPeriod_tbl A
WHERE Period_DateEnd >= (SELECT TOP 1 WeekEnd FROM WeekEnd_tbl A WHERE A.IsCurrentWeek = 1 ORDER BY WeekEnd))
UNION ALL
SELECT
dateadd(d,-13,Period_DateEnd) Period
FROM ReportingPeriod_tbl WHERE ReportingPeriod_ID <= (SELECT TOP 1 ReportingPeriod_ID FROM ReportingPeriod_tbl A
WHERE Period_DateEnd >= (SELECT TOP 1 WeekEnd FROM WeekEnd_tbl A WHERE A.IsCurrentWeek = 1 ORDER BY WeekEnd))
) Period
答案 0 :(得分:0)
你的字符串日期时间格式是worng
示例:
select dateadd(d,-13,'2018/04/28 12:00:00.000') --fine be ok
select dateadd(d,-13,convert(datetime,'2018/04/28 12:00:00.000')) --fine be ok
select dateadd(d,-13,'04/28') --Conversion failed when converting date and/or time from character string
希望能帮到你:)。
新Qeustion:
更改您的查询:
SELECT
dateadd(d,-13,Period_DateEnd) Period
FROM ReportingPeriod_tbl
到
SELECT
dateadd(d,-13,
SUBSTRING(Period_DateEnd, 7, 4)
+'/'+SUBSTRING(Period_DateEnd, 4, 2)
+'/'+SUBSTRING(Period_DateEnd, 1, 2)
+SUBSTRING(Period_DateEnd, 11, 13)
) Period
FROM ReportingPeriod_tbl
DEMO 和 结果:
答案 1 :(得分:0)
请使用它来避免异常并找出格式不正确的strigs:
SELECT
[Period] = dateadd(d, -13, try_convert(datetime, [Period_DateEnd]))
,[Err_message] = iif(try_convert(datetime, [Period_DateEnd]) is null, 'Failed to convert string {' + [Period_DateEnd] + '} to datetime', null)
FROM
[ReportingPeriod_tbl];
完整查询:https://pastebin.com/3PPpkf2t
还有一件事:你必须拥有相同的日期时间格式。为什么?因为03/01/08。是2008年3月1日,或2008年1月3日,或2003年1月8日? :)