简体   繁体   中英

search for a matching string using part of the string in SQL

I current have one table whereby with a unique index of 'col_0' I have the same set of data for 2 different indexes. The problem is the copy function in my application automatically cuts of the description and adds "copied from at the end".

Example

Col_0 Description
A This is a very annoying application problem
B This is a very annoy (Copied from column a)

I just wanted to search for and then update B so it matches I've tried join it by part of the description.

So far I've tried CHARINDEX but I can't quite get it right.

I read your request thus: "Copied from column a)" means copied from the description of the record with col_0 = 'A'. And you want to update all "copied from .." descriptions with their original description.

In order to find the "copied from .." records I am using LIKE. To extract the col_0 value from the string I am using some string functions (mainly REVERSE + CHARINDEX to find the last occurrence of a blank and then SUBSTRING for the extraction).

update mytable upd
set description =
(
 select description
 from mytable orig
 where orig.col_0 = 
   substring(upd.description, 
             len(upd.description) - charindex(' ', reverse(upd.description)) + 2, 
             charindex(' ', reverse(upd.description) - 2
            )
)
where description like '%(Copied from column %)';

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