这是我到目前为止所拥有的:
DECLARE @STR AS VARCHAR(1000) = 'CustomerID #101010 added. Fixed Price: 3.5555 Effective from 10/16/2024 to 03/31/2 SADFGZFGDA025 Deliveries: 100 Company Pricing Program: TEST 1 Pricing Plan Name: Test plan'
SELECT
CASE WHEN CHARINDEX('Effective from ', @STR) > 0 AND CHARINDEX(CHAR(10), @STR, CHARINDEX('Effective from ', @STR)) > 0 THEN SUBSTRING(@STR, CHARINDEX('Effective from ', @STR) + LEN('Effective from ') + 1, CHARINDEX(CHAR(10), @STR, CHARINDEX('Effective from ', @STR) + LEN('Effective from ') + 1) - (CHARINDEX('Effective from ', @STR) + LEN('Effective from ') + 1))
WHEN CHARINDEX('Effective from ', @STR) > 0 THEN SUBSTRING(@STR,CHARINDEX('Effective from ', @STR) + LEN('Effective from ') + 1, 60) ELSE NULL
END 'Start Date'
我只想查看 10/16/2024,所以我需要子字符串在 to 之前结束。
确实感觉你把这里的问题过于复杂化了。你的日期只有 10 个字符,那么为什么不直接找到日期的位置,然后获取后面的 10 个字符呢?像这样的东西:
DECLARE @STR AS varchar(1000) = 'CustomerID #101010 added. Fixed Price: 3.5555 Effective from 10/16/2024 to 03/31/2 SADFGZFGDA025 Deliveries: 100 Company Pricing Program: TEST 1 Pricing Plan Name: Test plan';
SELECT SUBSTRING(@STR,NULLIF(CHARINDEX('Effective from',@STR),0)+LEN('Effective from')+1,10);
所以我找到
'Effective from'
的位置(如果没有找到,则返回NULL
),加上字符串的长度'Effective from'
+1,然后返回接下来的10个字符。