成都七中成绩文件导入SQL脚本

--select * from Paper
--
=======================================================================公共变量===============================================================================
declare @examId uniqueIdentifier = '97E4D516-7CAC-4517-9F7F-E2F4000F37F1'        --考试ID
--
select * from examination
declare @paperId uniqueIdentifier = 'F3942637-72C7-40E0-89FB-3FEEEFDFF8DB'        --试卷ID
declare @classDivideType int = 0                                                --分班类型,0:未分班;1:文科班;2:理科班
declare @filePath varchar(300= 'D:\生物.xls'


declare @sql varchar(max= ''

--=======================================================================创建试题信息表===============================================================================
if(OBJECT_ID('PQInfo')>0)
    drop table PQInfo

create table PQInfo
(
    Label int identity(1,1),
    PQId uniqueIdentifier,
    OrderNumber varchar(10),
    SortOrderNumber varchar(10),
    IsObjective bit
)

insert into PQInfo
select pq.Id,pq.OrderNumber,pq.SortOrderNumber,qt.IsObjective
from PaperQuestion pq
inner join Question q on q.Id = pq.QuestionId
inner join QuestionType qt on qt.Id = q.QuestionTypeId
where q.QuestionKind in (0,3,4and pq.PaperId = @paperId
order by qt.IsObjective desc,SortOrderNumber

--select * from PQInfo

--------=============================================插入EPS记录=============================================
if(OBJECT_ID('tmpEps')>0)
    drop table tmpEps

declare @examPaperId uniqueIdentifier 
select @examPaperId=ep.Id from ExamPaper ep where ep.PaperId = @paperId and ep.ExaminationId=@examId

select NEWID() as Id,epc.Id as ExamPaperClassId,s.Id as StudentId,s.StudentID as StudentNumber,s.Name as studentName,s.Gender as StudentGender,
s.IsYingJie,c.ClassDivideType,100.0 as TotalScore,0 as IsOutComing,100.0 as SubjectScore,100.0 as ObjectScore
into tmpEps
from Student s
inner join ExamPaperClass epc on epc.ClassId=s.ClassId
inner join Class c on c.Id = s.ClassId
where epc.ExamPaperId = @exampaperId and c.ClassDivideType = @classDivideType

print ('--------------------------完成EPS记录创建-----------------------------------')

------select * from tmpEps
--
=======================================================================Excel成绩入库===============================================================================
declare @subjectName varchar(20= ''
declare @startPosition int = 1,@endPosition int = 0
declare @lastIndex int = 0

while @startPosition != 0
begin
    set @lastIndex = @startPosition
    set @startPosition = CHARINDEX('\',@filePath,@startPosition+1)
end

select @subjectName = SUBSTRING(@filePath,@lastIndex+1,len(@filePath)-@lastIndex-4)


if(OBJECT_ID('tmpData')>0)
    drop table tmpData
    
set @sql = 'SELECT * into tmpData FROM OPENROWSET(''microsoft.jet.oledb.4.0'',''Excel 8.0;HDR=yes;database=' + @filePath + '''''select * from [' + @subjectName + '$]'')'

exec(@sql)

declare @n1 int = 0,@n2 int = 0 
select @n1 = COUNT(*from sys.columns where object_id = object_id('tmpData'and name like 'KG%A'
select @n2 = COUNT(*from PQInfo where IsObjective = 1

if(@n1 != @n2)
begin
    print('成绩文件中客观题数目不正确')
    return
end

select @n1 = COUNT(*)-18-@n1*2 from sys.columns where object_id = object_id('tmpData'
select @n2 = COUNT(*from PQInfo where IsObjective = 0

if(@n1 != @n2)
begin
    print('成绩文件中主观题数目不正确')
    return
end

delete from tmpEPS where studentNumber in
(
    select studentNumber from tmpEPS 
    except
    select distinct KSH from tmpData


declare @absentSN varchar(max= ''

;with cte as
(
    select distinct KSH as SN from tmpData
    except
    select distinct studentNumber  from tmpEPS
)
select @absentSN = dbo.JoinString(SN) from cte

if(@absentSN != '')
begin
    print '如下学生 '+@absentSN+' 在系统中不存在'
    return
end

------=============================================tmpES表创建=============================================

if(OBJECT_ID('tmpES')>0)
    drop table tmpES

CREATE TABLE tmpES(
    [Id] [uniqueidentifier],
    [ExamPaperStudentId] [uniqueidentifier],
    [Answer] [varchar](10) ,
    [ScoreValue] [decimal](181) ,
    [PaperQuestionId] [uniqueidentifier] ,
    [OrderNumber] [varchar](10) ,
    [SortOrderNumber] [varchar](10) ,
 CONSTRAINT [PK_tmpES] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ONON [PRIMARY]
ON [PRIMARY]

print('--------------------------完成tmpES表创建-----------------------------------')

------=============================================插入客观题tmpES记录=============================================

if(OBJECT_ID('tmpAnswer')>0)
    drop table tmpAnswer
    
create table tmpAnswer
(
    SN varchar(20),
    Answer varchar(10),
    Label int
)

declare @fields varchar(max= ''

declare @qNumber int = 0
select @qNumber = COUNT(*from pqinfo where isobjective = 1

set @endPosition = 18 + 2*@qNumber
set @startPosition = 19

while @startPosition <= @endPosition
begin
    select @fields += '[' + name + '],' from sys.columns where object_id = object_id('tmpData'and column_id = @startPosition
    set @startPosition += 2
end

select @fields = substring(@fields,1,LEN(@fields)-1)
set @sql = ';with cte as(select KSH, score,field from tmpData unpivot(score for field in(' + @fields +')) as unpvt) insert into tmpAnswer select cte.ksh,Score,(s.column_id-17)/2 from cte inner join sys.columns s on s.name = cte.field where s.object_id = object_id(''tmpData'')'

exec(@sql)

if(OBJECT_ID('tmpScore')>0)
    drop table tmpScore
    
create table tmpScore
(
    SN varchar(20),
    Score decimal(5,2),
    Label int
)

set @fields = ''
set @endPosition = 18 + 2*@qNumber
set @startPosition = 20

while @startPosition <= @endPosition
begin
    select @fields += '[' + name + '],' from sys.columns where object_id = object_id('tmpData'and column_id = @startPosition
    set @startPosition += 2
end

select @fields = substring(@fields,1,LEN(@fields)-1)
set @sql = ';with cte as(select KSH, score,field from tmpData unpivot(score for field in(' + @fields +')) as unpvt) insert into tmpScore select cte.ksh,Score,(s.column_id-18)/2 from cte inner join sys.columns s on s.name = cte.field where s.object_id = object_id(''tmpData'')'

exec(@sql)

insert into tmpES
select NEWID(),tmpEps.Id,ta.Answer,ts.Score,pq.pqid,pq.OrderNumber,pq.SortOrderNumber 
from tmpScore ts
inner join tmpAnswer ta on ts.SN = ta.SN and ts.Label = ta.Label
inner join pqinfo pq on pq.label = ts.Label
inner join tmpEps on tmpEps.studentNumber = ts.SN

print('------=============================================插入客观题tmpES记录=============================================')

------=============================================插入主观题tmpES记录=============================================

truncate table tmpScore
set @fields = ''
set @startPosition = 19 + 2*@qNumber
declare @subjectOffset int = 0;
set @subjectOffset = 18 + @qNumber

select @qNumber = COUNT(*from pqinfo where isobjective = 0
set @endPosition = @startPosition + @qNumber - 1

while @startPosition <= @endPosition
begin
    select @fields += '[' + name + '],' from sys.columns where object_id = object_id('tmpData'and column_id = @startPosition
    set @startPosition += 1
end

select @fields = substring(@fields,1,LEN(@fields)-1)

set @sql = ';with cte as(select KSH, score,field from tmpData unpivot(score for field in(' + @fields +')) as unpvt) insert into tmpScore select cte.ksh,Score,s.column_id-' + ltrim(@subjectOffset+ ' from cte inner join sys.columns s on s.name = cte.field where s.object_id = object_id(''tmpData'')'

exec(@sql)

insert into tmpES
select NEWID(),tmpEps.Id,'',ts.Score,pq.pqid,pq.OrderNumber,pq.SortOrderNumber 
from tmpScore ts
inner join pqinfo pq on pq.label = ts.Label
inner join tmpEps on tmpEps.studentNumber = ts.SN

print('------=============================================插入主观题tmpES记录=============================================')

--=============================================套卷试题与成绩文件检查=============================================
if(OBJECT_ID('tmpValidate')>0)
    drop table tmpValidate
    
;with cte as
(
    select pq.SortOrderNumber,pq.Score from PaperQuestion pq
    inner join Question q on q.Id = pq.QuestionId
    where pq.PaperId=@paperId and q.QuestionKind in (0,3,4)
)
,cte2 as
(
    select pq.SortOrderNumber,MAX(es.ScoreValue) as sc from tmpES es
    inner join PaperQuestion pq on pq.Id = es.PaperQuestionId
    inner join Question q on q.Id = pq.QuestionId
    where pq.PaperId=@paperId and q.QuestionKind in (0,3,4)
    group by pq.SortOrderNumber

select cte.SortOrderNumber,cte.Score as 满分,cte2.sc as 最大值,case when cte2.sc>cte.Score then 'X' else '' end as 有问题  
into tmpValidate
from cte 
inner join cte2 on cte.SortOrderNumber = cte2.SortOrderNumber

declare @errorCount int = 0;
select @errorCount=COUNT(*from tmpValidate where 有问题='X'

if(@errorCount>0)
begin
    select * from tmpValidate 
    order by SortOrderNumber
    return
end

print('--------------------------成绩文件与试卷结构匹配-----------------------------------')


--=============================================主观题、客观题、总分汇总=============================================
--
--------总分
;with cte as
(
    select ExamPaperStudentId,SUM(scoreValue) as totalScore from tmpES
    group by ExamPaperStudentId
)
update tmpEPS set totalScore = cte.totalScore
from tmpEPS
inner join cte on cte.ExamPaperStudentId = tmpEPS.Id

----------客观题总分
;with cte as
(
    select ExamPaperStudentId,SUM(scoreValue) as totalScore from tmpES
    inner join PQInfo pq on pq.pqId = tmpES.PaperQuestionId
    where pq.IsObjective = 1
    group by ExamPaperStudentId
)
update tmpEPS set objectScore = cte.totalScore
from tmpEPS
inner join cte on cte.ExamPaperStudentId = tmpEPS.Id

----------主观题总分
;with cte as
(
    select ExamPaperStudentId,SUM(scoreValue) as totalScore from tmpES
    inner join PQInfo pq on pq.pqId = tmpES.PaperQuestionId
    where pq.IsObjective = 0
    group by ExamPaperStudentId
)
update tmpEPS set subjectScore = cte.totalScore
from tmpEPS
inner join cte on cte.ExamPaperStudentId = tmpEPS.Id

print('--------------------------完成主观题、客观题、总分汇总-----------------------------------')

--=============================================拷贝缓存数据到系统库=============================================
if(OBJECT_ID('tmpEPSID')>0)
    drop table tmpEPSID

select eps.Id into tmpEPSID 
from ExamPaperStudent eps
inner join ExamPaperClass epc on epc.Id = eps.ExamPaperClassId
inner join ExamPaper ep on ep.Id = epc.ExamPaperId
where ep.ExaminationId=@examId and ep.PaperId = @paperId

delete from ExamScore where ExamPaperStudentId in (Select * from tmpEPSID)

delete from ExamPaperStudent where Id in (select * from tmpEPSID)

insert into ExamPaperStudent
select * from tmpEPS

update tmpES set Answer='E'
where Answer = '*'

update tmpES set Answer='F'
where Answer = '+'

;with cte as
(
    select PQId,tmpEps.id as epsId,OrderNumber,SortOrderNumber from PQInfo
    cross  join tmpEps
    except
    select PaperQuestionId,ExamPaperStudentId,OrderNumber,SortOrderNumber from tmpES
)
insert into tmpES
select NEWID(),epsId,'E',0,pqid,OrderNumber,SortOrderNumber from  cte

insert into ExamScore
select * from tmpES

print('--------------------------完成拷贝缓存数据到系统库-----------------------------------')

--=============================================清理临时表=============================================

if(OBJECT_ID('tmpEps')>0)
    drop table tmpEps
    
if(OBJECT_ID('tmpES')>0)
    drop table tmpES

if(OBJECT_ID('tmpValidate')>0)
    drop table tmpValidate

if(OBJECT_ID('PQInfo')>0)
    drop table PQInfo
    
if(OBJECT_ID('tmpData')>0)
    drop table tmpData
    
if(OBJECT_ID('tmpAnswer'> 0)
    drop table tmpAnswer    
    
if(OBJECT_ID('tmpScore'> 0)
    drop table tmpScore
    
if(OBJECT_ID('tmpEPSID')>0)
    drop table tmpEPSID
    
print('--------------------------完成清理临时物理表-----------------------------------')
原文地址:https://www.cnblogs.com/AndyGe/p/2799693.html