The differences between STUFF, REPLACE and SUBSTRING functions is one of the most common interview question. By using the STUFF, REPLACE and SUBSTRING functions we can modify the strings as per our requirement.
STUFF():
STUFF is used to replace the part of string with some other string OR It delete a specified length of characters within a string and replace with another set of characters.
Syntax:
STUFF():
STUFF is used to replace the part of string with some other string OR It delete a specified length of characters within a string and replace with another set of characters.
Syntax:
STUFF(string_expression , start, length, string_expression2)
string_expression : represents the string in which the stuff is to be applied.
start : indicates the starting position of the character in string_expression.
length : indicates the length of characters which need to be replaced.
string_expression2 : indicates the string that will be replaced to the start position.
Example:
start : indicates the starting position of the character in string_expression.
length : indicates the length of characters which need to be replaced.
string_expression2 : indicates the string that will be replaced to the start position.
Example:
- DECLARE @str VARCHAR(35) = 'ABCDEFGH'
- SELECT @str, STUFF(@str,4,5,'_STUFF')
REPLACE():
REPLACE is used to replace all the occurrences of the given pattern in a string.
Syntax
REPLACE (string_expression, replace, string_expression2)
string_expression : Specifies the string that contains the substring to replace all instances of with another.
Replace : Specifies the substring to locate.
string_expression2 : Specifies the substring with which to replace the located substring.
Example:
Replace : Specifies the substring to locate.
string_expression2 : Specifies the substring with which to replace the located substring.
Example:
- DECLARE @str VARCHAR(35) = 'ABCDEFGH'
- SELECT @str, REPLACE(@str,'DEFGH','_REPLACE')
SUBSTRING():
SUBSTRING returns the part of the string from a given string_expression.
Syntax
SUBSTRING (string_expression, start, length)
Example:
- DECLARE @str VARCHAR(35) = 'ABCDEFGH'
- SELECT @str, SUBSTRING(@str,1,3)
Summary
Lets take an example to describe STUFF, REPLACE and SUBSTRING functions.
Example:
- DECLARE @str VARCHAR(35) = 'ABCDEFGH'
- SELECT @str, STUFF(@str,4,5,'_STUFF')
- SELECT @str, REPLACE(@str,'DEFGH','_REPLACE')
- SELECT @str, SUBSTRING(@str,1,3)
No comments:
Post a Comment