Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best Sql Data Exception check REGEX

Tags:

sql

sql-server

I have a gas cert number column and want to check if any of them do not confor the format of a gas cert number . The format should be : WN/3333333/1 ( 2 LETTERS that should be WN followed by / and a 7 digit number then / and a single digit, like 1 and not 01 or 0001.

My thinking was to work out all the scenarios and solve them one by one. But the 1st step is working out what all the exceptions are by doing some super sql query .

Is there a good way of trying to identify the execptions using sql ?

like image 627
James Khan Avatar asked Dec 21 '25 23:12

James Khan


2 Answers

For a dynamic pattern match consider the following:

"A" represents any ALPHA and the "0" represents any DIGIT.

Declare @Patt varchar(150) ='AA/0000000/0'
Declare @Test varchar(150) ='WN/3333333/1'

Set @Patt = replace(replace(replace(@Patt COLLATE Latin1_General_BIN, 'A', '[A-Z]'), 'a', '[a-z]'), '0', '[0-9]')
Select case when @Test Like @Patt then 1 else 0 end

Returns 1 or 0

1    -- Pattern Match

Now, if the pattern would always be WN/..., the @Patt would be 'WN/0000000/0'

like image 136
John Cappelletti Avatar answered Dec 24 '25 20:12

John Cappelletti


SQL Server supports some basic regex functionality with LIKE. I think you can identify non conforming records by using a single LIKE expression.

SELECT column
FROM yourTable
WHERE column NOT LIKE 'WN/[0-9][0-9][0-9][0-9][0-9][0-9][0-9]/[0-9]'
like image 26
Tim Biegeleisen Avatar answered Dec 24 '25 19:12

Tim Biegeleisen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!