0

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
)

returns NULL, while I would expect it to return 'z'.

Stuff

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.

Syntax

STUFF ( character_expression , start , length , replaceWith_expression )

Remarks

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
asked Oct 2, 2019 at 20:30

1 Answer 1

1

After closely reading the documentation while posting this question, I realized it told me the answer. I'm still posting it, since I hope it might be helpful to others in a similar predicament.

Per the documentation:

If start is negative or zero, a null string is returned. If start is longer than the first character_expression, a null string is returned. start can be of type bigint.

This means that, effectively, you can't use STUFF with an empty string (since any argument to start will result in a NULL string).

One workaround is to use a non-empty string, and delete the content. For the above example, you could use STUFF('a', 1, 1, 'z') to delete the initial character.

answered Oct 2, 2019 at 20:30

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.