/*--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 [email protected] while @s<>'' begin insert #t(id,keyword,position) select @id,@keyword,[email protected] from 序數表 where charindex(@keyword,@s,id)=id
select @[email protected][email protected],@s=substring(content,@i+1,4000) from ta where [email protected] 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 行)--*/