Pages

22 Apr 2012

SQL Pattern matching

MS SQL queries allows us to play with strings (pattern matching).
Let's create an employee table and insert values,


create table employees (id int identity(1,1), name varchar(256), primary key(id))


insert into employees values('James')
insert into employees values('Leon')


//now select will give following values
select * from employees
1 James
2 Leon 
  • if we need to query names starting 'J', we can use '%' to replace one or more characters. 
select name from employees where name like 'J%'
James

  • '%' can replace one ore more characters, however if we want to replace one character use '_'
select name from employees where name like '_eon'
Leon
  • if we want to query for names with a letter ranging between a group use '[]' 
select * from employees where name like '[h-k]%'
1 James
  • if we need to query for name with a letter not in a range use '[^]'
select * from employees where name like '[^h-k]%'
2 Leon

No comments:

Post a Comment