茫茫網海中的冷日 - 對這文章發表回應
茫茫網海中的冷日
         
茫茫網海中的冷日
發生過的事,不可能遺忘,只是想不起來而已!
 恭喜您是本站第 1671880 位訪客!  登入  | 註冊
主選單

Google 自訂搜尋

Goole 廣告

隨機相片
PIMG_00012.jpg

授權條款

使用者登入
使用者名稱:

密碼:


忘了密碼?

現在就註冊!

對這文章發表回應

發表限制: 非會員 可以發表

發表者: 冷日 發表時間: 2019/7/29 13:46:45

Oracle 如何做到 SQL Server 的 Identity 欄位型態

在 DB table 規劃時,內部使用的 primary key 欄位常見用法分成兩派:使用 int 或是 GUID,在 SQL Server 上兩種做法都有對應的欄位型態,而在 Oracle 上就得要自行處理了,以 int 做法為例,在 SQL Server 中實作的欄位型態為 Identity,是一種自動累加固定值的識別碼,馬上來看看該如何在 Oracle 上實作 Identity 囉

實作做法說明

  1. 依實際需求建立 table 及欄位,並指定 primary key 欄位為 number 型態
  2. 建立 oracle sequence (序列) 用來取號
  3. 建立 trigger 在 insert data 時從 sequence 取號塞值

1. 建立 table

請依實際需求調整 table 欄位

  • 需要 primary key 為 number(10, 0)not null

    我這邊使用 Id 為欄位名稱

  • 指定 constraint

  • 語法範例


    create table UserProfile
    (
    Id number(10, 0) not null,
    Name VARCHAR2(50) not null,
    BirthDay date not null,
    Addr VARCHAR2(250) not null,
    constraint PK_UserProfile primary key (Id)
    )

2. 建立 Oracle Sequence

  • 用來自動循序增加數字
  • 語法範例


    create sequence SQ_UserProfile

3. 建立 Trigger

  • 在 insert 資料前到 sequence 取號寫入 primary key 欄位
  • 語法範例


    create or replace trigger TR_UserProfile
    before insert on UserProfile
    for each row
    begin
    select SQ_UserProfile.nextval into :new.Id from dual;
    end;

實際效果

  • 輸入時指定 100

    1input

  • 儲存 1

    2save

心得

一直以來都是使用 SQL Server 從來沒想過原來其他 db 沒有 identity 欄位型態,本來也沒想到可以這麼做,是使用 code first 產生 pl-sql 時發現原來 oracle 的 identity 可以透過上述方式建立,特別筆記一下

參考資訊


原文出處:Oracle 如何做到 SQL Server 的 Identity 欄位型態 - Yowko's Notes
內容圖示
url email imgsrc image code quote
樣本
bold italic underline linethrough   












 [詳情...]
validation picture

注意事項:
預覽不需輸入認證碼,僅真正發送文章時才會檢查驗證碼。
認證碼有效期10分鐘,若輸入資料超過10分鐘,請您備份內容後,重新整理本頁並貼回您的內容,再輸入驗證碼送出。

選項

Powered by XOOPS 2.0 © 2001-2008 The XOOPS Project|