1

How do i replace set of character in a table?

ColumnA
%%1234UIT
!!1234TTT
678@@PPP

Currently I am using

`replace(replace(replace([BLOCK_NAME],'%%',''),'!!',''),'@@',''),1,LEN(BLOCK_NAME)-1`
OR
replace(replace(replace(substring([BLOCK_NAME],1,LEN(BLOCK_NAME)-1),'**',''),'##',''),'$$','')
Expected OUTPUT:
1234UIT
123TTT
678PPP
4
  • Are you trying to remove all non-numeric characters? Commented Oct 18, 2013 at 6:54
  • What's the expected output? The expression you've shown is incomplete - it looks like you've stripped out maybe a SUBSTRING call? Because your expression currently is <nested replace>,number,number Commented Oct 18, 2013 at 6:55
  • @unlimit no just those specified characters. Commented Oct 18, 2013 at 7:01
  • @Damien_The_Unbeliever you are right. I escaped substring. I just want to know if there is single function doing all the replacing. Commented Oct 18, 2013 at 7:03

3 Answers 3

1

This should work for your problem, it removes all non numeric characters from the record. You can create a sql function to be called from your query.

WHILE PATINDEX('%[^0-9]%', @strText) > 0
BEGIN
    SET @strText = STUFF(@strText, PATINDEX('%[^0-9]%', @strText), 1, '')
END
RETURN @strText
Sign up to request clarification or add additional context in comments.

Comments

1

You can create a function as:

CREATE FUNCTION [dbo].[fn_RemoveCharacters]
(
    @Str NVARCHAR(MAX), 
    @MatchExpression VARCHAR(255)
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
    SET @MatchExpression =  '%['+@MatchExpression+']%'

    WHILE PatIndex(@MatchExpression, @Str) > 0
        SET @Str = Stuff(@Str, PatIndex(@MatchExpression, @Str), 1, '')

    RETURN @Str

END

Go 

and then call it as:

SELECT [dbo].[fn_RemoveCharacters](ColumnA, '%%!!@@') as ColumnA
from table1

Hope this helps!!!

Comments

1

Please refer how to remove non-numeric/non-alphanumeric characters from string

CREATE FUNCTION [fnRemoveNonNumericCharacters](@strText VARCHAR(1000))
RETURNS VARCHAR(1000)
AS
BEGIN
    WHILE PATINDEX('%[^a-z0-9]%', @strText) > 0
    BEGIN
        SET @strText = STUFF(@strText, PATINDEX('%[^a-z0-9]%', @strText), 1, '')
    END
    RETURN @strText
END

select data using the created function

SELECT 
    dbo.fnRemoveNonNumericCharacters(BLOCK_NAME)
FROM 
    YourTable

OR

;WITH T as(
  SELECT STUFF(BLOCK_NAME, PATINDEX('%[^a-z0-9]%', BLOCK_NAME), 1, '') BLOCK_NAME from YourTable
  UNION ALL
  SELECT STUFF(BLOCK_NAME, PATINDEX('%[^a-z0-9]%', BLOCK_NAME), 1, '') BLOCK_NAME from T where PATINDEX('%[^a-z0-9]%', BLOCK_NAME) > 0
)
select 
    * 
from 
    T 
where PATINDEX('%[^a-z0-9]%', BLOCK_NAME) = 0

I prefer the second method using CTE without a user-defined function.

Comments

Your Answer

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.