Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeating characters in T-SQL LIKE condition

Problem:
Limit the value of a VARCHAR variable (or a column) to digits and ASCI characters, but allow variable length.
This script will not yield required result:

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

if (@var LIKE '[a-zA-Z0-9]{0,150}')
    print 'OK'
else
    print 'Not OK'  

Anyone have idea how to do this?

like image 505
Nikola Avatar asked Jan 28 '26 10:01

Nikola


2 Answers

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'  
like image 76
Meff Avatar answered Jan 31 '26 01:01

Meff


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

like image 33
Niladri Biswas Avatar answered Jan 31 '26 01:01

Niladri Biswas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!