Tuesday, October 21, 2008

Pattern Matching with the ESCAPE Clause

We use % and _ in wildcard search with like clause but, some time we need to search the same chars from the string. So below example shows how to tackle this situation
For that we can use the ESCAPE caluse with like clause. we just have to define a ESCAPE char that will ESCAPE the next char from search string.


if object_id('test','U') is not null
drop table TASK_DETAIL
GO
create table task_detail
(
id int identity primary key,
name nvarchar(200),
task ntext
)
insert into task_detail(name,task)
select 'Chintak','review 100%_managemnet 20%_performance tuning 30%'
union all
select 'Chirag','coding 100%_unit testing 30%'
union all
select 'Ahish','management 100 hours'


-- To find out who is working 20% on any task
select id,name,task from task_detail where task like '%20!%%' ESCAPE '!'
--this will give the first row

--To find out employees working 100% on one task and also works on other task
select id,name,task from task_detail where task like '%100!%!_%' ESCAPE '!'
--this will give the first two rows