假设A表是主表,有单号order_id、开单人operator、开单日期oper_date、备注memo等;B表是副表,有单号order_id、序号id、商品编码code、商品名称name、备注memo等。A表的备注是有数据的,B表的备注没有数据,现在要把A表的数据更新到B表,并且B表有数据的不能更新了。A表与B表是以单号来关联的。更新数据的SQL语法如下:
update B set B.memo=A.memo from B,A
where A.order_id=B.order_id and (B.memo is null or B.memo=\'\');
A、B表的order_id是索引,而且是关联字段,所以要放在Where条件作为第一条件。B表的备注为空值,或等于没有值的,才能更新。
-----------------------------------------------------------
实例:
一、建立测试表
CREATE TABLE t_user (
ID int identity PRIMARY KEY,
UserID
varchar(50) not null,
UserName varchar(50) null,
deptID int not
null,
phone varchar(50) null,
fax varchar(50) null
)
CREATE TABLE t_dept (
ID int identity PRIMARY KEY,
DeptName varchar(50)
null,
phone varchar(50) null,
fax varchar(50) null
)
INSERT t_user
SELECT N\'001\',N\'张三\',1,N\'88888001\',N\'99999001\'
UNION ALL
SELECT N\'002\',N\'李四\',2,N\'88888002\',N\'99999002\'
UNION ALL SELECT
N\'003\',N\'王五\',2,N\'88888003\',N\'99999003\'
UNION ALL SELECT
N\'004\',N\'赵六\',3,N\'88888004\',N\'99999004\'
INSERT t_dept
SELECT N\'开发部\',N\'88888011\',N\'99999011\'
UNION ALL SELECT
N\'市场部\',N\'88888022\',N\'99999022\'
UNION ALL SELECT
N\'售后部\',N\'88888033\',N\'99999033\'
二、sql更新(每次执行update后都还原t_user数据)
1、update t_user set u.phone=d.phone, u.fax=d.fax from t_user u, t_dept d where u.deptID=d.ID
报错:无法绑定由多个部分组成的标识符 "u.phone"。
2、update u set u.phone=d.phone, u.fax=d.fax
from t_user u, t_dept d where u.deptID=d.ID
|
正确 select * from t_user
|
3、update t_user u set u.phone=d.phone, u.fax=d.fax from t_dept d where u.deptID=d.ID
报错:\'u\' 附近有语法错误。
4、update t_user set phone=d.phone, fax=d.fax from t_dept d where deptID=d.ID
正确,结果同2
转载自:http://blog.csdn.net/leamonjxl/article/details/6441669