代码之家  ›  专栏  ›  技术社区  ›  David Phillips

根据其他列值进行条件替换

  •  1
  • David Phillips  · 技术社区  · 6 年前

    我有一个数据库,其中有一个表包含:

    ********************************
    * Code  *      FileName        *
    ********************************
    * NULL  * Cats and Dogs        *
    * C123  * C123 - Cats and Dogs *
    * NULL  * Baking Cakes         *
    * Z345  * Z345 - Plants        *
    * F967  * E345 - Tractors      *
    ********************************
    

    我想返回所有行的文件名或操纵文件名,这取决于“代码”列中是否有值并且它与文件名中的代码匹配。

    所以查询应该返回

    Cats and Dogs
    xxxx - Cats and Dogs
    Baking Cakes
    xxxx - Plants
    E345 - Tractors
    

    从上面的一组数据。

    我正在努力对另一列中的值进行条件替换——如果我用case语句进行替换,我需要列出所有可能的代码,这将很难维护。有什么办法吗

    Select Replace(FileName, Code, "xxxx") from table where filename like %Code%
    
    2 回复  |  直到 6 年前
        1
  •  2
  •   Tim Biegeleisen    6 年前

    您可以尝试以下查询:

    SELECT
        CASE WHEN Code IS NULL
             THEN FileName
             ELSE REPLACE(FileName, Code + ' - ', 'xxxx - ') END AS label
    FROM yourTable;
    

    enter image description here

    Demo

    你不一定需要 WHERE 子句,因为替换逻辑已经检查是否存在匹配项。注意,我搜索 code - ,即您所期望的上下文中的代码。这至少部分缓解了出现虚假替代品的可能性。

        2
  •  0
  •   Doug Coats    6 年前

    试试这个

    CREATE TABLE #tmp (Code varchar(25), FileName varchar (25))
    
    INSERT INTO #tmp VALUES
    (NULL, 'Cats and Dogs '),
    ('C123', 'C123 - Cats and Dogs'),
    (NULL, 'Baking Cakes'),
    ('Z345', 'Z345 - Plants'),
    ('F967', 'E345 - Tractors')
    
    SELECT  
    CASE 
          WHEN CHARINDEX(Code, FileName,1)>0 THEN Replace(FileName, Code, 'xxxx') 
          ELSE FileName 
    END As Result
    FROM #tmp
    

    enter image description here