Insert (SQL)

Bách khoa toàn thư mở Wikipedia

Câu lệnh SQL INSERT (có nghĩa là thêm) dùng để thêm dữ liệu vào một bảng trong cơ sở dữ liệu quan hệ.

Mục lục

[sửa] Cấu trúc cơ bản

Câu lệnh insert có cấu trúc như sau:

  • INSERT INTO table (column1, [column2, ... ]) VALUES (value1, [value2, ...])

Số lượng cột và giá trị trong câu lệnh phải bằng nhau. Nếu tên cột không được chỉ ra trong câu truy vấn, thì giá trị mặc định cho cột được sử dụng. The values specified (or implied) by the INSERT statement must satisfy all the applicable constraints (such as primary keys, CHECK constraints, and NOT NULL constraints). Nếu có lỗi xuất hiện do xung đột với hằng số thì sẽ không có hàng nào được thêm vào

Ví dụ:

INSERT INTO phone_book (name, number) VALUES ('John Doe', '555-1212');

Khi tất cả giá trị của các cột được chỉ ra thì ta có thể dùng cách viết thu gọn.

  • INSERT INTO table VALUES (value1, [value2, ...])

Ví dụ: (assuming that 'name' and 'number' are the only columns in the 'phone_book' table):

INSERT INTO phone_book VALUES ('John Doe', '555-1212');

[sửa] Tùy chọn

An optional SQL feature (since SQL-92) is the use of row value constructors to insert multiple rows at a time:

  • INSERT INTO table (column1, [column2, ... ]) VALUES (value1a, [value1b, ...]), (value2a, [value2b, ...]), ...

This optional feature is supported by DB2 and MySQL.

Example (assuming that 'name' and 'number' are the only columns in the 'phone_book' table):

INSERT INTO phone_book VALUES ('John Doe', '555-1212'), ('Peter Doe', '555-2323');

- which may be seen as a shorthand for

 INSERT INTO phone_book VALUES ('John Doe', '555-1212');
 INSERT INTO phone_book VALUES ('Peter Doe', '555-2323');

Example (creating records in one table from another table / copying records using insert):

 INSERT INTO phone_book2 SELECT * FROM phone_book
 WHERE NAME IN ('John Doe', 'Peter Doe')            

[sửa] Retrieving the key

Database designers that use a surrogate key as the primary key for every table will run into the occasional scenario where they need to automatically retrieve the database generated primary key from a SQL INSERT query for use in another SQL INSERT query. Since SQL INSERT does not return row data, it becomes necessary to implement a workaround to such scenarios. Common implementations include:

  • Using a database-specific stored procedure.
  • Using a database-specific SELECT query on a temporary table containing last inserted row(s).
  • Using a unique combination of elements from the original SQL INSERT in a SELECT statement.
  • Using a GUID in the SQL INSERT query and retrieving it in a SELECT statement.

[sửa] Xem thêm