删除 SQL 中字段中子字符串后面的字符
如果这已经完成,我深表歉意,但我很难找到答案。
我正在尝试重建数据库后清理一些数据。该数据库适用于一家艺术品商店。旧的做法是我们有一个产品表,产品名称表示艺术的名称,然后是“由某某制作”,
例如,
最近 一种产品的名称可能是“列奥纳多·达·芬奇的蒙娜丽莎”我们希望向网站添加功能,以便能够按艺术家对产品进行索引。因此,我创建了一个具有自己的名称字段的艺术家表,并且我不再需要产品名称中的艺术家名称。
所以我想删除“by”之后的所有内容。
因此,用“蒙娜丽莎”代替“达芬奇的蒙娜丽莎”
我该怎么办?
I apologize if this has already been done but I'm having trouble finding an answer.
I'm trying to clean up some data after rebuilding a database. The database is for an art store. The old way of doing it is we'd have a Product table and the Product Name said the name of the art and then "by so and so"
So for example one product might have the name "Mona Lisa by Leonardo Da Vinci"
Recently we wanted to add functionality to the website to be able to index products by artists. So I created an artist table with it's own name field and I no longer want the Artist Name in the Product Name.
So I want to remove everything from the "by" onward.
So instead of "Mona Lisa by Leonardo Da Vinci" just "Mona Lisa"
How can I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是您需要的代码:
此方法可确保您从单词“by”的最后一个实例开始切掉由空格包围的文本。否则,“Joe Jones 的《Lady by the Lake》”就会变成“Lady”,
披头士乐队的“Abby Road”将变成“Ab”。
对 REVERSE 的调用会翻转字符的顺序,以便您可以向后搜索。对 CHARINDEX 的调用查找此反转字符串中“yb”的第一个实例,它恰好是原始字符串中“by”的最后实例。然后截断到该点。瞧。
祝你好运!
Here's the code you need:
This approach ensures that you slice off the text beginning at the last instance of the word " by " surrounded by spaces. Otherwise, "Lady by the Lake by Joe Jones" would become "Lady",
and "Abby Road by The Beatles" would become "Ab".
The call to REVERSE flips the order of the characters around so you can search backwards. The call to CHARINDEX finds the first instance of " yb " in this reversed string, which happens to be the last instance of " by " in the original string. Then truncate to that point. Voila.
Good luck!
如果您确定每个产品记录都有“ by ”后跟艺术家姓名,您可以:
If you're sure every product record has " by " followed by the artist name, you can:
如果使用 TSQL:
If using TSQL: