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;