Wednesday, April 4, 2012

LIKE using Wildcard character

Wildcard character are %, _ (underscore), [ ], [^]

I) Percent (%) - Replaces any number of characters (including 0 characters) in the string.
For example, %at would match at, cat, hat, and that.

1) Now we want to select the persons living in a city that starts with "sa" from the "Persons" table.
SELECT * FROM Persons WHERE City LIKE 'sa%'

2) Now, we want to select the persons living in a city that contains the pattern "nes" from the "Persons" table.
SELECT * FROM Persons WHERE City LIKE '%nes%'

3) Now we want to select the persons living in a city that ends "sa" from the "Persons" table.
SELECT * FROM Persons WHERE City LIKE '%sa'

II)Underscore(_) Replaces exactly one character in the string. For example, _at would
match cat and hat, but it would not match that or at.

Now we want to select the persons with a first name that starts with any character, followed by "la" from the "Persons" table.
SELECT * FROM PersonsWHERE FirstName LIKE '_la'
Output of Firstname is Ola

Next, we want to select the persons with a last name that starts with "S", followed by any character, followed by "end", followed by any character, followed by "on" from the "Persons" table.

III) Square Brackets ([ ]) Replaces any one character within a set or a range of characters.
A set is frequently displayed as a straight list of characters, for example, [abcd]; but the
characters can be separated by commas to add clarity, for example, [a,b,c,d]. A range is
separated by a dash, for example, [a–d]. Each of these three options includes all rows
where the specified character is an a, b, c, or d.

IV) Caret (^) Any character not within a set or range of characters. For example, [^a-d]
would be equal to [e–z].

How do I search for special characters (e.g. %) in SQL Server?

SELECT columns FROM table WHERE column LIKE '%[%]%'

or

Escape_character:

Is a character that is put in front of a wildcard character to indicate that the wildcard should be interpreted as a regular character and not as a wildcard. escape_character is a character expression that has no default and must evaluate to only one character.

SELECT columns FROM table WHERE column LIKE '%\%%' ESCAPE '\'

No comments: