如何使用存储过程完全替代视图
ALTER PROCEDURE P_tblJianding_Count_UPDATE
AS
BEGIN
/*需求说明:
在tblJianding表中,有4个字段idsJiandingID , chrChanpinXinghao , chrZhizaoBianhao , lngJiandingshu
现需要要将chrChanpinXinghao , chrZhizaoBianhao这2个字段组合后分组计数的值更新到lngJiandingshu字段中,
我使用了下面的方法:建立2个视图,然后将视图组合起来在存储过程写入数量到lngJiandingshu字段
虽然可以实现所需功能,但总觉得存储过程外部还挂了2个视图,太分散了,对维护不利。
问题:1、如果只使用1个存储过程完成的话,应该怎样写呢?
2、如果chrChanpinXinghao , chrZhizaoBianhao其中之一的字段有更新,即执行此存储过程,应该怎么办呢?
-------------------------------------------------
*/
--V_JiXingJihaoZuhe 视图:取得tblJianding表的主键和组合字段
/*
SELECT idsJiandingID ,
chrChanpinXinghao + chrZhizaoBianhao AS chrJixingJihaoZuhe ,
lngJiandingshu
FROM dbo.tblJianding
*/
--V_JixingJihaoZuheShuliang 视图:取得2个字段组合后的计数
/*
SELECT chrChanpinXinghao + chrZhizaoBianhao AS chrJixingJihaoZuhe ,
COUNT(chrChanpinXinghao + chrZhizaoBianhao) AS lngShuliang
FROM dbo.tblJianding
GROUP BY chrChanpinXinghao + chrZhizaoBianhao
*/
--将组合后的记录数写入到lngJiandingshu字段
UPDATE V_JiXingJihaoZuhe
SET lngJiandingshu = V_JixingJihaoZuheShuliang.lngShuliang
FROM V_JiXingJihaoZuhe
INNER JOIN V_JixingJihaoZuheShuliang ON V_JiXingJihaoZuhe.chrJixingJihaoZuhe = V_JixingJihaoZuheShuliang.chrJixingJihaoZuhe
-------------------------------------------------
END
GO
------解决方案--------------------
-- 1、如果只使用1个存储过程完成的话,应该怎样写呢?
--> 1个存储过程实现,如下代码
create procedure P_tblJianding_Count_UPDATE
as
begin
update a
set a.lngJiandingshu=b.qty
from dbo.tblJianding a
inner join
(select chrChanpinXinghao+chrZhizaoBianhao 'chrJixingJihaoZuhe',
count(1) 'qty'
from dbo.tblJianding&