我有一个表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
.