SQL Server 2016 How to use a simple Regular Expression in T-SQL?

前端 未结 2 776
粉色の甜心
粉色の甜心 2021-01-29 00:12

I have a column with the name of a person in the following format: \"LAST NAME, FIRST NAME\"

  • Only Upper Cases Allowed
  • Space after comma optional
2条回答
  •  情深已故
    2021-01-29 00:47

    First, case sensitivity depends on the collation of the DB, though with LIKE you can specify case comparisons. With that... here is some Boolean logic to take care of the cases you stated. Though, you may need to add additional clauses if you discover some bogus input.

    declare @table table (Person varchar(64), is_correct_format varchar(3) default 'NO')
    insert into @table (Person)
    values
    ('LowerCase, Here'),
    ('CORRECTLY, FORMATTED'),
    ('CORRECTLY,FORMATTEDTWO'),
    ('ONLY FIRST UPPER, LowerLast'),
    ('WEGOT, FormaNUMB3RStted'),
    ('NoComma Formatted'),
    ('CORRECTLY, TWOCOMMA, A'),
    (',COMMA FIRST'),
    ('COMMA LAST,'),
    ('SPACE BEFORE COMMA , GOOD'),
    (' SPACE AT BEGINNING, GOOD')
    
    
    update @table
    set is_correct_format = 'YES'
    where 
            Person not like '%[^A-Z, ]%'                                                    --check for non characters, excluding comma and spaces
        and len(replace(Person,' ','')) = len(replace(replace(Person,' ',''),',','')) + 1   --make sure there is only one comma
        and charindex(',',Person) <> 1                                                      --make sure the comma isn't at the beginning
        and charindex(',',Person) <> len(Person)                                            --make sure the comma isn't at the end
        and substring(Person,charindex(',',Person) - 1,1) <> ' '                            --make sure there isn't a space before comma
        and left(Person,1) <> ' '                                                           --check preceeding spaces
        and UPPER(Person) = Person collate Latin1_General_CS_AS                             --check collation for CI default (only upper cases)
    
    select * from @table
    

提交回复
热议问题