我想阅读公司表并从名称中取出所有可能的后缀。这是我到目前为止所做的:
declare @badStrings table (item varchar(50))
INSERT INTO @badStrings(item)
SELECT 'company' UNION ALL
SELECT 'co.' UNION ALL
SELECT 'incorporated' UNION ALL
SELECT 'inc.' UNION ALL
SELECT 'llc' UNION ALL
SELECT 'llp' UNION ALL
SELECT 'ltd'
select id, (companyname = Replace(name, item, '') FROM @badStrings)
from companies
where name != ''
答案 0 :(得分:4)
SELECT c.ID, RTRIM(x.Name) [Name]
FROM @companies c
OUTER APPLY
( SELECT REPLACE(c.name, item, '') AS [Name]
FROM @badStrings
-- WHERE CLAUSE ADDED HERE
WHERE CHARINDEX(item, c.Name) = 1 + LEN(c.Name) - LEN(Item)
) x
WHERE c.name != ''
AND x.[Name] != c.Name
这将产生“PC公司”而没有重复。
另一个选项是递归地替换Bad Strings的所有出现:
;WITH CTE AS
( SELECT c.ID, c.Name [OriginalName], RTRIM(x.Name) [Name], 1 [Level]
FROM @companies c
OUTER APPLY
( SELECT REPLACE(c.name, item, '') AS [Name]
FROM @badStrings
WHERE CHARINDEX(item, c.Name) = 1 + LEN(c.Name) - LEN(Item)
) x
WHERE c.name != ''
AND RTRIM(x.Name) != c.Name
UNION ALL
SELECT c.ID, OriginalName, RTRIM(x.Name) [Name], Level + 1 [Level]
FROM CTE c
OUTER APPLY
( SELECT REPLACE(c.name, item, '') AS [Name]
FROM @badStrings
WHERE CHARINDEX(item, c.Name) = 1 + LEN(c.Name) - LEN(Item)
) x
WHERE c.name != ''
AND x.[Name] != c.Name
)
SELECT DISTINCT ID, Name, OriginalName
FROM ( SELECT *, MAX(Level) OVER(PARTITION BY ID) [MaxLevel]
FROM CTE
) c
WHERE Level = maxLevel
这将从“The PC Company”中获得“PC”。
答案 1 :(得分:3)
我运行代码段的错误是:
Msg 102, Level 15, State 1, Line 12
Incorrect syntax near '='.
以下代码不是理想的解决方案 - 它只返回REPLACE
函数更改了其名称已的公司列表。
declare @companies table (id int, name nvarchar(50))
INSERT INTO @companies(id, name)
SELECT 1,'One Company' UNION ALL
SELECT 2, 'Two co.' UNION ALL
SELECT 3, 'Three incorporated' UNION ALL
SELECT 4, 'Four inc.' UNION ALL
SELECT 5, 'Five llc' UNION ALL
SELECT 6, 'Six llp' UNION ALL
SELECT 7, 'Seven ltd'
select * from @companies
declare @badStrings table (item varchar(50))
INSERT INTO @badStrings(item)
SELECT 'company' UNION ALL
SELECT 'co.' UNION ALL
SELECT 'incorporated' UNION ALL
SELECT 'inc.' UNION ALL
SELECT 'llc' UNION ALL
SELECT 'llp' UNION ALL
SELECT 'ltd'
select * from @badStrings
以下是已编辑的查询:
select id, x.Name
from @companies c
OUTER APPLY (
SELECT Replace(c.name, item, '') AS [Name]
FROM @badStrings
) x
where c.name != ''
AND x.[Name] != c.Name
返回:
id Name
----------- --------
1 One
2 Two
3 Three
4 Four
5 Five
6 Six
7 Seven
(7 row(s) affected)
希望它有用
修改强>
将匹配应用于结束且@badStrings
值
select id, x.Name
from @companies c
OUTER APPLY (
SELECT Replace(c.name, item, '') AS [Name]
FROM @badStrings
WHERE c.Name LIKE '%'+item
) x
where c.name != ''