8

我在重写使用CONTAINS谓词的现有进程时遇到问题。现有进程正在使用 a CURSOR,但它真的很慢,并且随着插入更多数据而变得更慢。

我已经制作了一个简单的示例(下面的代码),其中包含两个表 - 一个是Full Text Indexed,另一个有一个列,它标识CONTAINS从第一个中选择行的条件。

当前存储过程使用 aCURSOR循环第二个表,设置一个@filter变量,然后使用CONTAINS从第一个表中找到匹配的行。问题是它运行了几个小时,而且情况越来越糟。

为了加快这个过程,我尝试CONTAINS直接在列值上使用谓词,而不是经历游标的痛苦……但我遇到了语法错误。我的例子如下。

我尝试实现 aCROSS APPLY并且还尝试编写用户定义函数 ( fnCONTAINS),但没有成功。

IF ( object_id('Players') IS NOT NULL )
  DROP TABLE Players

go

IF ( object_id('TeamNeeds') IS NOT NULL )
  DROP TABLE TeamNeeds

go

-- create fulltext catalog ft as default
go

CREATE TABLE Players
  (
     PlayerID        INT IDENTITY(1, 1),
     PlayerName      VARCHAR(20),
     PlayerPositions VARCHAR(60)
  )

go

CREATE UNIQUE INDEX IXPlayerID
  ON Players( PlayerID )

go

CREATE fulltext INDEX ON Players(PlayerPositions) KEY INDEX IXPlayerID

go

INSERT Players
       (PlayerName,
        PlayerPositions)
VALUES( 'Patrick Travers',
        'Pitcher,Left Field,Center Field,Right Field,Shortstop' )

go

CREATE TABLE TeamNeeds
  (
     TeamID   INT,
     Keywords VARCHAR(50)
  )

go

INSERT TeamNeeds
       (TeamID,
        Keywords)
VALUES( 1,
        '"Center Field" and "Shortstop" and "Pitcher"' )

go

WAITFOR delay '00:00:05'

go -- Give the Full Text Index process time to populate the catalog
SELECT PlayerID,
       PlayerName,
       PlayerPositions
FROM   Player,
       TeamNeeds
WHERE  CONTAINS(PlayerPositions, Keywords)

go -- Syntax error on Keywords...
SELECT PlayerID,
       PlayerName,
       PlayerPositions
FROM   Players,
       TeamNeeds
WHERE  CONTAINS(PlayerPositions, '"Center Field" and "Shortstop" and "Pitcher"')

go -- Works just fine, but requires setting an explicit search expression for every search, which is terribly slow
4

1 回答 1

3

据我所知,这只有在多语句 TVF 中才有可能。

创建以下函数

CREATE FUNCTION [dbo].[ft_test] (@Keywords VARCHAR(50))
RETURNS @ReturnTable TABLE (
  PlayerID        INT,
  PlayerName      VARCHAR(20),
  PlayerPositions VARCHAR(60))
AS
  BEGIN
      INSERT INTO @ReturnTable
      SELECT PlayerID,
             PlayerName,
             PlayerPositions
      FROM   Players
      WHERE  CONTAINS(PlayerPositions, @Keywords)

      RETURN
  END

然后以下工作正常

SELECT *
FROM   TeamNeeds
       CROSS APPLY [dbo].[ft_test] (Keywords) CA 

尽管内联版本因“内联函数“x”无法采用相关参数或子查询,因为它使用全文运算符而失败。”

于 2014-12-27T21:37:52.667 回答