跳轉到內容

結構化查詢語言/插入 1

來自華夏公益教科書



提示:小心並停用 AUTOCOMMIT


INSERT 命令將一個或多個新行儲存到一個表中。新行的內容由固定值或執行時評估的 SELECT 結果組成。因此,有兩種不同的語法可以完成這項工作。

靜態插入

[編輯 | 編輯原始碼]
-- The static version of the INSERT command
INSERT INTO <tablename> (<list_of_columnnames>)
VALUES                  (<list_of_values>),
                        (<list_of_values>),
                        (<list_of_values>),
                             ... ;


在表名之後,我們可以列出受影響的列,並在關鍵字 'VALUES' 之後宣告一個或多個值列表以插入。每個值列表代表一行新行。列和值的列表必須一致,這樣列表條目數量相同,資料型別相關聯。

-- One value list results in one new row.
INSERT INTO person (id,  firstname,       lastname,    date_of_birth,     place_of_birth, ssn,           weight)
VALUES             (91,  'Larry, no. 91', 'Goldstein', DATE'1970-11-20', 'Dallas',        '078-05-1120', 95);
COMMIT;

-- The SQL standard - but not all implementations, in particular Oracle - supports a 'row value constructor' by
-- enumerate values inside a pair of parenthesis as shown in the above green box.  
-- Three lists of values (= row value constructors) result in three new rows. Please note the comma after all 
-- but the last one.
INSERT INTO person (id,  firstname,       lastname,    date_of_birth,     place_of_birth, ssn,           weight)
VALUES             (92,  'Larry, no. 92', 'Goldstein', DATE'1970-11-20', 'Dallas',        '078-05-1120', 95),
                   (93,  'Larry, no. 93', 'Goldstein', DATE'1970-11-20', 'Dallas',        '078-05-1120', 95),
                   (94,  'Larry, no. 94', 'Goldstein', DATE'1970-11-20', 'Dallas',        '078-05-1120', 95);
COMMIT;


我們可以選擇任意列順序,但列名和值必須一致。

-- Sometimes things are scrambled. Maybe confusing, but works fine. See weight and id.
INSERT INTO person (date_of_birth, firstname, ssn, lastname, place_of_birth, weight, id)
VALUES             (DATE'1970-11-20', 'Larry, no. 95', '078-05-1120', 'Goldstein', 'Dallas', 95, 95);
COMMIT;


我們可以省略不必要的列。

-- Depending on CREATE TABLE statement the missing columns will get the 'null special marker' or a default value.
INSERT INTO person (id,  firstname,       lastname,     weight)
VALUES             (96,  'Larry, no. 96', 'Goldstein',  95);
COMMIT;


清理您的表格。

DELETE FROM person WHERE id BETWEEN 91 AND 96;
COMMIT;

動態插入

[編輯 | 編輯原始碼]

與上一段不同,我們可以插入在執行時從任何表、函式或計算中評估的動態值,而不是固定值。即使新行的數量也可以是動態的。所有這些都在一個子選擇中完成,它替換 VALUE 子句。我們在頁面 高階插入 中解釋了這種技術。有關列數和順序或省略值的規則仍然有效。

為 Peter Hufington 先生插入一個新行,其體重為 67 公斤。他出生於洛杉磯。

點選檢視解決方案
-- Choose any free id
INSERT INTO person (id,  firstname,       lastname,     weight, place_of_birth)
VALUES             (81,  'Peter, no. 81', 'Hufington',  67,     'Los Angeles');
COMMIT;
-- Check your result
SELECT * FROM person;


華夏公益教科書