0

我有一个表tblJobs,我想在其上实现对列的搜索JobDescription。我

我在这个表中有超过 70,000 行。我成功实现了这个,但是我使用的方式太慢了。

谁能帮我解决这个问题?我使用的 SQL 存储过程是这样的:

    Create Procedure Sp_SearchJobs
     (
        @SearchValue varchar(Max)
     )
    AS
BEGIN
    WITH SplitTblJobs AS
    (
        SELECT tbljobs.*, s.ListValue FROM tbljobs tbljobs
        CROSS APPLY  dbo.FN_ListToTable(' ',tbljobs.JobDescription) AS s
    )

    , WordMatchCount AS 
              (
      SELECT s.JobID,COUNT(*) AS CountOfWordMatch FROM                         dbo.FN_ListToTable('',@SearchValue) v
      INNER JOIN SplitTblJobs s ON v.ListValue=s.ListValue
      GROUP BY s.JobID
      HAVING COUNT(*)>0
               )
    , SearchLen AS 
    (
      SELECT n.Number,SUBSTRING(@SearchValue,1,n.Number) AS PartialSearchValue
      FROM Numbers n WHERE n.Number<=LEN(@SearchValue)
            )
     , MatchLen AS 
    (
      SELECT tbljobs.JobID,MAX(l.Number) MatchStartLen FROM tbljobs tbljobs
      LEFT OUTER JOIN SearchLen l ON LEFT(tbljobs.JobDescription,l.Number)=l.PartialSearchValue
      GROUP BY tbljobs.JobID
    )
      SELECT  tbljobs.*,w.CountOfWordMatch,m.MatchStartLen FROM tbljobs tbljobs
      LEFT OUTER JOIN WordMatchCount  w ON tbljobs.JobID=w.JobID
      LEFT OUTER JOIN MatchLen        m ON tbljobs.JobID=m.JobID
      WHERE w.CountOfWordMatch>0
      ORDER BY w.CountOfWordMatch DESC,m.MatchStartLen DESC,LEN(tbljobs.JobDescription) 
      DESC,tbljobs.JobDescription ASC
END 

这里在函数中有一个使用的函数。该表值函数的代码是这样的:

  Create FUNCTION [dbo].[FN_ListToTable]
  (
       @SplitOn  char(1)    
      ,@List   varchar(8000)
  )
  RETURNS TABLE

  AS  RETURN 
  (

    SELECT
      ListValue
    FROM (SELECT
              LTRIM(RTRIM(SUBSTRING(List2, number+1, CHARINDEX(@SplitOn, List2, number+1)-number - 1))) AS ListValue
              FROM (
                       SELECT @SplitOn + @List + @SplitOn AS List2
                   ) AS dt
                  INNER JOIN dbo.Numbers n ON n.Number < LEN(dt.List2)
              WHERE SUBSTRING(List2, number, 1) = @SplitOn
         ) dt2
    WHERE ListValue IS NOT NULL AND ListValue!='');

这里使用了另一个表。它的结构如下:

   CREATE TABLE [dbo].[Numbers]
   (
     [Number] [int] IDENTITY(1,1) NOT NULL,
         CONSTRAINT [PK_Numbers] PRIMARY KEY CLUSTERED 
         (
           [Number] ASC
         )
         WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) 
        ON [PRIMARY]
   ) ON [PRIMARY]

   GO

要使此程序运行..

  1. 制作上述表格
  2. 制作函数
  3. 制作存储过程。

我想在tbljobs.

4

2 回答 2

1

假设您使用 SQL Server,您应该启用并使用全文搜索。

http://msdn.microsoft.com/en-us/library/ms142571.aspx

于 2012-07-05T07:28:16.627 回答
0

我认为您正在尝试在这里重新发明轮子-如果您想要的只是简单的子字符串搜索,请使用 LIKE 运算符。

如果您需要更高级的搜索功能,请查看 RDBMS(我假设是 SQL 服务器)的文档以了解如何执行全文搜索。

于 2012-07-05T07:29:21.843 回答