I am trying to parse a string column matching it against several patterns. I have code that does not produce the desired results.
This is a sample table:
-- demo data
IF OBJECT_ID('dbo.Input', 'U') IS NOT NULL DROP TABLE dbo.Input
GO
CREATE TABLE [dbo].[Input]
(
[PromotionCode] [char](10) NOT NULL,
[Description] [char](30) NULL
CONSTRAINT [PK_Input] PRIMARY KEY CLUSTERED (PromotionCode)
)
GO
INSERT INTO dbo.Input (PromotionCode, Description) Values ('1709106-01', 'Good Gums 10% /M100/'), ('1708162-01', 'PURE Santevia 6% /M33/E33/R33/'), ( '1709164-01', 'Sovereign 10% /M50/E50/'),( '6031709-04', 'VS JF Powder 240g /M7/R3/E10/')
And this is my query:
-- parse description using patindex
select PromotionCode, [Description],
--patindex('%/M[0-9][0-9]/%', [Description]) as 'WWW',
--substring([Description], patindex( '%/M[0-9][0-9]/%', [Description]) + 2, 2) as 'XXX',
--parse(substring([Description], patindex( '%/M[0-9][0-9]/%', [Description]) + 2, 2) as float using 'en-US') as 'ZZZ',
CASE
WHEN patindex('%/M[0-9][0-9][0-9]/%', [Description]) = 0 then 0
WHEN patindex('%/M[0-9][0-9][0-9]/%', [Description]) > 0 then parse(substring([Description], patindex( '%/M[0-9][0-9][0-9]/%', [Description]) + 2, 3) as float using 'en-US')
ELSE (
CASE
WHEN patindex('%/M[0-9][0-9]/%', [Description]) = 0 then 0
WHEN patindex('%/M[0-9][0-9]/%', [Description]) > 0 then parse(substring([Description], patindex( '%/M[0-9][0-9]/%', [Description]) + 2, 2) as float using 'en-US')
ELSE (
CASE
WHEN patindex('%/M[0-9]/%', [Description]) = 0 then 0
WHEN patindex('%/M[0-9]/%', [Description]) > 0 then parse(substring([Description], patindex( '%/M[0-9]/%', [Description]) + 2, 1) as float using 'en-US')
ELSE NULL
END)
END)
END [MCB]
from dbo.Input
It is looking for an Mxxx
token where xxx
is a number, and is supposed to extract and return the number.
The desired results for my data sample are:
PromotionCode Description MCB 1708162-01 PURE Santevia 6% /M33/E33/R33/ 33 1709106-01 Good Gums 10% /M100/ 100 1709164-01 Sovereign 10% /M50/E50/ 50 6031709-04 VS JF Powder 240g /M7/R3/E10/ 7
What I get instead is:
PromotionCode Description MCB 1708162-01 PURE Santevia 6% /M33/E33/R33/ 0 1709106-01 Good Gums 10% /M100/ 100 1709164-01 Sovereign 10% /M50/E50/ 0 6031709-04 VS JF Powder 240g /M7/R3/E10/ 0
How to resolve the problem?