【发布时间】:2017-12-06 07:53:45
【问题描述】:
我有一个查询,它从 char 字段中剪切出一个子字符串并返回一个日期。 它有效:
select
ujp_jobid, ujp_lfdnr,
isnull(convert(date, substring(ujp_parawert, charindex(' ', ujp_parawert) + 1,10), 104), convert(date, getDate())) para_date,
datediff(day, isnull(convert(date, substring(ujp_parawert, charindex(' ', ujp_parawert) + 1,10), 104), convert(date,getDate())), convert(date,getDate())) datedif
from
uno_jobpara
where
ujp_jobid between 0 and 30000
and ujp_paraname = 'P_PGENDE'
结果是:
1 6 2017-11-28 8
2 372 2017-05-06 214
3 84 2017-05-01 219
...
我首先尝试使用 datedif 部分作为 where 子句:
...
and ujp_paraname = 'P_PGENDE'
and datediff(day, isnull(convert(date, substring(ujp_parawert, charindex(' ', ujp_parawert) + 1,10), 104), convert(date,getDate()) ), convert(date,getDate())) > 0
服务器突然报错:
[代码:241,SQL 状态:S0001] Fehler beim Konvertieren einer Zeichenfolge in ein Datum und/oder eine Uhrzeit。
(粗略翻译:将字符串转换为日期和/或时间时出错)
不太清楚为什么会这样,但我猜是服务器尝试首先检查 where 条件并认为它可能会遇到错误。
但是我试图把所有的都放在另一个选择中:
select
ujp_jobid, ujp_lfdnr, para_date, datedif
from
(select
ujp_jobid, ujp_lfdnr,
isnull(convert(date, substring(ujp_parawert, charindex(' ', ujp_parawert) + 1,10), 104), convert(date,getDate()) ) para_date,
datediff(day, isnull(convert(date, substring(ujp_parawert, charindex(' ', ujp_parawert) + 1,10), 104), convert(date, getDate()) ), convert(date, getDate())) datedif
from
uno_jobpara
where
ujp_jobid between 0 and 30000
and ujp_paraname = 'P_PGENDE') as tt
where
tt.datedif > 0;
同样的错误?!为什么,以及如何告诉 SQL Server 先运行子查询?我真的需要临时表吗?
TIA
乔
【问题讨论】:
-
您使用的是哪个版本的 SQL Server?
SELECT @@VERSION -
Microsoft SQL Server 2016 (SP1-GDR) (KB4019089) - 13.0.4206.0 (X64) Jul 6 2017 07:55:03 版权所有 (c) Microsoft Corporation Standard Edition (64-bit) on Windows Server 2012 Datacenter 6.2
(Build 9200: ) (Hypervisor)
标签: sql-server string date substring