在sqlserver中使用Like进行模式匹配
我的表中有一列,其值如下在sqlserver中使用Like进行模式匹配,sql,sql-server,regex,database,Sql,Sql Server,Regex,Database,我的表中有一列,其值如下 1VT34 5AB37-A 1XY38-2 0VT31-2 Science History01 111111 我只想获取那些字母数字格式的值,它们以一个数字开始(从1到任意数字),它们应该以一个数字结束,如果任何数字带有“-”,那么它应该是这种格式->1VT37-a,1VT38-2。“-”后面的字符可以是1-9之间的任何数字,也可以是A 从上述值中,我希望我的查询仅获取 1VT34 5AB37-A 1XY38-2 我使用like操作符编写了以下查
1VT34
5AB37-A
1XY38-2
0VT31-2
Science
History01
111111
我只想获取那些字母数字格式的值,它们以一个数字开始(从1到任意数字),它们应该以一个数字结束,如果任何数字带有“-”,那么它应该是这种格式->1VT37-a,1VT38-2。“-”后面的字符可以是1-9之间的任何数字,也可以是A
从上述值中,我希望我的查询仅获取
1VT34
5AB37-A
1XY38-2
我使用like操作符编写了以下查询-
select * from Details where Name like '[^0A-Z]%'
但它也得到了111111,这是我不想要的
然后我写这篇文章只是为了获取字母数字
select * from Details where Name like '[^0A-Z]%' and Name like '[^0-9]'
但它什么也收不到
为了获取带有“-”的名称,我编写了以下代码
select * from Details where Name like '[^0A-Z]%' and (Name like '%-A' or Name like '%-[0-9]')
但它只吸引了我
5AB37-A
1XY38-2
而不是其他人
为了避免这种情况,我使用了另一个使用UNION的查询-
select * from Details where Name like '[^0A-Z]%' union
select * from Details where Name like '[^0A-Z]%' and Name like '%-A'
但111111仍在获取中。您可以尝试以下方法-
select * from Details where Name like '[1-9][A-Z]%'
对于此示例数据,模式应为:
where Name like '[1-9]%[A-Z]%[A1-9]'
或:
请参阅。结果:
使用SQL Server获取精确匹配非常棘手。为了正确起见,您可以考虑如下名称:
1VT34$$
1VT34-1-1
还有其他的怪事。因此,根据您的描述:
我只想获取那些字母数字格式的值,它们以一个数字开始(从1到任意数字),它们应该以一个数字结束,如果任何数字带有“-”,那么它应该是这种格式->1VT37-a,1VT38-2。“-”后面的字符可以是1-9之间的任何数字,也可以是A
编辑了我的问题,名称不一定包含VT。它可以是任何内容。@Anonymous,我已经更新了我的答案-你可以给出一个tryPerfect。谢谢。第二个选项还避免了使用union,从而使我的查询简短而有效。
Name
-------
1VT34
5AB37-A
1XY38-2
1VT34$$
1VT34-1-1
where name not like '%[^-a-zA-Z0-9]%' and -- only alphanumeric and hyphen
name like '[0-9]%' and -- starts with a digit
name not like '%-%-%' and -- at most one hyphen
( (name like '%[0-9]' and name not like '%-%') or -- ends with a number if no hyphen
name like '%-[A1-9]' -- other ends with hyphen and A or 1-9
)