TSQL复杂的字符串操作

时间:2016-03-21 04:06:51

标签: sql sql-server tsql

我有一个名为'Title'的列。它存储了职称ex:'a java Developer'。 我想创建另一个表,从标题创建关键字并将所有关键字存储在其中。我想摆脱所有特殊字符,某些单词如'a'和'the',打破字符串并将关键字表中的'Java'和'Developer'(大写第一个字符)存储为两个不同的记录。我该怎么做到这一点?有什么SQL函数可以帮助我解决这个问题?任何文章或演示将不胜感激。感谢

2 个答案:

答案 0 :(得分:2)

类似这样的事情

INSERT INTO KeyWord (keyword)
SELECT DISTNCT s.word
FROM   tbl t
CROSS APPLY dbo.SomeDelimiterSplitterFunction(t.Title, ' ') s
WHERE  t.word not in ('', 'a', 'the')

答案 1 :(得分:2)

您也可以尝试这样的事情:

DECLARE @test VARCHAR(50) = ' senior java developer'

DECLARE @Final VARCHAR(50)

--Replace all the words you don't need
SELECT @Final = RTRIM(LTRIM(REPLACE(REPLACE(REPLACE(CONCAT(' ' , LTRIM(@test)), ' a ',''),' the ',  ''),' an ', '')))

;WITH cte_Replace AS
(
SELECT 
    SUBSTRING(@Final,1,CHARINDEX(' ',@Final,1) -1) AS Title,
    SUBSTRING(@Final,CHARINDEX(' ',@Final,1) +1, LEN(@Final) - CHARINDEX(' ',@Final,1) +1) AS RemainingString

UNION ALL

SELECT 
    CASE WHEN CHARINDEX(' ',RemainingString,1) != 0 THEN SUBSTRING(RemainingString,1,CHARINDEX(' ',RemainingString,1) -1) ELSE RemainingString END AS Title,
    CASE WHEN CHARINDEX(' ',RemainingString,1) != 0 THEN SUBSTRING(RemainingString,CHARINDEX(' ',RemainingString,1) +1, LEN(RemainingString) - CHARINDEX(' ',RemainingString,1) +1)  ELSE NULL END AS RemainingString
FROM 
    cte_Replace
where 
    RemainingString IS NOT  NULL
)
SELECT 
  UPPER(SUBSTRING(Title,1,1)) + SUBSTRING(Title,2,LEN(Title)-1) AS Title FROM cte_Replace