11 out of 13 rated this helpful Rate this topic

STUFF (Transact-SQL)

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.

Topic link icon Transact-SQL Syntax Conventions


STUFF ( character_expression , start , length ,character_expression )
character_expression

Is an expression of character data. character_expression can be a constant, variable, or column of either character or binary data.

start

Is an integer value that specifies the location to start deletion and insertion. If start or length is negative, 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.

length

Is an integer that specifies the number of characters to delete. If length is longer than the first character_expression, deletion occurs up to the last character in the last character_expression. length can be of type bigint.

Returns character data if character_expression is one of the supported character data types. Returns binary data if character_expression is one of the supported binary data types.

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 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.

The following example returns a character string created by deleting three characters from the first string, abcdef, starting at position 2, at b, and inserting the second string at the deletion point.

SELECT STUFF('abcdef', 2, 3, 'ijklmn');
GO

Here is the result set.

--------- 
aijklmnef 

(1 row(s) affected)
Did you find this helpful?
(2000 characters remaining)
Community Content Add
Annotations FAQ
Information is not wrong
Above mentioned method is right and it talks about setting length as zero and not start index as zero. Setting Length as zero does not remove any character from the string
Insert instead of substitute/replace
At first sight it might not be clear directly how to insert a character (or a string) instead of substituting characters in the original string.

To insert a string, without replacing/substituting characters in the original string you need to specify a length of 0 (zero).
SELECT STUFF('abcghi', 4, 0, 'DEF');
-- this results in 'abcDEFghi'.

Wrong information - indices start at 1
In contrast to what is stated here, the index start has to be greater than 0; character indices start in 1 in T-SQL. Therefore 0 is not a valid start index, and STUFF also returns NULL.