首页 > 解决方案 > PATINDEX 表达式

问题描述

我正在创建一个 patindex:

字符 1 必须为 Alpha 且非空格,其余字符应包含任意 AZ、az、空格或'-

 patindex('^ [A-Z]%[A-Za-z '-]','Worktester')

但这似乎不起作用

似乎 PATINDEX() 不允许这种模式匹配。

您能否告知这是否正确或任何可以帮助表达的链接?

谢谢

标签: sqlsql-servertsql

解决方案


有时使用模式匹配的诀窍是找到坏的,而不是好的,模式。要验证长度未知的字符串(而不是提取子字符串),您可以搜索不可接受字符的模式:

declare @Samples as Table ( Sample VarChar(16) );
insert into @Samples ( Sample ) values
  ( 'Worktester' ), ( 'Foo Bar' ), ( 'Voot-Plex' ),
  ( 'BR549' ), ( ' Spaced Out' ), ( 'low down' ), ( 'Oops!' );

select Sample,
  -- Check the first character for uppercase alpha only.
  PatIndex( '[^A-Z]%', Sample collate Latin1_General_BIN ) as Part1,
  -- Check the remaining characters for any mix of alpha, space and hyphen.
  PatIndex( '_%[^-A-Za-z ]%', Sample collate Latin1_General_BIN ) as Part2,
  -- Put it together into a single status.
  case
    when PatIndex( '[^A-Z]%', Sample collate Latin1_General_BIN ) = 0 and
      PatIndex( '_%[^-A-Za-z ]%', Sample collate Latin1_General_BIN ) = 0 then 'Good'
    else 'Bad' end as Status
  from @Samples;

请注意,默认排序规则往往不区分大小写。Part1尝试通过删除显式排序规则来更改行。


推荐阅读