How is the stuff function used in SQL Server?
The STUFF function in SQL Server is used to replace specific characters or strings at a given position within a string.
Syntax:
STUFF ( character_expression , start , length , replaceWith_expression )
Explanation:
- The string to be modified.
- start: specifies the start position of the character or string to be replaced.
- length: the size of the character or string to be replaced.
- new character or string used for replacement.
Suppose we have a string ‘Hello, world!’ and we want to replace the comma with a period, we can use the STUFF function.
SELECT STUFF('Hello, world!', 6, 1, '.');
The result will return ‘Hello, world!’.
Another example is replacing the middle three characters in the string ‘12345’ with ‘abc’, which can be done using the STUFF function.
SELECT STUFF('12345', 2, 3, 'abc');
The result will return ‘1abc5’.