我有一个列名为人的列,格式如下:"最后一个姓名,第一个姓名"
我想使用正则表达式,如:[A-Z] +,[]?[A-Z] +但我不知道如何在T-SQL中执行此操作。在Oracle中,我会使用REGEXP_LIKE,是否有类似于SQL Server 2016的东西?
我需要以下内容:
UPDATE table
SET is_correct_format = 'YES'
WHERE REGEXP_LIKE(table.name,'[A-Z]+,[ ]?[A-Z]+');
答案 0 :(得分:2)
首先,区分大小写取决于DB的排序规则,但使用LIKE
可以指定大小写比较。有了......这里有一些布尔逻辑来处理你说的案例。但是,如果您发现了一些伪造的输入,则可能需要添加其他条款。
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
答案 1 :(得分:1)
tsql等价物可能如下所示。我没有保证这个解决方案的效率。
declare @table as table(name varchar(20), is_Correct_format varchar(5))
insert into @table(name) Values
('Smith, Jon')
,('se7en, six')
,('Billy bob')
UPDATE @table
SET is_correct_format = 'YES'
WHERE
replace(name, ', ', ',x')
like (replicate('[a-z]', charindex(',', name) - 1)
+ ','
+ replicate('[a-z]', len(name) - charindex(',', name)) )
select * from @table
可选空间难以解决,因此,由于它位于合法角色旁边,我只是在其中替换另一个合法角色。
TSQL没有提供那种重复模式&#39;正则表达式中的*或+,因此您必须对字符进行计数并在搜索模式中多次构建模式。
我将字符串拆分为逗号,计算前后的alpha值,并构建匹配的搜索模式。
笨重,但可行。