loading..
Русский    English
02:09

REPLACE function

REPLACE function

  1. REPLACE (string_expression1 , string_expression2 , string_expression3)
replaces in the string_expression1 all the occurrences of the string_expression2 with the string_expression3. This function is absolutely helpful in UPDATE operators, if we should change the content of the column. For example, let we are needed to replace all the spaces with the hyphen in the names of the ships. Then we can write

  1. UPDATE Ships
  2. SET name = REPLACE(name, ' ', '-')

Notes:

This example you can perform on the page with the DML exercises, where the questions on updating the data are admitted

However this function can also find its appliance in more non-trivial cases. Let's determine how many times the letter "a" is used in a name of a ship. The idea is quite easy: let's replace every searching letter with any two characters, and after that we'll calculate the difference of lengths of the string we got and the source string. So,

Console
Execute
  1. SELECT name, LEN(REPLACE(name, 'a', 'aa')) - LEN(name)
  2. FROM Ships

And what if we need to determine the number of occurrences of a random sequence of characters that, say, we get as a parameter of a stored procedure? In this case we should complement the used above algorithm with the division on a number of a characters in a sequence:

  1. DECLARE @str AS VARCHAR(100)
  2. SET @str='ma'
  3. SELECT name, (LEN(REPLACE(name, @str, @str + @str)) - LEN(name))/LEN(@str) FROM Ships

Bookmark and Share
The book was updated
yesterday
©SQL-EX,2008 [Evolution] [Feedback] [About] [Links] [Team]
All right reserved.
Rambler's Top100