Asked By
Toasty Guru
0 points
N/A
Posted on - 10/12/2016
MY SQL database is a popular open source database. Usually administrators install it on the Server OS. Like other programming language it also has syntaxes and definitions. How can we use like in SQL Server 2012?
SQL Server 2012 To Create Web Based Application Using SQL.
Like condition is used to perform pattern matching using the syntax.
SYNTAX:
Expression LIKE pattern [ ESCAPE ‘escape_character’]
Expression consists of a character like column or field.
Pattern consists of a character expression that has the pattern matching.
The following patterns can be chosen:
‘%’ allows matching any string of any length.
‘-‘allows to match a single character.
‘[]’ allows to match any character in [].
‘[^]’ allows to match any character in [^]. Escape_character allows testing for the literal instances.
EXAMPLES:
Using %
• We wish to find all the names of students starting with A.
SELECT *
FROM students
Where last_name LIKE ‘A%’;
• We wish to find the names having z in the last name.
SELECT *
FROM persons
WHERE last_name LIKE ‘%z%’;
Using _
• We wish to get the names having 4 characters in the first name and the first two letters are Ad and last character is m.
SELECT *
FROM students
Where first_name LIKE ‘Ad_m’;
• We wish to find an student number when we have 3 digits out of 4.
SELECT *
FROM students
WHERE student_number LIKE’145_’;
Using []
• We wish to get the names where the name has 5 letters. First two are R and H and the last two are P and Q. the middle letter is either Y or M.
SELECT *
FROM students
WHERE first_name LIKE ‘RH[YM]PQ’;
Using [^]
• We wish to get the names where the name has 5 letters. First two are R and H and the last two are P and Q. the middle letter is neither Y nor M.
SELECT *
FROM students
WHERE first_name LIKE ‘RH [^YM] PQ’;
USING THE NOT OPERATOR
• We wish to find all the names of students not starting with A.
SELECT *
FROM students
Where last_name NOT LIKE ‘A%’;
USING THE ESCAPE CHARACTER
• We wish to find a% or a_ character.
SELECT *
FROM students
Where secret_hint LIKE ‘678! %898’ ESCAPE ‘!’;
This will escape the ‘!’ character and return the students with secret_hint as 678%898