将从常量字段派生的 varchar 值转换为月份和年份

Converting varchar values that were derived from a constant field to Month and Year

我有一个查询,我要从字符串中抓取某些文本。字符串的一个例子是:

"Captured Credit Card: MasterCard, xxxx-xxxx-xxxx-xxxx, 09/19. Set as Default."

我的查询是从该文本中提取到期月份和年份。

SUBSTRING(ADT.MsgText, CHARINDEX('/', ADT.MsgText, 0) -2, 2) AS [Month]
,'20' + SUBSTRING(ADT.MsgText, CHARINDEX('/', ADT.MsgText, 0) + 1, 2) AS [Year]

但是,我需要将这些数值识别为日期值。我尝试了以下方法,但没有成功:

UPDATE CCC
SET CCC.[Month] = convert(date, convert(varchar(4), CCC.[Year]) + ' ' + convert(varchar(2), CCC.[Month]))
FROM CC_Captured CCC

我收到的错误信息是:"Update or insert of view or function 'CCC' failed because it contains a derived or constant field."

我想知道如何将这些值转换为日期? 感谢您的帮助!

(我也在用SQL 2016)

您可以使用 DATEFROMPARTS 构造月份中的日期(月份的第一天或最后一天)。

declare @MsgText nvarchar(1000) = N'Captured Credit Card: MasterCard, xxxx-xxxx-xxxx-xxxx, 09/19. Set as Default.'
select SUBSTRING(@MsgText, CHARINDEX('/', @MsgText, 0) -2, 2) AS [Month]
,'20' + SUBSTRING(@MsgText, CHARINDEX('/', @MsgText, 0) + 1, 2) AS [Year]
-- First day of the month
select DATEFROMPARTS(CAST('20' + SUBSTRING(@MsgText, CHARINDEX('/', @MsgText, 0) + 1, 2) as int), CAST(SUBSTRING(@MsgText, CHARINDEX('/', @MsgText, 0) -2, 2) as int), 1) as FirstDayOfMonth
-- Last day of the month - add 1 month to the date above and go back 1 day
select DATEADD(day, -1, DATEADD(month, 1, DATEFROMPARTS(CAST('20' + SUBSTRING(@MsgText, CHARINDEX('/', @MsgText, 0) + 1, 2) as int), CAST(SUBSTRING(@MsgText, CHARINDEX('/', @MsgText, 0) -2, 2) as int), 1))) as EndOfMonth

或者更好,使用 EOMONTH 函数:

select EOMONTH(DATEFROMPARTS(CAST('20' + SUBSTRING(@MsgText, CHARINDEX('/', @MsgText, 0) + 1, 2) as int), CAST(SUBSTRING(@MsgText, CHARINDEX('/', @MsgText, 0) -2, 2) as int), 1)) as EndOfMonth