日期:2014-05-18  浏览次数:20556 次

评论 - 存储过程 ----------------------------------- 在线等 ------------------------------
SQL code
--产品表
CREATE table product
(
pid int primary key identity,    --产品编号
ptitle varchar(100),    --产品标题
pcontent text,    --产品内容
pcomments int,    --评论数
)

GO

--新闻表
CREATE table news
(
nid int primary key identity,    --新闻编号
ntitle varchar(100),    --新闻标题
ncontent text,    --新闻内容
ncomments int,    --评论数
)
GO


--评论表
CREATE Table comments
(
cid int primary key identity,    --评论编号
ctype int,    --评论类型(1为产品,2为新闻)
cobjId int,    --评论目标ID
ccontent text,    --评论内容
)




求个存储过程,或思路,要求如下:当插入一条评论时,判断该评论属于产品或新闻,如果是产品,则查询出对应产品的评论数,并在对应产品中现有的评论数里加1 (pcomments产品评论数字段)---感谢!




------解决方案--------------------
可以在评论表里写个insert触发器,判断插入的评论类型的值,如果是1,则将产品表中的评论数加1,如果是2,则将新闻表中的评论数加1
------解决方案--------------------
虽然触发器有诸多弊端,但还是建议写触发器,如果涉及到批量插入数据好处理点
SQL code

---->>TravyLee生成测试数据:
--产品表
CREATE table product
(
pid int primary key identity,    --产品编号
ptitle varchar(100),    --产品标题
pcontent text,    --产品内容
pcomments int,    --评论数
)
GO
insert product(ptitle,pcontent,pcomments)
select 'title1','content1',0 union all
select 'title2','content1',0 union all
select 'title3','content1',0
--新闻表
CREATE table news
(
nid int primary key identity,    --新闻编号
ntitle varchar(100),    --新闻标题
ncontent text,    --新闻内容
ncomments int,    --评论数
)
GO
insert news(ntitle,ncontent,ncomments)
select 'title1','content1',0 union all
select 'title2','content1',0 union all
select 'title3','content1',0
go
--评论表
CREATE Table comments
(
cid int primary key identity,    --评论编号
ctype int,    --评论类型(1为产品,2为新闻)
cobjId int,    --评论目标ID
ccontent text,    --评论内容
)

if OBJECT_ID('tri_test') is not null
drop trigger tri_test
go
create trigger tri_test on comments
for insert
as
;with t
as(
select cobjId,count(1) as pcomments 
from inserted where ctype=1
group by cobjId
)
update product
set product.pcomments=product.pcomments+t.pcomments from t
where t.cobjId=product.pid
;with m
as(
select cobjId,count(1) as ncomments 
from inserted where ctype=2
group by cobjId
)
update news
set news.ncomments=news.ncomments+m.ncomments from m
where m.cobjId=news.nid
go


insert comments(ctype,cobjId,ccontent)
select 1,2,'very good' union all
select 2,1,'very good' union all
select 2,3,'very good' union all
select 2,1,'very good' union all
select 1,2,'very good'

select * from product
/*
pid    ptitle    pcontent    pcomments
--------------------------------------
1    title1    content1    0
2    title2    content1    2
3    title3    content1    0
*/

select * from news
/*
nid    ntitle    ncontent    ncomments
-----------------------------------------
1    title1    content1    2
2    title2    content1    0
3    title3    content1    1
*/