DiigIT | IT Community
No Profile Image
Welcome Guest
New User? Register | Login
SQL
IT Tags
DiigIT » SQL » qna

Need Help for Sql query

By: rekha singh | 31 Aug 2010 4:31 pm

Hi All,

I have a table with a field say username which is a char field (to
accomadate values like 1, 11nml, 3 and also abc12, xyz456 etc.). Since
username is a char field I get the output like

12
34
abc12
xyz456

But I would like to get the output like

11nml
abc12
xyz456

ie only alphanumeric values...
 

Comments

Here's one way:

SELECT * from mytable WHERE ASCII(myfield) between 65 and 90

This will exclude records where the first character of myfield is NOT
between A and Z . You should extend this to also include those between
a and z - just check the ASCII table.

Good luck
 

By: rekha singh | 31 Aug 2010

I would recommend using PATINDEX.

SELECT username
FROM usernametable
WHERE PATINDEX('%[ 0-9]%', username) > 0
AND PATINDEX('%[ A-Za-z]%' , username) > 0

PATINDEX finds the start of a patter in a string. By using that and including wildcards and some basic regular expressions you can test for numbers and letters. If both the test for the number and the letter returns a starting position > 0 (0 is returned when no match is found) then you will have the items you are looking for.
 

By: rekha singh | 31 Aug 2010

Use PATINDEX

http://msdn. microsoft. com/en-us/ library/ms188395 .aspx

SELECT *

FROM MyTable

WHERE PATINDEX('%[ ^0-9]%', MyColumn) > 0

AND PATINDEX('%[ ^a-zA-Z]% ', MyColumn) > 0
 

By: rekha singh | 31 Aug 2010

with
usernames as
(
select '1' username from dual union all
select '11nml' username from dual union all
select '3' username from dual union all
select 'abc12' username from dual union all
select 'xyz456' username from dual union all
select '12' username from dual union all
select '34' username from dual
)
select *
from usernames u
where not regexp_like( u.username, '^[[:digit:] ]+$')

Uglier, likely slower, but more portable...
with
usernames as
(
select '1' username from dual union all
select '11nml' username from dual union all
select '3' username from dual union all
select 'abc12' username from dual union all
select 'xyz456' username from dual union all
select '12' username from dual union all
select '34' username from dual
)
select *
from usernames u
where replace(replace( replace(replace( replace(
replace(replace( replace(replace( replace(
u.username
, '0', '') , '5', '')
, '1', '') , '6', '')
, '2', '') , '7', '')
, '3', '') , '8', '')
, '4', '') , '9', '') is not null
 

By: rekha singh | 31 Aug 2010

Leave a comment

Enter the text in the image
img
Can't read?
Type the characters you see in the picture below.


Close Move