1. 程式人生 > >SQL Server 2008 資料庫_實驗四_SQL DDL 操作

SQL Server 2008 資料庫_實驗四_SQL DDL 操作

SQL DDL 操作、

什麼是SQL DDL 操作?
  DDL是SQL定義語言,它主要包括三個關鍵字:create ,alter , drop(資料庫關鍵字不分大小寫 ),主要操作物件 有資料庫、表、索引、檢視等。
  
語句說明:

建立資料庫   create database
修改資料庫   alter database
刪除資料庫   drop database
建立表     create table
修改表     alter table
刪除表     drop table
建立索引    create index
刪除索引    drop index

實驗的目的

  • 掌握使用遊標的基本步驟。
  • 熟悉卷遊標的使用
  • 學習用遊標解決實際問題
  • 瞭解SQL的流程控制

實驗內容與要求

1、在實驗1、2建立的S、SC、C、T四個基本表的基礎上,編寫以下游標:
實現一個遊標,順序讀取並列印所有學生的 學號、課程號、成績資訊,讀取過程中刪除S5的選課記錄,並將為空的成績修改為60分。
提示:編寫過程中,可需參閱聯機叢書獲取下列內容的具體用法
(1)宣告變數可用declare,為變數賦值用set
(2)需要判斷可用if語句,如if內需執行多條語句,可用begin 和 end 來限定if的作用範圍
(3)可通過while迴圈來依次讀取所有記錄,讀取狀態可用@@FETCH_STATUS獲取
(4)如遊標已建立,但執行過程中出錯。導致重新執行時提示遊標已存在,可用cursor_status來檢查是否存在該遊標,如存在,則先deallocate
2、實現一個卷遊標,逆序列印所有學生的 學號、課程號、成績資訊

實驗主要步驟

在實驗1、2建立的S、SC、C、T四個基本表的基礎上,編寫以下游標:
實現一個遊標,順序讀取並列印所有學生的 學號、課程號、成績資訊,讀取過程中刪除S5的選課記錄,並將為空的成績修改為60分

實現一個遊標,順序讀取並列印所有學生的 學號、課程號、成績資訊
在這裡插入圖片描述
原始碼:

--定義遊標
declare @s# char(6),@c# char(6),@score int   --定義變數
declare scuur cursor for select * from sc;   --宣告遊標
open scuur
fetch next from scuur
into @s#,@c#,@score
while @@FETCH_STATUS = 0
	begin
		if(@score is null)
			begin
				print'學號:'
[email protected]
# +'課程號:'[email protected]#+'成績:'+'--' end else --begin print'學號:'[email protected]#+'課程號:'[email protected]#+'成績:'+ cast(@score as char(5))-- 型別轉化 fetch next from scuur into @s#,@c#,@score --end end close scuur deallocate scuur

讀取過程中刪除S5的選課記錄,並將為空的成績修改為60分
在這裡插入圖片描述
原始碼:

declare @s# char(6),@c# char(6),@score int   --定義變數
declare scuur cursor for select * from sc;   --宣告遊標
open scuur
fetch next from scuur
into @s#,@c#,@score
while @@FETCH_STATUS=0
	begin
		if(@score is null)
			begin
				set @score = 60
				print'學號:'[email protected]# +'課程號:'[email protected]#+'成績:'+cast(@score as char(5))
			end
		else
			begin
				print'學號:'[email protected]#+'課程號:'[email protected]#+'成績:'+cast(@score as char(5))-- 型別轉化
				fetch next from scuur
				into @s#,@c#,@score
			end
	end
close scuur
deallocate scuur

實現一個卷遊標,逆序列印所有學生的 學號、課程號、成績資訊
在這裡插入圖片描述
原始碼:

--實現一個卷遊標,逆序列印所有學生的學號、課程號、成績資訊
--卷遊標
declare scuur scroll cursor for select * from sc order by sc.s# desc --卷遊標的申明scroll
open scuur
fetch next from scuur --利用遊標提取資料
while @@FETCH_STATUS=0--返回下一條的資料
	begin
		fetch next from scuur 
	end
--倒過來讀取資料
close scuur
deallocate scuur

重點語法介紹:

  • 在T-SQL中,Begin表示語句塊的開始;End表示語句塊的結束。Begin和End類似於C語言中表示語句塊的左花括號{ 和右花括號 }

  • 遊標的基本操作:
    –定義遊標命令
    declare demo1 cursor for select * from c for read only;
    –開啟遊標命令
    open demo1 ;
    –執行遊標命令
    fetch next from demo1;
    –關閉遊標命令
    close demo1;
    –刪除遊標命令
    deallocate demo1;

  • 遊標也可以看作是一個表中的記錄指標,該指標與某個查詢結果相聯絡。在某一時刻,該指標只指向一條記錄,即遊標是通過移動指向記錄的指標來處理資料的。當用戶在SQL Server Management Studio中瀏覽記錄時,總有一條記錄的前面有一個黑色的三角標識,該標識就好像是一個記錄指標。

如有錯誤,歡迎指正!