SQL Server STUFF() Function
The SQL Server (Transact-SQL) STUFF() function inserts a substring into a string at a specified position for a certain number of characters.
If the specified position is not within the length of the string, this function will return a null string. If length is negative, a null string is returned. If length is longer than the string, deletion occurs up to the last character in the string. If length is zero, insertion occurs at position location and no characters are deleted.
Syntax
STUFF(string, position, length, substring)
Parameters
string |
Required. Specify the string to modify. |
position |
Required. Specify the position in string to insert substring. |
length |
Required. Specify the number of characters to replace in string. |
substring |
Required. Specify the substring to insert into string. |
Return Value
Returns the modified string.
Example 1:
The example below shows the usage of STUFF() function.
SELECT STUFF('Learning SQL is fun', 10, 3, 'SQL Server'); Result: 'Learning SQL Server is fun' SELECT STUFF('abcxyz', 4, 3, 'def'); Result: 'abcdef' SELECT STUFF('ABCPQR', 4, 3, 'abc'); Result: 'ABCabc'
Example 2:
Consider a database table called Employee with the following records:
EmpID | Name | City | Salary |
---|---|---|---|
FIN001 | John | London | 3000 |
FIN002 | Marry | New York | 2750 |
FIN003 | Jo | Paris | 2800 |
FIN004 | Kim | Amsterdam | 3100 |
FIN005 | Ramesh | New Delhi | 3000 |
FIN006 | Huang | Beijing | 2800 |
In the below query, the STUFF() function is used to change the records of EmpID column of the Employee table:
UPDATE Employee SET EmpID = STUFF(EmpID, 1, 3, 'FINCAD'); -- see the result SELECT * FROM Employee;
This will produce the following result:
EmpID | Name | City | Salary |
---|---|---|---|
FINCAD001 | John | London | 3000 |
FINCAD002 | Marry | New York | 2750 |
FINCAD003 | Jo | Paris | 2800 |
FINCAD004 | Kim | Amsterdam | 3100 |
FINCAD005 | Ramesh | New Delhi | 3000 |
FINCAD006 | Huang | Beijing | 2800 |
❮ SQL Server Functions