读书人

求:一个简单的新增存储过程。送分。该

发布时间: 2012-02-17 17:50:41 作者: rapoo

求:一个简单的新增存储过程。送分。
两张表:class包含:班级ID,所属学校,年度,月份。
student包含:学生ID,班级ID,年龄
预写个存储过程:要实现判断class中是否已经有所属学校年度月份,如果class表中已经包含了这条信息那返回班级ID给student表。
如果没有这记录,那在CLASS表中新增所属学校年度月份,返回班级ID给students表新增。
哪位高手指点下啊~送分了

[解决办法]
Create PROCEDURE dbo.GetClassId
(
@School varchar(50),
@year int,
@month int,
@ClassId bigint output
)
as
select @ClassId=班级ID from class where 所属学校=@School and 年度=@year and 月份=@month
if @ClassId is null or @Class=0
begin
insert class (所属学校,年度,月份) values (@School,@year,@month)
Select @ClassId = SCOPE_IDENTITY()
end
return
调用时取Command执行后的@ClassId参数的值
[解决办法]

declare @classid int
if exists (select * from class where 所属学校 = '所属学校参数 ' and 年度 = '年度参数 ' and 月份 = '年度参数 ' )
begin
--注意,如果有多个ClassID的话,那么得到的是最后一个
select @classid = 班级ID from class where 所属学校 = '所属学校参数 ' and 年度 = '年度参数 ' and 月份 = '年度参数 '
end
else
begin
--班级ID必须是自增主键
insert into class select '所属学校参数 ', '年度参数 ', '年度参数 '
select @classid = @@identity
end

以后这类问题发在数据库板块
[解决办法]
SCOPE_IDENTITY()是最后一句insert语句的新自动增量值

读书人网 >VB Dotnet

热点推荐