实现以空格分割 的tag模式的文章插入以及存储过程

因为中国使用方块字,所以对于tag,中国人也喜欢用空格来间隔来表示不是同一个tag

我的解决的方案是这样的 在这里和大家分享,如有好的思路希望可以大家一起讨论.

比如 这里 给用户 一个题目输入框 内容输入框  一个tag输入框 支持tag以空格分割

这里我们重点说明的是程序如何辨别tag空格的 以及插入做操的存储过程。

我是利用正则,获取到字符串中的空格 然后替换成"," 这样我们就可以传入数据库由存储过程来处理了

比如你输入的tag形式如下:voosay  blog  pizi 那么使用正则以后变成 voosay,blog,pizi  这样我们就可以直接交给存储过程来处理了。存储过程代码在最下面。

程序里正则地使用很简单 两行:

string p = @"\s+";
  string result = Regex.Replace("voosay  blog  pizi ",p,",");

以下是存储过程,我加了足够的注释,大家应该可以看得懂

CREATE  PROCEDURE voosaythemtag
@themname nvarchar(50),
@userid int,
@classid int,
@readme ntext,
@kword nvarchar(50),
@wordback int output

AS
declare @Tagid int
declare @Taid int
declare @num int
declare @tagname nvarchar(1000)
declare @sum int
declare @word nvarchar(50)
declare @f varchar(8000)
declare @int int
declare @a int


insert them(themname,readme,userid,voosayclassid)
values(@themname,@readme,@userid,@userid,@classid)--先插入数据建立专题
set @Taid=@@identity--获取刚刚插入的主健
if(@kword<>'' and @kword<>null)--判断输入的tag是否为空
begin
 set   @int=charindex(',',@kword)
 if(@int=0)--@int为零意味着插入的tag只有一个
 begin
  select @num=count(themtagid) from themtag where themtagname=@kword
  if(@num=1)--@num等于1意味着tag名字已经存在
  BEGIN
   select @tagid=themtagid from themtag where themtagname=@kword---获取该tag已经存在的tagid
   INSERT themvstag VALUES(@tagid,@Taid)--建立专题和tag的关系
  end
  else if(@num=0)--显然@num等于0意味着tag名字还不存在
  begin
   INSERT themtag(themtagname) VALUES(@kword)
   SET @tagid=@@identity--获得刚刚插入的主健
   INSERT themvstag VALUES(@tagid,@Taid)
  end
 end
 else---转折点 说明tag的个数是一个以上
 begin
  set   @f=@kword
  set   @int=0
  set   @int=charindex(',',@f)
  while   @int<>0
  begin
   set @word=left(@f,charindex(',',@f)-1)--从左面开始截取tag
   select @num=count(themtagid) from themtag where themtagname=@word
   if(@num!=0)--@num等于1意味着tag名字已经存在,@num这里必定是等于1 如果不等于0的话
   BEGIN
    select @tagid=themtagid from themtag where themtagname=@word
    INSERT themvstag VALUES(@tagid,@Taid)--建立专题和tag的关系
   end
   else
   begin
    INSERT themtag(themtagname) VALUES(@word)
    SET @tagid=@@identity
    INSERT themvstag VALUES(@tagid,@Taid)
    set   @f=right(@f,len(@f)-@int)--从传进来的tag中减去刚操作的那个字符串
    set   @int=charindex(',',@f)--建立新的字符串
   end
  end--在这里while循环结束 --下面的来进行判断字符串中最后一个
  select @num=count(themtagid) from themtag where themtagname=@f
  if(@num!=0)
  BEGIN
   select @tagid=themtagid from themtag where themtagname=@f
   INSERT themvstag VALUES(@tagid,@Taid)
  end
  else
  begin
   INSERT themtag(themtagname) VALUES(@f)
   SET @tagid=@@identity
   INSERT themvstag VALUES(@tagid,@Taid)
  end
 end
end

if(@@error<>0)
BEGIN
 set @wordback =1---表明存储过程失败
end
else
begin
 set @wordback=0 ---表明存储过程成功
end
GO

posted on 2006-10-03 16:55  坯子  阅读(538)  评论(1编辑  收藏  举报

导航