Use string functions of SQL Server STUFF

Preface:

Recently, a practice exercise is the student enrollment data in the student table [st_id] second and third character field to delete, and then insert a new string in this position, "200900", in fact, replace the meaning of a new generation String.

STUFF function string into another string. It deletes the specified character length from the start position of a character string; and a second string into the start position of a character string.

 

grammar:

STUFF ( character_expression , start , length , replaceWith_expression )

Parameter Description:

character_expression
expression of character data. character_expression can be a constant, variable, it can be a character or binary column data column.
start
an integer value to specify delete and insert start point. If start is negative or zero, an empty string is returned. If the length is greater than the first start character_expression, empty string is returned. start of type can be bigint.
length
An integer specifying the number of characters to delete. If the length is negative, a null string is returned. If the length is greater than the length of the first character_expression, then up to the last character_expression delete the last character. If the length is zero, insert content before the first character string. length of type can be bigint.
replaceWith_expression
expression of character data. character_expression can be a constant, variable, it can be a character or binary column data column. This expression began to replace character_expression length characters from start. If replaceWith_expression is NULL, delete characters without inserting any content.

Return type:

If character_expression is one of the supported character data types, character data is returned. If character_expression is one of the supported binary data types, binary data is returned.

 

Remarks:

If the start position or the length value is negative, or greater than the start position of a length of the string, the string is returned Null. If the starting position is 0, Null value is returned. To remove a length greater than the length of the first string, the first string deleted to the first character.

If the resulting value is greater than the maximum supported return type of error is thrown.

 

Example 1:

The following example is deleted from the first start position the second string of Sungeek (u) three characters, then delete the inserted position in the second string, to create and return a string.

SELECT STUFF('SUNGEEK', 2, 3, '20190814');  
GO

 

Example 2:

The second and third characters student enrollment data in the student table [st_id] field to delete, and then insert a new string in this position, "200900" is actually meant to replace, creating a new string.

select [st_id],[st_nm],
stuff([st_id],2,2,200900) as 新学号
from [dbo].[student]

 

Guess you like

Origin www.cnblogs.com/Sungeek/p/11352242.html