簡體   English   中英

如何從SQL Server 2008中的字段獲取單詞

[英]How to get words from field in SQL Server 2008

我需要在文本字段中獲取單詞,並使用這些單詞進行一些更新,例如:

原始數據

words        | other field    | another field
---------------------------------------------
white        |                |
some words   |                |
some other w |                |

理想的結果

words        | other field    | another field
---------------------------------------------
white        |                |
some         | words          |
some         | other          | w

我該怎么做?

額外

我有這個查詢,我得到一個字段有多少個單詞

select nombre, 
       LEN(words) - LEN(REPLACE(words, ' ', ''))+1 as palabras
  from origen_informacion
 where words <> ''

如果您嘗試分割以空格分隔的字符串,則可以使用以下功能:

create function fn_ParseCSVString
(
@CSVString  varchar(8000) ,
@Delimiter  varchar(10)
)
returns @tbl table (s varchar(1000))
as
/*
select * from dbo.fn_ParseCSVString ('qwe rew wer', ',c,')
*/
begin
declare @i int ,
    @j int
    select  @i = 1
    while @i <= len(@CSVString)
    begin
        select  @j = charindex(@Delimiter, @CSVString, @i)
        if @j = 0
        begin
            select  @j = len(@CSVString) + 1
        end
        insert  @tbl select substring(@CSVString, @i, @j - @i)
        select  @i = @j + len(@Delimiter)
    end
    return
end


GO

並通過''作為分隔符。

select * from dbo.fn_ParseCSVString ('qwe rew wer', ' ')

在SQL Server 2008中,可以使用sys.dm_fts_parser將字符串拆分為單詞。 您可以將其與cross apply合並。

DECLARE @data TABLE 
(
id INT IDENTITY(1,1) PRIMARY KEY,
words VARCHAR(1000),
other_field VARCHAR(1000),
another_field VARCHAR(1000)
)

INSERT INTO @data (words) 
VALUES ('white'),('some words'),('some other w '),('This sentence has 5 words');

WITH splitData AS
(
SELECT 
       id ,
       max(case when occurrence = 1 then display_term end) as word1,
       max(case when occurrence = 2 then display_term end) as word2,
       max(case when occurrence = 3 then display_term end) as word3,
       max(case when occurrence = 4 then display_term end) as word4       
FROM @data
CROSS APPLY sys.dm_fts_parser('"' + REPLACE(words,'"','') + '"',1033,NULL,0)
GROUP BY id
HAVING MAX(occurrence) <= 4
)
UPDATE @data
SET words = word1, other_field=word2, another_field=word3 + ISNULL(' ' + word4,'')
FROM @data d1
JOIN  splitData sd ON d1.id = sd.id

SELECT * FROM @data

輸出量

id     words                          other_field     another_field
------ ------------------------------ --------------- --------------
1      white                          NULL            NULL
2      some                           words           NULL
3      some                           other           w
4      This sentence has 5 words      NULL            NULL

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM