Search

Showing posts with label Stuff. Show all posts
Showing posts with label Stuff. Show all posts

Thursday, August 11, 2011

Stuff

STUFF is another function that is hardly used, it is useful if you want to replace or add characters inside data Take a look at the code below. the first STUFF will replace X with 98765, the second STUFF will place 98765 before the X and the third stuff will replace X- with 98765
DECLARE @v VARCHAR(11)
    SELECT @v ='-X-'

    SELECT STUFF(@v, 2, 1, '98765'),
    STUFF(@v, 2, 0, '98765'),
    STUFF(@v, 2, 2, '98765')

The STUFF function is very handy if you need to insert dashes in a social security. You can accomplish that by using the function STUFF twice instead of using substring,left and right
DECLARE @v VARCHAR(11)
    SELECT @v ='123456789'

    SELECT @v,STUFF(STUFF(@v,4,0,'-'),7,0,'-')

Saturday, January 15, 2011

When to use STUFF instead of REPLACE – SQL Server

The STUFF function in SQL Server ‘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.
REPLACE on the other hand replaces all occurrences of a specified string value with another string value.
The STUFF function is useful when you are not sure of the characters to replace, but you do know the position of the character. I saw an excellent implementation of this function overhere by GMastros and Even. Here’s the code with a practical usage of STUFF:
CREATE FUNCTION [dbo].[fn_StripCharacters](    @String NVARCHAR(MAX),    @MatchExpression VARCHAR(255))RETURNS NVARCHAR(MAX)ASBEGIN    SET @MatchExpression =  '%['+@MatchExpression+']%'    WHILE PatIndex(@MatchExpression, @String) > 0        SET @String = STUFF(@String, PatIndex(@MatchExpression,@String), 1, '')    RETURN @StringENDSELECT dbo.fn_StripCharacters('a1$%s#22d&39#f4$', '^a-z')as OnlyAlphabets