Repeating characters in T-SQL LIKE condition

浪子不回头ぞ 提交于 2019-12-06 02:02:59

You can do this with the not carat ^, and a NOT LIKE expression.

So you say, where not like not non-alphanumeric ;) This works for standard numbers & characters:

declare @var as VARCHAR (150)
select @var = '123ABC'

if (@var NOT LIKE '%[^a-zA-Z0-9]%')
    print 'OK'
else
    print 'Not OK'

Edit: Thanks Martin for the collation hint, if you want the characters like ý treated as non-alphanumeric add in the COLLATE as below

declare @var as VARCHAR (150)
select @var = '123ABCý'

if (@var NOT LIKE '%[^a-zA-Z0-9]%' COLLATE Latin1_General_BIN ) 
    print 'OK'
else
    print 'Not OK'  

Will this help

Declare @t table (Alphanumeric VARCHAR(100))
Insert Into @t 
Select '123ABCD' Union All Select 'ABC' Union All 
Select '123'  Union All  Select  '123ABCý' Union All
Select 'a-z123' Union All  Select 'abc123' Union All
Select 'a1b2c3d4'


SELECT Alphanumeric
FROM @t 
WHERE Alphanumeric LIKE '%[a-zA-Z0-9]%' 
AND ( Alphanumeric NOT LIKE  '%[^0-9a-zA-Z]%' COLLATE Latin1_General_BIN) 
AND LEN(Alphanumeric)> 6 -- display records having more than a length of 6

//Result

Alphanumeric

123ABCD
a1b2c3d4

N.B.~ Used Martin's collation hint..Thanks

T-SQL doesn't support RegEx.

You can use SQL CLR to run such expression though.


Also try the LEN function:

if (LEN(@var) <= 150)
    print 'OK'
else
    print 'Not OK'  
Fedor Hajdu

T-SQL doesn't support regex, closest you can get is the PATHINDEX function that you can use to match specific characters, but you can't specify the count. You can try combining it with LEN function to check the length.

EDIT: Check this page for a few examples of PATINDEX.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!