SQL UPDATE 语句
SQL UPDATE 语句
UPDATE语句用于修改表中的现有记录。
更新语法
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
注意:更新表中的记录时要小心!请注意UPDATE语句中的WHERE子句.WHERE子句指定应更新的记录。如果省略WHERE子句,表中的所有记录都将更新!
演示数据库
以下是Northwind示例数据库中“Customers”表的选择:
CustomerID |
CustomerName |
ContactName |
Address |
City |
PostalCode |
Country |
1 |
Alfreds Futterkiste |
Maria Anders |
Obere Str. 57 |
Berlin |
12209 |
Germany |
2 |
Ana Trujillo Emparedados y helados |
Ana Trujillo |
Avda. de la Constituciуn 2222 |
Mйxico D.F. |
05021 |
Mexico |
3 |
Antonio Moreno Taquerнa |
Antonio Moreno |
Mataderos 2312 |
Mйxico D.F. |
05023 |
Mexico |
4 |
Around the Horn |
Thomas Hardy |
120 Hanover Sq. |
London |
WA1 1DP |
UK |
5 |
Berglunds snabbkцp |
Christina Berglund |
Berguvsvдgen 8 |
Luleе |
S-958 22 |
Sweden |
更新表
以下SQL语句使用新联系人
和新城市更新第一个客户(CustomerID = 1)。
实例
UPDATE Customers
SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'
WHERE CustomerID = 1;
运行实例»
“Customers”表中的查询如下所示:
CustomerID |
CustomerName |
ContactName |
Address |
City |
PostalCode |
Country |
1 |
Alfreds Futterkiste |
Alfred Schmidt |
Obere Str. 57 |
Frankfurt |
12209 |
Germany |
2 |
Ana Trujillo Emparedados y helados |
Ana Trujillo |
Avda. de la Constituciуn 2222 |
Mйxico D.F. |
05021 |
Mexico |
3 |
Antonio Moreno Taquerнa |
Antonio Moreno |
Mataderos 2312 |
Mйxico D.F. |
05023 |
Mexico |
4 |
Around the Horn |
Thomas Hardy |
120 Hanover Sq. |
London |
WA1 1DP |
UK |
5 |
Berglunds snabbkцp |
Christina Berglund |
Berguvsvдgen 8 |
Luleе |
S-958 22 |
Sweden |
更新多个记录
它是WHERE子句,用于确定要更新的记录数。
以下SQL语句对于“Country”为“Mexico”的所有记录的联系人名称更新为“Juan”:
实例
UPDATE Customers
SET ContactName='Juan'
WHERE Country='Mexico';
运行实例»
“Customers”表中的查询如下所示:
CustomerID |
CustomerName |
ContactName |
Address |
City |
PostalCode |
Country |
1 |
Alfreds Futterkiste |
Alfred Schmidt |
Obere Str. 57 |
Frankfurt |
12209 |
Germany |
2 |
Ana Trujillo Emparedados y helados |
Juan |
Avda. de la Constituciуn 2222 |
Mйxico D.F. |
05021 |
Mexico |
3 |
Antonio Moreno Taquerнa |
Juan |
Mataderos 2312 |
Mйxico D.F. |
05023 |
Mexico |
4 |
Around the Horn |
Thomas Hardy |
120 Hanover Sq. |
London |
WA1 1DP |
UK |
5 |
Berglunds snabbkцp |
Christina Berglund |
Berguvsvдgen 8 |
Luleе |
S-958 22 |
Sweden |
更新警告!
更新记录时要小心。如果省略WHERE子句,则将更新所有记录!
实例
UPDATE Customers
SET ContactName='Juan';
运行实例»
“Customers”表中的查询如下所示:
CustomerID |
CustomerName |
ContactName |
Address |
City |
PostalCode |
Country |
1 |
Alfreds Futterkiste |
Juan |
Obere Str. 57 |
Frankfurt |
12209 |
Germany |
2 |
Ana Trujillo Emparedados y helados |
Juan |
Avda. de la Constituciуn 2222 |
Mйxico D.F. |
05021 |
Mexico |
3 |
Antonio Moreno Taquerнa |
Juan |
Mataderos 2312 |
Mйxico D.F. |
05023 |
Mexico |
4 |
Around the Horn |
Juan |
120 Hanover Sq. |
London |
WA1 1DP |
UK |
5 |
Berglunds snabbkцp |
Juan |
Berguvsvдgen 8 |
Luleе |
S-958 22 |
Sweden |