SQL CREATE 關鍵字
CREATE DATABASE
The CREATE DATABASE
command is used is to create a new SQL database.
The following SQL creates a database called "testDB"
示例
CREATE DATABASE testDB;
Tip: Make sure you have admin privilege before creating any database. Once a database is created, you can check it in the list of databases with the following SQL command: SHOW DATABASES;
CREATE TABLE
CREATE TABLE
命令在資料庫中建立一個新表。
以下 SQL 建立了一個名為 "Persons" 的表,該表包含五個列:PersonID、LastName、FirstName、Address 和 City。
示例
CREATE TABLE Persons (
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
使用另一個表建立 CREATE TABLE
The following SQL creates a new table called "TestTables" (which is a copy of two columns of the "Customers" table):
示例
CREATE TABLE TestTable AS
SELECT customername, contactname
FROM customers;
CREATE INDEX
CREATE INDEX
命令用於在表中建立索引(允許重複值)。
索引用於非常快速地從資料庫中檢索資料。使用者看不到索引,它們僅用於加快搜索/查詢的速度。
以下 SQL 在 "Persons" 表的 "LastName" 列上建立了一個名為 "idx_lastname" 的索引
CREATE INDEX idx_lastname
ON Persons (LastName);
如果你想在列組合上建立索引,可以將列名放在括號內,用逗號分隔。
CREATE INDEX idx_pname
ON Persons (LastName, FirstName);
注意:建立索引的語法因資料庫而異。因此:請檢查你的資料庫中建立索引的語法。
注意:更新帶索引的表比更新不帶索引的表花費的時間更多(因為索引也需要更新)。因此,僅在經常搜尋的列上建立索引。
CREATE UNIQUE INDEX
The CREATE UNIQUE INDEX
command creates a unique index on a table (no duplicate values allowed)
The following SQL creates an index named "uidx_pid" on the "PersonID" column in the "Persons" table
CREATE UNIQUE INDEX uidx_pid
ON Persons (PersonID);
CREATE VIEW
The CREATE VIEW
command creates a view.
A view is a virtual table based on the result set of an SQL statement.
The following SQL creates a view that selects all customers from Brazil
示例
CREATE VIEW [Brazil Customers] AS
SELECT CustomerName, ContactName
FROM Customers
WHERE Country = "Brazil";
CREATE OR REPLACE VIEW
The CREATE OR REPLACE VIEW
command updates a view.
The following SQL adds the "City" column to the "Brazil Customers" view
示例
CREATE OR REPLACE VIEW [Brazil Customers] AS
SELECT CustomerName, ContactName, City
FROM Customers
WHERE Country = "Brazil";
Query The View
We can query the view above as follows
示例
SELECT * FROM [Brazil Customers];
CREATE PROCEDURE
The CREATE PROCEDURE
command is used to create a stored procedure.
儲存過程是預先準備好的 SQL 程式碼,您可以儲存它,以便程式碼可以一次又一次地重用。
The following SQL creates a stored procedure named "SelectAllCustomers" that selects all records from the "Customers" table
示例
CREATE PROCEDURE SelectAllCustomers
AS
SELECT * FROM Customers
GO;
如下執行上面的儲存過程
示例
EXEC SelectAllCustomers;