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

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