在SQL Server中使用patindex检查六个连续的数值

时间:2018-06-15 14:38:31

标签: sql sql-server tsql

我需要检查一个字符串是否在带有PATINDEX函数的字符串中有6个连续数值。

示例(如果符合6位数,则在括号中显示数字):

case 1 - s24334fth06 
case 2 - 234567tgf       (234567)
case 3 - t443786ftu03    (443786)
case 4 - tt43456

预期结果:

case 1 - 0   (it has only 5 continuous numeric values, so no index is given)
case 2 - 1   
case 3 - 2  
case 4 - 0

我试过

PATINDEX('%[0-9]{6}%', @string)

它为所有情况提供0。

3 个答案:

答案 0 :(得分:3)

您实际上可以在这里使用LIKE运算符:

SELECT *
FROM yourTable
WHERE col LIKE '%[0-9][0-9][0-9][0-9][0-9][0-9]%';

SQL Server几乎没有内置的正则表达式支持,但他们试图通过使用一些正则表达式功能增强LIKE来部分补偿它。

答案 1 :(得分:2)

您可以使用:

PATINDEX('%[0-9][0-9][0-9][0-9][0-9][0-9]%', @string)

<强> DBFiddle Demo

提取(第一次出现):

SELECT c, 
  SUBSTRING(c,NULLIF(PATINDEX('%[0-9][0-9][0-9][0-9][0-9][0-9]%', c),0), 6) AS r
FROM tab;

<强> DBFiddle Demo2

┌──────────────┬────────┐
│      c       │   r    │
├──────────────┼────────┤
│ s24334fth06  │ null   │
│ 234567tgf    │ 234567 │
│ t443786ftu03 │ 443786 │
│ tt43456      │ null   │
└──────────────┴────────┘

答案 2 :(得分:2)

为什么要使用patindex()代替likecase

select t.*,
       (case when col like '%[0-9][0-9][0-9][0-9][0-9][0-9]%' then 1 else 0 end) as six_flag
from t;