Mssql2008存储过程实现文章添加过程(内容分离)要实现的流程是这样的,
用户提交文章数据->查询用户是否有可有发布量->减少发布量->判断文章分类是否存在/合法->插入文章基本信息得到文章表ID->插入内容数据->返回最新文章ID
来看具体的sql过程代码,
USE [db_luyugao] GO /****** Object: StoredProcedure [dbo].[insertArticle] Script Date: 11/12/2015 09:21:26 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO --过程开始 CREATE procedure [dbo].[insertArticle] ( @content text, @title varchar(250), @mtid int, @username varchar(50), @isyiliao int) as --新增的内容ID declare @ID int set @ID = 0 --剩余量 declare @cover int --新文章的ID declare @newartid int set @newartid=0 declare @tmpmtid int set @tmpmtid=0 --插入文章结果 declare @addartres int set @addartres=0 begin Transaction --查询剩余数量 set @cover=(select countover from tb_user where username=@username) if @@error<>0 begin RollBack Transaction return 0 end if @cover<1 --没有剩余量了 begin RollBack Transaction return 2 end --减少发布量 update tb_user set countover=countover-1 where username=@username if @@error<>0 begin RollBack Transaction return 0 end --查询媒体是否存在 set @tmpmtid=(select COUNT(*) from tb_category where mtid=@mtid and mtid>0 and enable=1 and isyiliao=@isyiliao) if @@error<>0 begin RollBack Transaction return 0 end if @tmpmtid=0 begin RollBack Transaction return 3 end ---- --RollBack Transaction --return 3 --插入内容 insert into tb_content (content) values(@content) select @ID=scope_identity() if @@error<>0 begin RollBack Transaction return 0 end --插入文章 declare @fabutime datetime = CONVERT(varchar(100), GETDATE(), 20)--获取当前时间 insert into tb_article(title,mtid,username,pubtime,contentid,huilian,status,huilianid) values(@title,@mtid,@username,@fabutime,@ID,'',0,0) if @@ROWCOUNT=0 --没有受影响条数 begin RollBack Transaction return 0 end set @newartid=(select scope_identity()) --得到文章ID Commit Transaction --提交事务 return @newartid --return 1 --0 失败 --2 没有剩余量 --3 媒体不合法 --其他 本地文章ID --执行存储过程 --exec insertArticle @content ='6L+Z5Liq5piv5paH56ug5YaF5a6544CC', --@title='文章标题 来自存储',@categoryid=17,@username='lyg' GO
适当的时候用回滚机制,sql存储过程可以返回“受影响行数”,“自定义返回值”等