Sunday 23 July 2017

Escape % Sign from Like clause in sql server

Read LIKE clause in SQL serverhere click here

In SQL Server like command is basically used for use wild card character in where clause. The most useful wild character is % . But what happen when in our column already contains % in column data. See the example if in table value have %. Like Bagesh%kumar , Rajesh%Kumar etc.
I am creating a simple table.
create table EmpTemp
( ID int identity(1,1),
  Name varchar(50)
 )
Now I am inserting some records.
Insert into EmpTemp ( name) Values
('Bagesh%Kumar'),
('Rajesh%kumar'),
('Mashesh%Kumar'),
('Manishkumar')
 I want to fetch all record which have h%k
SELECT * FROM EmpTemp WHERE name like '%h%k%'

See the output.
  

That is not a correct output.
See below sql query.
SELECT * FROM EmpTemp WHERE name like '%h[%]k%'
See the output
  

Get the expected output.

We need to write the % in [] (squire bracket) then it will work.

No comments:

Post a Comment

If you have any doubt, please let me know.

Popular Posts