【SQL Server】利用游標將學生表中的成績轉化為績點


軟件工程綜合實踐第一次作業
代碼來源:班上同學的數據庫大作業
alter table sc
add GPA float;               --加入績點列
alter table sc
add number int identity(1,1);--將表按原始位置順序編號(可加可不加)
alter table sc add primary key(number)
declare score_visit cursor    --聲明一個游標      
for select score from sc 
open score_visit              --打開游標  
declare @GPA float
select @GPA=score from sc
fetch next from score_visit into @GPA
while @@fetch_status=0        --循環讀取
begin
if @GPA>=90
update sc set GPA=4.0 where current of score_visit;
if @GPA >=85 and @GPA <90
update sc set GPA =3.7 where current of score_visit;
if @GPA >=82 and @GPA <85
update sc set GPA =3.3 where current of score_visit;
if @GPA >=78 and @GPA <81
update sc set GPA =3.0 where current of score_visit;
if @GPA >=75 and @GPA <78
update sc set GPA =2.7 where current of score_visit;
if @GPA >=72 and @GPA <75
update sc set GPA =2.3 where current of score_visit;
if @GPA >=68 and @GPA <72
update sc set GPA =2.0 where current of score_visit;
if @GPA >=64 and @GPA <68
update sc set GPA =1.5 where current of score_visit;
if @GPA >=60 and @GPA <64
update sc set GPA =1.0 where current of score_visit;
if @GPA <60
update sc set GPA =0 where current of score_visit;
fetch next from score_visit into @GPA
end
close score_visit              --關閉游標
deallocate score_visit         --刪除游標
具體實現代碼

一、分析、功能:在已經有學生數據的基礎上,利用游標的循環讀取功能,將數據表中的成績依次轉化為績點。

       游標:是一種能從包括多條數據記錄的結果集中每次提取一條記錄的機制。游標可以被看作是一個查詢結果集(可以是零條、一條或由相關的選擇 語句檢索出的多條記錄)和結果集中指向特定記錄的游標位置組成的一個臨時文件,提供了在查詢結果集中向前或向后瀏覽數據處理結果集中數據的能力。

  在表中加入一個GPA列並合理化聲明一個游標后,將原先表中的成績數據讀取到一個新的變量中,利用績點轉換規則,將成績轉化為相應績點,並生成到GPA列,操作完成后,關閉並刪除游標。

二、運行結果:(如圖)

 

三、心得體會:雖然一開始並沒有搞清楚游標的操作機制,導致數據的處理出現了一點小問題,但是在利用游標對數據的轉化中,對游標的使用也慢慢地顯得得心應手,同時又對部分細節進行了更好的深入,如讀取數據時對各條數據的處理以及對表結構的細分。從陌生到熟悉正是知識體系建立並掌握的過程。

四、遇到的問題:

1.讀取到的數據並不能進行實際操作

2.游標使用后未關閉/刪除,導致程序下次運行時出現錯誤

 3.成績比較過程中的變量處理不恰當

五、解決辦法:

1.將讀取到的數據暫時放入到新聲明的一個變量中

2.將使用后的游標關閉/刪除

3.對變量進行規范處理,統一格式

六、改進方案:

1.將 if 所在的條件判斷語句塊進行簡化

2.直接將讀取數據進行轉化,不必暫時放到新聲明的變量內

3.在加入GPA列后對表中數據進行分段化處理,不至於顯得雜亂

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM