简体   繁体   中英

Update field in table for all records using a select statement

A previous developer created a table that stores the absolute path to files in our server. I want to convert them to relative paths instead.

I already wrote the portion that properly strips the string down to a relative path. My issue is understanding how to basically update each record, with a new version of its own string.

Here is what I originally tried:

UPDATE LFRX_Attachments
    SET [File] = (SELECT TOP 1 SUBSTRING([File], PATINDEX('%Files\%', [File]) + 6, LEN([File]))
                     FROM LFRX_Attachments A
                     WHERE [Type] = 4 AND AttachmentId = A.AttachmentId)

However, this tanked in epic fashion by just overwriting every record to have the value of the first record in the table. Any suggestions?

UPDATE LFRX_Attachments
SET [File] = SUBSTRING([File], PATINDEX('Files\', [File]) + 6, LEN([File]))
WHERE [Type] = 4 

从可读性/维护性的角度来看,最好选择要更改的数据,然后遍历结果集并分别更新每个记录。

Does this work for you?

UPDATE LFRX_Attachments SET [File] = SUBSTRING([File], PATINDEX('Files\\', [File]) + 6, LEN([File]))

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