REPLACE function |
||||||||||||
REPLACE function
This example you can perform on the page with the DML - Data Manipulation Language - sublanguge of SQL including SELECT, INSERT, UPDATE and DELETE statements.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, 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:
You should be careful when using this method to calculating the number of spaces. Apart from the fact that LEN function does not take into account trailing spaces, the result also depends on data type. In the string "World Wide Web" there is 14 characters. Let's replace each space with 2-character string and calculate the length of the string before the replacement and after that:
We wanted to add 2 characters but are obtaining 88 instead of 16. This is due to the CHAR being strict data type, so the length of any string must have the specified value. We had specified 50 characters hence the value of variable will be padded by trailing spaces up to 50 characters as a whole. So we'll get (50-14)х2 = 72, and then 16 + 72 = 88. But if we'll declare the variable as VARCHAR(50), we obtain the desired result:
|