USE [hdykxin]
GO
/****** Object: StoredProcedure [dbo].[pro_StudentExamScores] Script Date: 08/27/2012 00:13:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[pro_StudentExamScores]
-- Add the parameters for the stored procedure here
@examId int --传入考试ID
AS
BEGIN
set nocount on
begin transaction
declare @courses varchar(100), --班级定义考试课程列表
@index int,--当前下标
@activeCourse int, --当前课程
@length int, --字符串长度
@resultAction int --返回操作结果 1:成功 0:失败
select @courses=[class].coursePlan from h_kscj_exam exam
left join h_jxgl_ClassInfo [class] on exam.classid=[class].Id
where exam.id=@examId
select @length=LEN(@courses) --初始化LENGTH
if @length is not null and @length>0
begin
select @index=CHARINDEX(',',@courses) --初始化INDEX
while @index>0
begin
select @activeCourse=SUBSTRING(@courses,1,@index-1)--取得课程
select @courses=SUBSTRING(@courses,@index+1,@length)--去掉已经取得的课程
select @index=CHARINDEX(',',@courses)--更新index
--计算科目排名,并记录入数据库
if @activeCourse>0
begin
create table #scoreTable --创建临时表#scoreTable 用来进行排名
(
ID int IDENTITY (1,1) PRIMARY KEY not null, -- 排名
ScoreId int --考试科目成绩ID
);
insert into #scoreTable(ScoreId)
select cj.id as ScoreId
from h_kscj_cjRecords cj
left join h_jxgl_kcManage kc on cj.SubjectId=kc.Id
where SubjectId=@activeCourse and ExamId=@examId
order by Score desc
--每次插入数据之后删除临时表,保证排名从1开始
insert into h_kscj_examRanking
select ScoreId,ID from #scoreTable
drop table #scoreTable
end
end
--总分数排名
create table #SumscoreTable --创建临时表#scoreTable 用来进行排名
(
ID int IDENTITY (1,1) not null, -- 排名
ScoreId int --考试科目成绩ID
);
insert into #SumscoreTable(ScoreId)
select cj.id as ScoreId
from h_kscj_cjRecords cj
left join h_jxgl_kcManage kc on cj.SubjectId=kc.Id
where SubjectId=0 and ExamId=@examId
order by Score desc
--每次插入数据之后删除临时表,保证排名从1开始
insert into h_kscj_examRanking
select ScoreId,ID from #SumscoreTable
drop table #SumscoreTable
end
if(@@error>0)
begin
select @resultAction=0
rollback transaction
end
else
begin
select @resultAction=1
commit transaction
end
-- 最后的查询结果
select @resultAction as result
END
GO
结果会导致错误:“当 IDENTITY_INSERT 设置为 OFF 时,不能向表 'products' 中的标识列插入显式值。”