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

随心笔谈2年前发布 admin
199 0 0

文章摘要

这篇文章介绍了在SQL Server中创建了一个名为`proc sp_Insert_Student`的存储过程,用于处理学生信息的插入、更新和检查操作。该存储过程接受五个参数:学号、姓名、性别、年龄和返回值。它首先检查是否存在与学号相同的记录,如果存在,会进行更新操作并返回错误信息;如果不存在,则插入新记录并返回成功信息。该存储过程通过变量`@tmpName`、`@tmpSex`和`@tmpAge`来比较现有记录,确保主键的唯一性。


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

© 版权声明

相关文章