我有一个表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
要使此程序运行..
我想在tbljobs
的decscription列上实现搜索。
答案 0 :(得分:1)
假设您使用SQL Server,则应启用并使用全文搜索。
答案 1 :(得分:0)
我认为你试图在这里重新发明轮子 - 如果你想要的只是一个简单的子串搜索,请使用LIKE运算符。
如果您需要更高级的搜索功能,请查看RDBMS(我假设SQL服务器)的文档,了解如何执行全文搜索。