首先,區分大小寫取決於數據庫的整理,雖與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
TSQL不支持正則表達式。你需要爲此使用CLR。或者是一個沒有正則表達式的更復雜的TSQL表達式。雖然你可能想看到[Falsehoods程序員相信姓名](http://www.kalzumeus.com/2010/06/17/falsehoods-programmers-believe-about-names/)。 –
在SQL Server中不是標準的。但是請查看[SQL#](https://sqlsharp.com/features/)(請參閱RegEx)。 –
這是用於輸入驗證嗎? – scsimon