从Word逐字搜索产品

时间:2013-06-24 05:37:47

标签: sql sql-server-2012

我使用以下SQL,

SELECT * FROM Products P
WHERE  (P.Name LIKE '%'+@Keyword+'%')

现在我需要逐字搜索,这意味着当我输入Retina Sony时,我需要在名称字段中的名称字段Retina AND中搜索Sony。意味着我需要将关键字中的所有单词与anme字段匹配。以上查询对我不起作用。任何线索?

5 个答案:

答案 0 :(得分:1)

您可以编写一个函数来将字符串与空格分开,例如:

CREATE FUNCTION [dbo].[Split]
(
@String VARCHAR(200),
@Delimiter VARCHAR(5)
)

RETURNS @SplittedValues TABLE
(
OccurenceId SMALLINT IDENTITY(1,1),
SplitValue VARCHAR(200)
)

AS

BEGIN

DECLARE @SplitLength INT

WHILE LEN(@String) > 0
BEGIN

SELECT @SplitLength = (CASE CHARINDEX(@Delimiter,@String) WHEN 0 THEN

LEN(@String) ELSE CHARINDEX(@Delimiter,@String) -1 END)

INSERT INTO @SplittedValues

SELECT SUBSTRING(@String,1,@SplitLength)

SELECT @String = (CASE (LEN(@String) - @SplitLength) WHEN 0 THEN ''

ELSE RIGHT(@String, LEN(@String) - @SplitLength - 1) END)

END

RETURN

然后使用此功能,如:

SELECT * FROM Products P
WHERE  (P.Name in (Select * from dbo.Split(@Keyword, ' ')) )

答案 1 :(得分:1)

听起来像是全文搜索的完美用例:

CREATE TABLE dbo.Products
(
    ID INT IDENTITY CONSTRAINT PK_Products PRIMARY KEY CLUSTERED,
    Name NVARCHAR(100)
)
GO

CREATE FULLTEXT CATALOG mycatalog;
GO

CREATE FULLTEXT INDEX ON dbo.Products
( 
    Name LANGUAGE 1033
) 
KEY INDEX PK_Products ON mycatalog; 
GO

SELECT  *
FROM    dbo.Products
WHERE   FREETEXT(Name, 'Retina AND Sony') -- will match any text that contains the two words, their inflectional forms or synonyms

有几种搜索方式,上面只是一个例子。

请参阅: http://msdn.microsoft.com/en-us/library/ms142571.aspx http://msdn.microsoft.com/en-us/library/ms142583.aspx

答案 2 :(得分:0)

使用if event。 将输入的字符串转换为数组并尝试:

WHERE  
   (
      P.Name LIKE '%'+@Keyword[0]+'%' OR
      P.Name LIKE '%'+@Keyword[1]+'%'
      ....
   )

这是我的想法。

答案 3 :(得分:0)

CREATE FUNCTION [dbo].[Split]
(
    @String NVARCHAR(4000),
    @Delimiter NCHAR(1)
)
RETURNS TABLE 
AS
RETURN 
(
    WITH Split(stpos,endpos) 
    AS(
        SELECT 0 AS stpos, CHARINDEX(@Delimiter,@String) AS endpos
        UNION ALL
        SELECT endpos+1, CHARINDEX(@Delimiter,@String,endpos+1)
            FROM Split
            WHERE endpos > 0
    )
    SELECT 'Id' = ROW_NUMBER() OVER (ORDER BY (SELECT 1)),
        'Data' = SUBSTRING(@String,stpos,COALESCE(NULLIF(endpos,0),LEN(@String)+1)-stpos)
    FROM Split
)
GO

DECLARE @DelimitedString NVARCHAR(128)
SET @DelimitedString = 'Duckman,Cornfed,Ajax,Charles,Mambo'
SELECT * FROM dbo.Split(@DelimitedString, ',')

DECLARE @Keyword nvarchar(128)
SET @Keyword = 'Retina,Cornfed'

select *  from Products p where p.name in 
(SELECT Data FROM dbo.Split(@Keyword, ','))

现在检查这个

我已经测试了它,将单词

返回给我

答案 4 :(得分:0)

以下是答案,

SELECT  * from [Products] P
WHERE   NOT EXISTS(SELECT 1 FROM Split(@Keyword,' ') Words WHERE (P.Name NOT LIKE '%' + Words.Items +'%'))

来自a sql query with multiple search word