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?
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:
Edit: Thanks Martin for the collation hint, if you want the characters like ý treated as non-alphanumeric add in the COLLATE as below
T-SQL doesn't support RegEx.
You can use SQL CLR to run such expression though.
Also try the LEN function:
Will this help
//Result
Alphanumeric
N.B.~ Used Martin's collation hint..Thanks
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 withLEN
function to check the length.EDIT: Check this page for a few examples of
PATINDEX
.