欢迎来到.net学习网

欢迎联系站长一起更新本网站!QQ:879621940

您当前所在位置:首页 » SQLServer教程 » 正文

热门阅读

在sql中为文章自动加上锚文本链接

创建时间:2012年01月15日 17:27  阅读次数:(5885)
分享到:
锚文本可以在用户浏览我们的文章时引导用户找到想要的文章,在网站排名上也是一个相当重要的因素,所以为我们的文章加上适当的锚文本是相当不错的选择。

但像本人这样的业余站长,想手工来维护锚文本,工作量是非常大的,所以自己写了一个sql函数,在新增文章时,自动为文章添加上锚链接。

下面讲讲本人的思路:

首先是要创建一个表,这个表中存储了每篇文章的关键字,以确定什么样的文字可以链接到该文章。表结构如下:
create table tags
(
ID int not null primary key identity(1,1),
ArID int not null --文章的ID
ArType tinyint not null--文章的分类
Tag varchar(50) not null--关键字
IsPrimary bit not null--是否为主关键字
)

当然了,上面的表结构是根据本人的网站的创建的,各位可以创建适合自己网站的关键字表,为了控制锚文本的合理性,该表还需要添加一些约束,比如ArID与Tag应该唯一,ArID与IsPrimary也应该唯一等。

然后创建一个函数,用来自动将文章内容中的关键字加上链接,下面的函数用到了游标,可能效率不是很好,还请高手们指点更好的方法。(为了测试本站该功能,本处加上表值函数的关键字,看能不能自动加上链接:),望大家谅解!)

该函数的sql如下:
create function udf_create_tag_hy
(@str varchar(max))
returns varchar(max)
as
begin

declare @k_tag varchar(50)
declare @artype tinyint
declare @arid int
declare @path varchar(50)

declare @t_temp_key_tag table
(
temp_keytag varchar(50),
temp_arid int
)

declare re_sult cursor for select tag,artype,arid from keys_tag order by IsPrimary desc, 
id asc
--该处的order by IsPrimary desc, id asc排序的原因说明一下,我们应该尽量为主关键字加上链接,其次才是非主关键字
open re_sult

fetch next from re_sult into @k_tag,@artype,@arid
while @@fetch_status=0
begin
if (select count(1) from @t_temp_key_tag)<3 
and charindex(@k_tag,@str)< >0 
and not exists(select 1 from @t_temp_key_tag where temp_keytag=@k_tag or temp_arid=@arid)
/*
该处的判断条件说明:
1,(select count(1) from @t_temp_key_tag)<3 控件一篇文章的锚文本不超过三个
2,charindex(@k_tag,@str)< >0 判断关键字是在文章的主内容中存在
3,not exists(select 1 from @t_temp_key_tag where temp_keytag=@k_tag or temp_arid=@arid)
如果这篇文章一个关键字出现了多次,只为第一次出现的加上链接。
如果一篇文章的多个关键字都在该篇文章中出现,也只为一个关键字加上链接

为什么要有上面三个控制了?呵呵,都明白,就不细说了。
*/
begin
if(@artype=0)
begin
set @path='http://www.lmwlove.com/ac/ID717'
end
else if(@artype=1)
begin
set @path='http://www.lmwlove.com/ae/ID32'
end
else if(@artype=2)
begin
set @path='http://www.lmwlove.com/ah/ID31'
end
set @str=replace(@str,@k_tag,'<a href="'+@path+cast(@arid as varchar(50))+'" target="_blank" class="content_href" >'+@k_tag+'</a >')
insert into @t_temp_key_tag(temp_keytag,temp_arid) values (@k_tag,@arid)
end
fetch next from re_sult into @k_tag,@artype,@arid
end
close re_sult
deallocate re_sult

return @str
end

该函数的一些逻辑是基于本站数据库结构上的,比如对@artype参数的判断。

函数创建成功后,还需要在需要自动创建锚文本的表中加上instead of触发器,自动调用该函数,举例如下;
create trigger [dbo].[iti_Ar] on [dbo].[t_Ar] instead of insert
as
if @@rowcount=0 return
set nocount on

insert into Subject_Article
(
Title, Content, CreateDate
)
select Title,dbo.udf_create_tag_hy(Content), CreateDate from inserted

set nocount off

到此,在我们往表t_Ar添加文章时,触发器iti_Ar就会自动为我们创建锚文本了,大家试试吧。
来源:.net学习网
说明:所有来源为 .net学习网的文章均为原创,如有转载,请在转载处标注本页地址,谢谢!
【编辑:Wyf

打赏

取消

感谢您的支持,我会做的更好!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

最新评论

共有评论0条
  • 暂无任何评论,请留下您对本文章的看法,共同参入讨论!
发表评论:
留言人:
内  容:
请输入问题 26+87=? 的结果(结果是:113)
结  果: