if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[f_search]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[f_search]
GO
if exists (select * from dbo.sysobjects where id = object_id(N'[序數表]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [序數表]
GO
--為了效率,所以要一個輔助表配合
select top 2000 id=identity(int,1,1) into 序數表
from syscolumns a,syscolumns b
alter table 序數表 add constraint pk_id_序數表 primary key(id)
GO
/*--關鍵字搜索的函數
?
?在ntext數據中,搜索以空格分隔的關鍵字
?搜索到的關鍵字如果出現了多次,則只取最早出現的一次
?搜索到的關鍵字前后保留的字符數據,根據函數中定義的總字符數/關鍵字個數決定
--鄒建 2004.11(引用請保留此信息)--*/
/*--調用示例
?select dbo.f_search('北京 公司 網站 軟件 IT WWW','北京百聯美達美數碼科技有限公司,是面向IT專業技術人員和軟件開發及應用企業,以專業社區為中心的IT專業知識傳播與服務商。公司以IT專業網站(
www.CSDN.net
)為中心,建立了龐大的專業用戶群, 形成了網站和期刊雜志、專業出版、電子商務、企業服務、信息服務,教育培訓等關聯業務互動的商業模式。')
--*/
create function f_search(
@keyword nvarchar(2000),
@text ntext
)returns nvarchar(4000)
as
begin
?declare @relen int
?set @relen=120?--搜索結果返回的總長度(不包含關鍵字自身長度)
??--根據這個總長度/搜索的關鍵字個數,決定關鍵字前后包含的字符數
?declare @t table(keyword nvarchar(120),skey nvarchar(120))
?declare @r nvarchar(800),@i int,@ilen int
?--分拆關鍵字列表
?insert @t select substring(@keyword,id,charindex(' ',@keyword+' ',id)-id)
??,'%'+substring(@keyword,id,charindex(' ',@keyword+' ',id)-id)+'%'
?from 序數表
?where id<=len(@keyword)+1 and charindex(' ','
'+@keyword,id)-id=0
?
?--關鍵字前后要取的字符數(如果關鍵字前后的字符數是固定的,則直接為@ilen賦值)
?select @ilen=@relen/count(*) from @t
?--如果沒有搜索的關鍵字,或者無法取得前后的值,則直接退出
?if @ilen=0 return('')
?--取關鍵字
?declare @p1 int,@plen int
?select @r='',@i=null
?select
??@p1=case
???when @i>=pos-@ilen then @i
???when pos<@ilen then 1
???else
pos-@ilen
end,
??@plen=case
???when @i>=pos-@ilen then @ilen+keylen-@i+pos
???when pos<@ilen then @ilen+keylen+pos
???else @ilen*2+keylen end,
??@r=@r+case
???when @i>=pos-@ilen then ''
???else '...' end
???+substring(@text,@p1,@plen),
??@i=@p1+@plen
?from(
??select top 100 keyword,pos=patindex(skey,@text),keylen=len(keyword)
??from @t
??where patindex(skey,@text)>0
??order by pos
?)a
?return(@r+'...')
end
go
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
