ntext搜索关键字

80酷酷网    80kuku.com

  关键字
/*--ntext搜索

 按 tb 表中的 keyword 在 ta 中查找 content 列出每个 keyword 在 content 中的具体位置--邹建 2004.07--*/

--测试数据create table ta(id int identity(1,1),content ntext)insert ta select '我是中国人我是中国人'union all select '中国人民爱中国 中国人民爱中国 中国人民爱中国 中国人民爱中国'

create table tb(keyword nvarchar(100))insert tb select '中'union all select '中国'go

/*=================处理========================*/if exists (select * from dbo.sysobjects where id = object_id(N'[序数表]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)drop table [序数表]GO

--为了效率,所以要一个辅助表配合select top 4000 id=identity(int,1,1) into 序数表 from syscolumns a,syscolumns balter table 序数表 add constraint pk_id_序数表 primary key(id)go

--创建处理的存储过程create proc p_searchascreate table #t(id int,keyword nvarchar(100),position int)

declare s Nvarchar(4000),keyword nvarchar(100)declare id int,i int,ilen int

declare tb cursor local forselect a.id,b.keyword,position=charindex(b.keyword,a.content)-1,ilen=4000-len(b.keyword)from ta a,tb bwhere charindex(b.keyword,a.content)>0

open tbfetch tb into id,keyword,i,ilenwhile fetch_status=0begin select s=substring(content,i+1,4000) from ta where id=id while s<>'' begin  insert #t(id,keyword,position)  select id,keyword,id+i  from 序数表  where charindex(keyword,s,id)=id

  select i=i+ilen,s=substring(content,i+1,4000)  from ta where id=id end  fetch tb into id,keyword,i,ilenendclose tbdeallocate tbselect * from #tgo

--调用示例exec p_searchgo

--删除测试drop table 序数表,ta,tbdrop proc p_search

/*--测试结果

id          keyword   position  ----------- --------- ----------1           中        31           中        81           中国      31           中国      82           中        12           中        62           中        92           中        142           中        172           中        222           中        252           中        302           中国      12           中国      62           中国      92           中国      142           中国      172           中国      222           中国      252           中国      30

(所影响的行数为 20 行)--*/



分享到
  • 微信分享
  • 新浪微博
  • QQ好友
  • QQ空间
点击: