Using REPLACE to remove characters from Selected positions in your SQL Server column string

I faced a simple but challenging issue recently. A table had a nvarchar column with data in the following format: 91-39-45-3845

The Column was expected to be in the format 913945-3845 with the first two hyphens (-) removed.

Here’s how the requirement was achieved:

DECLARE @TT table
(
ItemDescription nvarchar(20)
)

INSERT INTO @TT VALUES('91-39-45-3845')
INSERT INTO @TT VALUES('45-24-85-5643')
INSERT INTO @TT VALUES('57-54-92-8835')

SELECT * FROM @TT

UPDATE @TT
SET ItemDescription = REPLACE(SUBSTRING(ItemDescription, 1, 7), '-', '')
+ SUBSTRING(ItemDescription, 8, DATALENGTH(ItemDescription))

SELECT * FROM @TT

OUTPUT:

Before the query was run

image

After the query was run

image

2 comments:

  1. Another method is

    select stuff(replace(ItemDescription,'-',''),7,0,'-') from @TT

    You can easily convert this to update

    Madhivanan
    http://beyondrelational.com/blogs/madhivanan

    ReplyDelete