我有一个字段(SIDENT),其中包含不同格式的文本数据。我想更新数据并制作一致的格式。目前的数据如下:
22-Jan-2014-0101
22-Jan-2014-0101
23-Jan-14-10001
QA Calibration C
23-Jan-14-10005
我想要的是YYYY-MM-DD-#####
---我必须忽略Alpha字符串(“QA ...”)
我有一个报告的选择语句(缺少运算符) - 有人可以告诉我错误在哪里吗?
SELECT SIDENT,
CASE WHEN SUBSTRING(SIDENT, 10, 1) = '-' THEN CAST(CAST(SUBSTRING(SIDENT, 1, 9) AS DATE) AS NVARCHAR) + '-' +
(CASE WHEN LEN(SIDENT) = 15 THEN SUBSTRING(SIDENT, 11, 5) ELSE '0' + SUBSTRING(SIDENT, 11, 4) END) ELSE
CAST(CAST(SUBSTRING(SIDENT, 1, 11) AS DATE) AS NVARCHAR) + '-' +
(CASE WHEN LEN(SIDENT) = 15 THEN SUBSTRING(SIDENT, 13, 5) ELSE '0' + SUBSTRING(SIDENT, 13, 4) END)
END AS SIDENT_FIXED
FROM ExcelFile_sident
ORDER BY
CASE WHEN SUBSTRING(SIDENT, 10, 1) = '-' THEN CAST(CAST(SUBSTRING(SIDENT, 1, 9) AS DATE) AS NVARCHAR) + '-' +
(CASE WHEN LEN(SIDENT) = 15 THEN SUBSTRING(SIDENT, 11, 5) ELSE '0' + SUBSTRING(SIDENT, 11, 4) END) ELSE
CAST(CAST(SUBSTRING(SIDENT, 1, 11) AS DATE) AS NVARCHAR) + '-' +
(CASE WHEN LEN(SIDENT) = 15 THEN SUBSTRING(SIDENT, 13, 5) ELSE '0' + SUBSTRING(SIDENT, 13, 4) END)
END
答案 0 :(得分:3)
正如评论中所指出的,Access不使用Case...when...end
语法。相反,您需要使用inline ifs
([IIF
])1。如果我尝试在Access查询中使用Case
,那么您所说的错误就是我得到的确切错误。
其他Access转化次数为
Cast(xxx as Date)
--->CDate()
Cast(xxx as NVARCHAR)
--->CStr()
Substring()
--->Mid()
+
---> &安培;
SELECT SIDENT, iif(Mid(SIDENT, 10, 1) = '-', mid(SIDENT, 1, 9) & '-' &
iif(LEN(SIDENT) = 15,Mid(SIDENT, 11, 5),'0' & Mid(SIDENT, 11, 4))
, Mid(SIDENT, 1, 11) & '-' & iif(LEN(SIDENT) = 15,Mid(SIDENT, 13, 5)
,'0' + Mid(SIDENT, 13, 4)) ) as SIDENT_FIXED
from ExcelFile_sident
order by iif(Mid(SIDENT, 10, 1) = '-', mid(SIDENT, 1, 9) & '-' &
iif(LEN(SIDENT) = 15,Mid(SIDENT, 11, 5),'0' & Mid(SIDENT, 11, 4))
, Mid(SIDENT, 1, 11) & '-' & iif(LEN(SIDENT) = 15,Mid(SIDENT, 13, 5)
,'0' + Mid(SIDENT, 13, 4)) )
答案 1 :(得分:1)
如果要使用Access SQL转换这些字符串,请使用此立即窗口示例中的Access支持的函数:
SIDENT = "22-Jan-2014-0101"
? InstrRev(SIDENT,"-")
12
? Left(SIDENT, InstrRev(SIDENT,"-") - 1)
22-Jan-2014
? Format(Left(SIDENT, InstrRev(SIDENT,"-") - 1), "yyyy-mm-dd")
2014-01-22
? Format(Left(SIDENT, InstrRev(SIDENT,"-") - 1), "yyyy-mm-dd") _
& "-" & Format(Mid(SIDENT, InstrRev(SIDENT,"-") + 1), "00000")
2014-01-22-00101
以下是使用这些功能的SELECT
查询:
SELECT
e.ID,
e.SIDENT,
Format(Left(SIDENT, InstrRev(SIDENT, '-') - 1), 'yyyy-mm-dd')
& '-' & Format(Mid(SIDENT, InstrRev(SIDENT, '-') + 1), '00000')
AS SIDENT_FIXED
FROM ExcelFile_sident AS e
WHERE e.SIDENT ALike '%-%';
请注意WHERE
子句:我假设您要转换的SIDENT
值都包含至少一个" - "字符。如果我的假设是错误的,请根据需要更改WHERE
子句。
以下是基于您的示例数据的查询输出:
ID SIDENT SIDENT_FIXED
-- ---------------- ----------------
1 22-Jan-2014-0101 2014-01-22-00101
2 22-Jan-2014-0101 2014-01-22-00101
3 23-Jan-14-10001 2014-01-23-10001
5 23-Jan-14-10005 2014-01-23-10005
如果您确实要更改存储的SIDENT
值,请将SELECT
转换为UPDATE
查询。