0

我在 SQL Server 中有一个简单的表(我使用的是 2008 R2):

Sites ( SiteId, Name )

假设我有以下数据:

-----------------------------------------
- SiteId - Name                         -
-----------------------------------------
-      1 - Foo Bar Baz                  -
-      2 - Qux Tar                      -
-      3 - Contoso                      -
-----------------------------------------

我希望允许用户搜索“ baz foo”并返回第 1 行。我希望 SQL Server 将输入字符串分解并仅返回列值与所有条件匹配的行。

从逻辑上讲,这将是这样的:

function Search(query) {
    query = query.Split(" ");
    sql = "SELECT ..."
    foreach(term in query) {
        sql += "WHERE Name LIKE " + term + " AND ";
    }
    executeSql( sql );
}

我知道 T-SQL 使处理数组变得非常困难,但肯定有一些内置的结构可以执行标记化/术语匹配吗?

4

2 回答 2

0

创建一个自定义函数来构建您的 SELECT 语句

CREATE FUNCTION [dbo].[FINDWORDS](@SEARCHTERMS VARCHAR(150), @TABLE VARCHAR(100))
RETURNS VARCHAR(200)

AS

BEGIN

DECLARE @CURRENTCOUNT AS INT
DECLARE @MAXCOUNT AS INT
DECLARE @SEARCHSTATEMENT AS VARCHAR(200)
DECLARE @CURRENTITEM AS VARCHAR(50)
DECLARE @WORDS TABLE (ROWNUMBER INT, ITEMS VARCHAR(50))

INSERT INTO @WORDS(ROWNUMBER, ITEMS)
SELECT ROWNUMBER = ROW_NUMBER() OVER(ORDER BY items), items
FROM dbo.splitfn(@SEARCHTERMS, ' ')

SET @CURRENTCOUNT = 1
SET @MAXCOUNT = (SELECT MAX(ROWNUMBER) FROM @WORDS)
SET @SEARCHSTATEMENT = 'SELECT SiteId, Name 
                        INTO #MYTABLE
                        FROM ' + @TABLE + ' WHERE Name LIKE ''%' 

WHILE(@CURRENTCOUNT <= @MAXCOUNT)
    BEGIN
        IF @CURRENTCOUNT > 1
            BEGIN
                SET @SEARCHSTATEMENT = @SEARCHSTATEMENT + ' AND NAME LIKE ''%'
            END
        SET @CURRENTITEM = (SELECT items 
                            FROM @WORDS 
                            WHERE ROWNUMBER = @CURRENTCOUNT)
        SET @SEARCHSTATEMENT = @SEARCHSTATEMENT + @CURRENTITEM + '%'''
        SET @CURRENTCOUNT = @CURRENTCOUNT + 1
    END

RETURN @SEARCHSTATEMENT

END

然后创建一个过程来调用 SELECT 语句(因为我们不能从函数中执行 SQL 字符串)

CREATE PROCEDURE [dbo].[FINDWORDS2] @SEARCHSTRING VARCHAR(200)

AS

BEGIN

DECLARE @STRING AS VARCHAR(200)

SET @STRING = DBO.FINDWORDS(@SEARCHSTRING, 'SITES') + ' SELECT * FROM #MYTABLE'

EXEC(@STRING)

END

您现在已准备好使用该过程搜索特定字符串

EXEC FINDWORDS2 @SEARCHSTRING = 'baz foo'
于 2013-01-28T15:35:29.903 回答
0

好吧,要在数据库中查找任何值,请看这里: http: //plixa.nl/find-any-value-in-a-database/它包含一个您可以使用的脚本!

于 2013-01-27T10:00:50.623 回答