如何使用LIKE匹配字段关联源表更新目标表数据
修正SQL匹配逻辑,实现表数据更新
表结构与数据
tblSource
| ID | Info | Born | City |
|---|---|---|---|
| 1 | 1954 Barry Nelson TV series | US | San Francisco |
| 2 | 1954 Sean Connery Dr. No | UK | Edinburgh |
| 3 | 1967 David Niven Casino Royale | UK | London |
| 4 | 1967 George Lazenby On Her Majesty´s Secret Service | AU | New South Wales |
| 5 | 1969 Roger Moore Moonraker | UK | London |
| 6 | 1973 Timothy Dalton The Living Daylights | UK | Wales |
| 7 | 1987 Pierce Brosnan The World Is Not Enough | IE | County Louth |
tblTarget(更新前)
| ID | Name | Born | City |
|---|---|---|---|
| 10 | Sean Connery | ||
| 11 | Roger Moore | ||
| 12 | Timothy Dalton | ||
| 13 | Pierce Brosnan | ||
| 14 | Daniel Craig |
需求说明
通过LIKE匹配关联行,将tblSource中的Born和City字段值更新到tblTarget对应列;无匹配的行不执行更新。需提供两种实现方案:
- 基于
tblTarget生成硬编码列表的方案 - 全动态关联的方案
预期更新后的tblTarget数据:
| ID | Name | Born | City |
|---|---|---|---|
| 10 | Sean Connery | UK | Edinburgh |
| 11 | Roger Moore | UK | London |
| 12 | Timothy Dalton | UK | Wales |
| 13 | Pierce Brosnan | IE | County Louth |
| 14 | Daniel Craig |
原错误SQL
UPDATE t SET t.Born = s.Born, t.City = s.City FROM tblTarget t JOIN tblSource s ON t.Name LIKE s.Info WHERE s.Info IN ('%Sean Connery%', '%Roger Moore%', '%Timothy Dalton%', '%Pierce Brosnan%', '%Daniel Craig%')
修正后的方案
1. 硬编码列表方案
原SQL核心错误是LIKE匹配方向颠倒,且IN条件误用通配符。修正后:
UPDATE t SET t.Born = s.Born, t.City = s.City FROM tblTarget t JOIN tblSource s ON s.Info LIKE '%' + t.Name + '%' WHERE t.Name IN ('Sean Connery', 'Roger Moore', 'Timothy Dalton', 'Pierce Brosnan')
ON子句实现tblSource.Info包含tblTarget.Name的匹配逻辑WHERE子句过滤出需要更新的目标姓名,减少无效关联
2. 全动态方案
无需硬编码,自动匹配所有存在对应记录的行:
UPDATE t SET t.Born = s.Born, t.City = s.City FROM tblTarget t JOIN tblSource s ON s.Info LIKE '%' + t.Name + '%'
该方案会自动匹配所有tblTarget.Name在tblSource.Info中出现的行,无匹配的行(如Daniel Craig)不会被更新,完全符合需求。
内容的提问来源于stack exchange,提问作者Kaptah
相关产品推荐
相关产品推荐

