根据其他列值进行条件替换
Conditional replacement depending on other column value
我有一个数据库 table 包含:
********************************
* Code * FileName *
********************************
* NULL * Cats and Dogs *
* C123 * C123 - Cats and Dogs *
* NULL * Baking Cakes *
* Z345 * Z345 - Plants *
* F967 * E345 - Tractors *
********************************
我想 return 所有行的文件名或操作文件名,基于代码列中是否有值并且它与文件名中的代码匹配。
所以查询应该return
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%
您可以尝试以下查询:
SELECT
CASE WHEN Code IS NULL
THEN FileName
ELSE REPLACE(FileName, Code + ' - ', 'xxxx - ') END AS label
FROM yourTable;
您在这里不一定需要 WHERE
子句,因为替换逻辑已经检查是否存在匹配项。请注意,我搜索 code -
,即您期望的上下文中的代码。这至少部分地减轻了可能存在错误替换的可能性。
试试这个
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
我有一个数据库 table 包含:
********************************
* Code * FileName *
********************************
* NULL * Cats and Dogs *
* C123 * C123 - Cats and Dogs *
* NULL * Baking Cakes *
* Z345 * Z345 - Plants *
* F967 * E345 - Tractors *
********************************
我想 return 所有行的文件名或操作文件名,基于代码列中是否有值并且它与文件名中的代码匹配。
所以查询应该return
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%
您可以尝试以下查询:
SELECT
CASE WHEN Code IS NULL
THEN FileName
ELSE REPLACE(FileName, Code + ' - ', 'xxxx - ') END AS label
FROM yourTable;
您在这里不一定需要 WHERE
子句,因为替换逻辑已经检查是否存在匹配项。请注意,我搜索 code -
,即您期望的上下文中的代码。这至少部分地减轻了可能存在错误替换的可能性。
试试这个
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