開始使用免費開始

建立階層式資料模型

在本練習中,你將透過建立 IT 資產的階層,來構建一個簡單的階層式資料模型。資產可以是 HardwareSoftwareSoftware 資產又可細分為 ApplicationTools,依此類推。階層如下圖所示。

若要刻畫這個階層,需要合適的資料結構。可以使用由子紀錄 ID 與父紀錄 ParentID 組成的資料模型來達成。ID 為 1 到 10 的連續數值。

你的任務是建立對應的 Equipment 資料表,並將資產 SoftwareMonitorMicrosoft Office 插入表中。請記得為每個資產設定正確的 ID,以達成預期的資產階層。

本練習屬於課程

SQL Server 的階層式與遞迴查詢

檢視課程

練習說明

  • 定義欄位 IDParentID 的型別為 INTID 不可為 NULLParentID 可以為 NULL
  • 以正確的 ID 將設備 Software 插入資料表。此軟體隸屬於 Asset
  • 以正確的 ID 將設備 Monitor 插入資料表。此顯示器隸屬於 Hardware
  • 以正確的 ID 將設備 Microsoft Office 插入資料表。此軟體隸屬於 Application

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

CREATE TABLE Equipment (   
    -- Define ID and ParentID 
	___ ___ NOT NULL,
    Equipment VARCHAR(255) NOT NULL,
    ___ ___ 
);

INSERT INTO Equipment VALUES (1,'Asset',NULL);
INSERT INTO Equipment VALUES (2,'Hardware',1);
-- Insert the type Software
INSERT INTO Equipment VALUES (___,____,1);
INSERT INTO Equipment VALUES (4,'Application',3);
INSERT INTO Equipment VALUES (5,'Tool',3);
INSERT INTO Equipment VALUES (6,'PC',2);
-- Insert the type Monitor 
INSERT INTO Equipment VALUES (___,'Monitor',2);
INSERT INTO Equipment VALUES (8,'Phone',2);
INSERT INTO Equipment VALUES (9,'IPhone',8);
-- Insert the type Microsoft Office 
INSERT INTO Equipment VALUES (___,___,4);

SELECT * 
FROM Equipment;
編輯並執行程式碼