MS-SQL : CHARINDEX Vs PATINDEX
CHARINDEX and PATINDEX functions return the starting position of a pattern you specify. PATINDEX can use wildcard characters while CHARINDEX cannot.
Imagine you have a BoxNo field with below values in your table.
BoxNo
——
BOX1
BOX3
BOX4
BOX30
BOX123
Using MS-SQL syntax,You will have a few options to separate those values into number.
1.)
select BoxNo,substring(BoxNo,CHARINDEX(’X',BoxNo)+1,len(BoxNo)) as No from #temp
2.)
select BoxNo,replace(BoxNo,’BOX’,”) as No from #temp
You will have a result like below:
BoxNo No
—— ——
BOX1 1
BOX3 3
BOX4 4
BOX30 30
BOX123 123
Now, again, imagine your BoxNo having values like below. The above SQL is not valid anymore since the pattern is different already.(These are my imaginary data, real data will not have something like below. :))
BoxNo
———
BB12
Box1222
MyBox35
My13
MyBoXx123
This is the time where we need to use PATINDEX instead of CHARINDEX. Your query will look like more complex already.But with same expected result of course.
Using below SQL,
select BoxNo,substring(BoxNo,PATINDEX(’[A-Z,a-z]%’,BoxNo)+(PATINDEX(’%[0-9]%’,BoxNo)-1),len(BoxNo)) as No from #temp
Will produce something like below.
BoxNo No ----- ----- BB12 12 Box1222 1222 MyBox35 35 My13 13 MyBoXx123 123
In real live,you will have different type of data with different pattern…this is the time where reqular expression will be your life saver.
Till then, happy SQL’ING
If you're new here, you may want to subscribe to my RSS feed or get my latest post directly in your mailbox. Thanks for visiting !
![[Ask]](http://www.arejae.com/blog/wp-content/plugins/bookmarkify/ask.png)
![[Bloglines]](http://www.arejae.com/blog/wp-content/plugins/bookmarkify/bloglines.png)
![[del.icio.us]](http://www.arejae.com/blog/wp-content/plugins/bookmarkify/delicious.png)
![[Digg]](http://www.arejae.com/blog/wp-content/plugins/bookmarkify/digg.png)
![[Furl]](http://www.arejae.com/blog/wp-content/plugins/bookmarkify/furl.png)
![[StumbleUpon]](http://www.arejae.com/blog/wp-content/plugins/bookmarkify/stumbleupon.png)
![[Technorati]](http://www.arejae.com/blog/wp-content/plugins/bookmarkify/technorati.png)


using this to solve sql injection problem for the replacement script.. actually it’s ur script.. hehehe
..
thanks for dropping by.
all these seems gibberish to me.
owh ya, imma mysql user. not really familiar with mssql syntax.
hehehe.
sql injection, cool topic to tackle.
@oryzana: so mmg life saver lar yer.ehehe.:)
@noris: I am mssql user by day,mysql user by night and other database by request.
I’m thinking to post about SQL Injection that kitaorg kena.yep..sudah kena HACK daa….now tengah kelam kabut to get all the thing back to normal.