使用sql server验证字符串格式

时间:2017-08-14 15:09:37

标签: sql sql-server regex

检查字符串是否遵循正确的格式。正确的格式如下:

2个大写字母; 2位数; 1至30个字符的字母数字(不区分大小写) 例如GB29RBOS60161331926819,      GB29RBOS60161331926819A,      GB29RBOS60161331926819B1

到目前为止,这就是我所拥有的......

declare @accountNumber varchar(1000) = 'GB99AERF12FDG8AERF12FDG8AERF12FDG8'

select 
case when @accountNumber not like '[A-Z][A-Z][0-9][0-9][0-9a-zA-Z]{30}$' 
then 'ERROR' else null end

2 个答案:

答案 0 :(得分:3)

首先,您的结构采用区分大小写的排序规则。其次,SQL Server无法识别{}$,因此您必须重复该模式。但是,您最多需要30个字符,因此拆分这些部分可能是最佳解决方案:

select (case when len(@accountNumber) not between 5 and 34 or
                  @accountNumber not like '[A-Z][A-Z][0-9][0-9]%' or
                  right(@accountNumber, 34) like '%[^A-Za-z0-9]%'
             then 'ERROR' 
        end)

答案 1 :(得分:1)

我认为这应该有用......从John获取一些提示。

declare @table table (i varchar(36))
insert into @table
values
('GR09xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'),     --30 x's
('GR09xxxxxxxxxxxxxxxxxxxxxxxxxxxx'),       --28 x's
('GR09xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'),    --31 x's
('Gx09xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'),    --lower case 2'd letter
('G509xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'),    --digit second letter
('GRg9xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')     --charcater first number (3rd index)

select 
case 
    when i + replicate('a',case when 34-len(i) < 0 then 0 else 34-len(i) end) not like '[A-Z][A-Z][0-9][0-9]' + replicate('[a-zA-Z0-9]',30)
then 'ERROR' else null end
from @table