Query to get common words between two strings [closed]

淺唱寂寞╮ 提交于 2019-12-11 05:52:25

问题


I need a SQL query to get the common words only between two sentences. For example:

Sentence 1: This site is very helpful

Sentence 2: I need a helpful site

The result should be: site helpful

Also, if I need to compare sentence 1 to table field records to get the record that contains most common words to sentence 1, what can I do?


回答1:


You question title says MSQL, so I'm taking your question as a Sql Server question.

  1. Split function

Depending on SQL Server version/Server Configuration, you'll need a split function that can split a string on a delimiter of choice. Here's such a function.

CREATE FUNCTION [dbo].[fnSplit](@data NVARCHAR(MAX), @delimiter NVARCHAR(5))
RETURNS @t TABLE (rowNum int IDENTITY(1,1), data NVARCHAR(max), descriptor varchar(255) NULL)
AS
BEGIN

    DECLARE @textXML XML;
    SELECT    @textXML = CAST('<d>' + REPLACE(@data, @delimiter, '</d><d>') + '</d>' AS XML);

    INSERT INTO @t(data)
    SELECT  RTRIM(LTRIM(T.split.value('.', 'nvarchar(max)'))) AS data
    FROM    @textXML.nodes('/d') T(split)

    RETURN
END
  1. Query for common words using split function (there are quite a few ways to do this, here's one). SELECT sentence1.data FROM dbo.fnSplit('This site is very helpful',' ') sentence1 INNER JOIN dbo.fnSplit('I need a helpful site',' ') sentence2 ON sentence1.data = sentence2.data


来源:https://stackoverflow.com/questions/13864446/query-to-get-common-words-between-two-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!