SQLServer2008存储过程实现数据插入与更新(sqlserver数据库存储过程存储在哪里)速看

随心笔谈9个月前发布 admin
206 00
🌐 经济型:买域名、轻量云服务器、用途:游戏 网站等 《腾讯云》特点:特价机便宜 适合初学者用 点我优惠购买
🚀 拓展型:买域名、轻量云服务器、用途:游戏 网站等 《阿里云》特点:中档服务器便宜 域名备案事多 点我优惠购买
🛡️ 稳定型:买域名、轻量云服务器、用途:游戏 网站等 《西部数码》 特点:比上两家略贵但是稳定性超好事也少 点我优惠购买

文章摘要

这篇文章介绍了名为`proc sp_Insert_Student`的数据库存储过程,用于对`Student`表进行插入或更新操作。存储过程通过以下逻辑处理数据: 1. **检查是否存在记录**:使用`if exists`语句查找`No`字段是否存在记录。2. **更新操作**:如果存在相同的`No`值,会调用`select`语句获取现有记录,并将新数据与现有数据进行比较。如果两者一致,返回`@rtn=0`;否则,进行更新操作。3. **插入操作**:如果不存在相同的`No`值,会调用`insert`语句将新数据插入`Student`表,并返回`@rtn=1`。 总结而言,该存储过程实现了`Student`表的插入、更新和报错功能。


Create proc sp_Insert_Student
@No char(10),
@Name varchar(20),
@Sex char(2),
@Age int,
@rtn int output
as
declare
@tmpName varchar(20),
@tmpSex char(2),
@tmpAge int

if exists(select * from Student where No=@No)
begin
select @tmpName=Name,@tmpSex=Sex,@tmpAge=Age from Student where No=@No
if ((@tmpName=@Name) and (@tmpSex=@Sex) and (@tmpAge=@Age))
begin
set @rtn=0 –有相同的数据,直接返回值
end
else
begin
update Student set Name=@Name,Sex=@Sex,Age=@Age where No=@No
set @rtn=2 –有主键相同的数据,进行更新处理
end
end
else
begin
insert into Student values(@No,@Name,@Sex,@Age)
set @rtn=1 –没有相同的数据,进行插入处理
end

© 版权声明

相关文章