增删改查存储过程

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go

ALTER proc [dbo].[GOODS_COMMONNAME_SAVE]
@UserID int,
@OpType int, -- 1 新增 2 修改 3 删除
@Items text,
@Root varchar(50) = 'Root/'
as
set nocount on
DECLARE @hdoc int
declare @ret int
declare @retmsg varchar(200)
EXEC @ret = sp_xml_preparedocument @hdoc OUTPUT, @Items --@hdoc表示此xml文件的句柄 @Items表示原xml文件
if @ret != 0 --@ret为0时表示执行成功 非0时表示失败
begin
select -1111, '解析xml失败'
return
end

select *
into #VItems --#VItems是临时表
FROM OPENXML (@hdoc, @Root,1) --@hdoc是 XML 文档的内部表式法的文档句柄。通过调用 sp_xml_preparedocument 创建 XML 文档的内部表式法
WITH ( --@Root是 XPath 模式,用来标识要作为行处理的节点(这些节点在 XML 文档中,该文档的句柄由 hdoc 参数传递)
COMMONID int, --商品ID
COMMONNAME varchar(100), -- 通用名
CHEMICALNAME varchar(100) -- 化学名
)
IF @@ROWCOUNT <= 0 --@@ROWCOUNT 返回受上一语句影响的行数
BEGIN
set @ret = -3312
set @retmsg = '没有可处理的信息'
goto outcode
end
if @optype in (1,2) --1 新增 ,2 修改
begin
if exists(select * from #vitems where commonname is null or commonname = '')
begin
set @ret = -3312
set @retmsg = '通用名不能为空'
goto outcode
end
end
if @optype in (2,3) -- 修改, 删除
begin
if exists(select * from #vitems where commonid is null or commonid = 0)
begin
set @ret = -3312
set @retmsg = '操作记录中缺乏有效的标识'
goto outcode
end
end
--begin tran......commit tran里面是事务处理 要么全部执行要么不执行
begin tran
if @optype = 1 -- 新增
begin
declare @mmid int
select @mmid = max(commonid) + 1 from opd_goodscommonname
if @mmid is null
set @mmid = 1
select identity (int,1,1) as cid , COMMONNAME, CHEMICALNAME
into #tname --这个临时表#tname中存放的cid序号是加1的
from #vitems--把临时表#vitems中的字段值自加1,然后和OMMMONNAME CHEMICALNAME和起构成临时表#vitems
insert opd_goodscommonname (commonid, commonname, chemicalname, cspell, wcspell)
select @mmid + cid, commonname, chemicalname, dbo.v6_pub_getspell(commonname), dbo.v6_pub_getwspell(commonname)
from #tname
if @@error <> 0 --如果前一个 Transact-SQL 语句执行没有错误,则返回 0。
begin
rollback tran--事务回滚
set @ret = -3312
set @retmsg = '插入表失败'
goto outcode
end
end
else if @optype = 2 -- 修改
begin
update a
set commonname = b.commonname
, chemicalname = b.chemicalname
,cspell = dbo.v6_pub_getspell(b.commonname)
,wcspell = dbo.v6_pub_getwspell(b.commonname)
from opd_goodscommonname a
inner join #vitems b on a.commonid = b.commonid
if @@error <> 0
begin
rollback tran
set @ret = -3312
set @retmsg = '修改表失败'
goto outcode
end
end
else if @optype = 3
begin
if exists (select * from #vitems a inner join bdo_goods b on a.commonid = b.commongoodsid)
begin
rollback tran
set @ret = -3312
set @retmsg = '通用名已有商品使用,不能删除'
goto outcode
end
delete a
from opd_goodscommonname a
inner join #vitems b on a.commonid = b.commonid
if @@error <> 0
begin
rollback tran
set @ret = -3312
set @retmsg = '删除纪录失败'
goto outcode
end
end
commit tran
set @ret = @userid
set @retmsg = '成功'

outcode:
exec sp_xml_removedocument @hdoc
select @ret, @retmsg
return @ret

 

你可能感兴趣的:(存储过程)