简体   繁体   中英

Matching string removal from another column

I am working in SQL Server 2014. I have 2 columns in a table named Gallery Name and Address . Below is my sample data from this table.

Gallery Name           Address
--------------------------------------------------------------
Boltelang              Boltelang street 12, Paris
BERG Contemporary      BERG Contemporary gorge ave, New York

Like this, I have a total of 207 records. Now the issue is that the data of column Gallery Name is being repeated in address column which I want to remove from address column. So it should be like this in

Gallery Name          Adress
--------------------------------------------
Bltelang              street 12, Paris
BERG Contemporary     gorge ave, New York

I have no clue which function I can use in SQL Server to achieve this

Answer to your query is to use REPLACE like following.

UPDATE TABLE_NAME 
SET [Address] = REPLACE([Address], [Gallery Name],'')

Note : In above query, REPLACE will replace all the occurrences of [Gallery Name] in [Address].

There can be scenario where you need to replace only the first occurance , not if it exists somewhere in the middle. In that case you can try like following.

 UPDATE T SET  [Address]= 
         LTRIM(STUFF([Address], CHARINDEX([Gallery Name], [Address]), LEN([Gallery Name]), ''))
    from TABLE_NAME T
    WHERE [Address] LIKE [Gallery Name] +'%'

I would go for:

update t
    set address = stuff(address, 1, len(gallery_name) + 1, '')
    where address like gallery_name + ' %';

These cover the examples in your question, where the gallery name is at the beginning of the address followed by a space. I am very conservative in making such changes. If you have another pattern, then you can run another update to fix those.

You want to be careful using REPLACE() , in case the address repeats the gallery name:

New York     New York 10 New York Ave

Assuming it's only needed when the "Gallery Name" is at the start of the "Address".

To correct the addresses in the table

UPDATE [YourTable]
SET [Address] = LTRIM(REPLACE([Address], [Gallery Name],''))
WHERE [Address] LIKE CONCAT([Gallery Name],'%')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM