15.8.08

String Pattern matching in SQL Server

Lets see some interesting facts in SQL Server. Today we will see pattern matching concept in SQL Server.
I have tried to create a table name VenkatTable and inserted some rows into it,



Code Snippet
create table VenkatTable( Col1 varchar(5) )
insert into VenkatTable values('_Sas')
insert into VenkatTable values('Sas_')
insert into VenkatTable values('S_us')
insert into VenkatTable values('Sas')
insert into VenkatTable values('Sa_s')
Now I need to fetch the data as per the below condition,



Real Query
select * from VenkatTable where Col1 Like '%Sa_%'


Without executing the above code. Can you tell the number of rows retrieved by the above query?


In the above query, a small trick is embedded, SQL Server wont check for the string having "Sa_"
Because, the character "_" is nothing but a single character matching.
The above query will fetch all the strings matching the word Sa, starting with 0 or any number of characters
and should have 1 character after Sa and its followed by 0 or any number of characters.

Happy Learning!!!

Regards,

Venkatesan Prabu .J

No comments:

Post a Comment