简体   繁体   English

从SQL中的字符串中提取匹配的单词

[英]Extracting matched word from string in sql

I would like to extract matched word from string. 我想从字符串中提取匹配的单词。 For example 例如

Str = "This is Nihar Kulkarni as Indian"

Here using LIKE we will fetch all records those contain "%India%", but here I would like extract whole word which matched. 在这里,我们将使用LIKE获取所有包含“%India%”的记录,但是在这里,我想提取匹配的整个单词。 Suppose from these string India matched so I want "Indian" as output. 假设印度匹配这些字符串,所以我希望将“ Indian”作为输出。

Thanks 谢谢

Something like this? 像这样吗

DECLARE @Word varchar(10) = 'India'

SELECT SUBSTRING(V.S,CIw.I, ISNULL(NULLIF(CIs.I,0),LEN(V.S)+1) - CIw.I)
FROM (VALUES('This is Nihar Kulkarni as Indian')) V(S)
     CROSS APPLY (VALUES(CHARINDEX(@Word,V.S))) CIw(I)
     CROSS APPLY (VALUES(CHARINDEX(' ',V.S,CIw.I))) CIs(I);

This gets the position of the word, and then the next space. 这将获取单词的位置,然后获取下一个空格。 If there is no space afterwards, the length of the full value (+1) is used. 如果之后没有空格,则使用完整值(+1)的长度。 Note that if you have grammar in your value, for example 'This is Nihar Kulkarni, who is Indian.' 请注意,如果您的语法有价值,例如'This is Nihar Kulkarni, who is Indian.' or 'He is Indian, but lives in Europe' then the value 'Indian.' 'He is Indian, but lives in Europe'则取值'Indian.' or 'Indian,' would be returned respectively. 'Indian,'将分别返回。

You can try this for any word that you like : 您可以尝试使用任何您喜欢的单词:

DECLARE @MatchedWord VARCHAR(50) = 'Indian'
DECLARE @Str  VARCHAR(50) = 'This is Nihar Kulkarni as Indian'

SELECT SUBSTRING(@Str,CHARINDEX(@MatchedWord,@Str),LEN(@MatchedWord))

您可以尝试以下查询:

select * from table_name where Str LIKE 'India%'

You can try the following query. 您可以尝试以下查询。 Here first I have inserted all words of given string into a table by separating space. 首先,我通过分隔空格将给定字符串的所有单词插入表中。 After that using like matching records from that table has been selected. 之后,从该表中选择使用类似的匹配记录。

DECLARE @Stringtofindmatching VARCHAR(MAX) = 'This is Nihar Kulkarni as Indian'
DECLARE @table TABLE ( matchingword VARCHAR(50) )
DECLARE @x INT = 0
DECLARE @firstspace INT = 0
DECLARE @nextspace INT = 0

SET @x = LEN(@Stringtofindmatching) - LEN(REPLACE(@Stringtofindmatching, ' ', '')) + 1 -- number of ids in id_list

WHILE @x > 0
    BEGIN
        SET @nextspace = CASE WHEN CHARINDEX(' ', @Stringtofindmatching, @firstspace + 1) = 0
                              THEN LEN(@Stringtofindmatching) + 1
                              ELSE CHARINDEX(' ', @Stringtofindmatching, @firstspace + 1)
                         END
        INSERT  INTO @table
        VALUES  ( SUBSTRING(@Stringtofindmatching, @firstspace + 1, (@nextspace - @firstspace) - 1) )
        SET @firstspace = CHARINDEX(' ', @Stringtofindmatching, @firstspace + 1)
        SET @x = @x - 1
    END

SELECT  *
FROM @table where matchingword like '%India%'

You can find the live demo Here . 您可以在此处找到现场演示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM