You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于另一列子串动态更新SQL Server列的实现问询

SQL Server 2019 动态更新Component_Keys列解决方案

核心更新语句

假设你的表名为YourTable,可直接使用以下语句实现需求:

UPDATE t1
SET Component_Keys = COALESCE(
    (SELECT STRING_AGG(DISTINCT t2.Code, '+') WITHIN GROUP (ORDER BY t2.Code)
     FROM YourTable t2
     WHERE t1.Code != t2.Code -- 排除当前行本身
       AND t1.Description LIKE '%' + t2.Keyword + '%' -- 匹配描述中出现的其他行关键词
       AND t2.Keyword != t1.Keyword -- 忽略当前行的关键词
    ), ''
)
FROM YourTable t1;

关键要求的实现说明

  • 忽略本行Keyword:通过t2.Keyword != t1.Keyword直接排除当前行的关键词,同时t1.Code != t2.Code避免同一行的误匹配
  • 去重相同Keyword:使用DISTINCT t2.Code确保同一关键词对应的Code只出现一次,即使该关键词在多行重复出现
  • 指定格式拼接:利用SQL Server 2017+支持的STRING_AGG函数,以+作为分隔符拼接去重后的Code,WITHIN GROUP (ORDER BY t2.Code)可保证拼接顺序稳定

特殊字符兼容处理

如果你的Keyword列包含%、_这类LIKE操作符的特殊字符,需要先转义避免匹配错误,修改后的语句如下:

UPDATE t1
SET Component_Keys = COALESCE(
    (SELECT STRING_AGG(DISTINCT t2.Code, '+') WITHIN GROUP (ORDER BY t2.Code)
     FROM YourTable t2
     WHERE t1.Code != t2.Code
       AND t1.Description LIKE '%' + REPLACE(REPLACE(t2.Keyword, '%', '[%]'), '_', '[_]') + '%'
       AND t2.Keyword != t1.Keyword
    ), ''
)
FROM YourTable t1;

内容的提问来源于stack exchange,提问作者Thomas Short

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 00:42:34