When working on answering another question (on SO), I came across some unexpected (to me) behavior with the STUFF function.
SELECT STUFF ( 'a', -- character expression 1, -- start 1, -- length 'z' -- replaceWith_expression )
NULL, while I would expect it to return 'z'.
The STUFF function inserts a string into another string. It deletes a specified length of characters in the first string at the start position and then inserts the second string into the first string at the start position.
STUFF ( character_expression , start , length , replaceWith_expression )
If the start position or the length is negative, or if the starting position is larger than length of the first string, a null string is returned. If the start position is 0, a null value is returned. If the length to delete is longer than the first string, it is deleted to the first character in the first string.
An error is raised if the resulting value is larger than the maximum supported by the return type.
Per the documentation, there are a number of reasons why a NULL string would be returned:
- If start is longer than the first character_expression
- If start is negative or 0
- If length is negative