一、當用一個表中的資料來更新另一個表中的資料,T-SQL提供多種寫法(下面列出了二種),但建議用第一種寫法,雖然傳統,但結構清晰。
並且要注意,當用一個表中的資料來更新另一個表中的資料時,二個表一定要有關聯!
1.
update t1
set t1.c2 = t2.c2
from t2
where t1.c1 = t2.c1
2.
Update t1
set t1.c2 = t2.c2
from t1 inner join t2
on t1.c1 = t2.c1
樣本:
UPDATE temp_Org_employee SET temp_Org_employee.mobile = c.tele FROM temp_Org_employee e INNER JOIN (SELECT a.name, b.ID, a.tele, b.mobile FROM EmplTeleTb a LEFT JOIN (SELECT * FROM temp_Org_employee WHERE DepartmentId IN (SELECT ID FROM org_Department WHERE CompanyID = 'T200812051418466710000194')) b ON a.Name = b.EmplName WHERE a.tele <> b.mobile) c ON e.ID = c.ID
樣本2:
UPDATE temp_Org_employee SET temp_Org_employee.mobile = c.tele FROM (SELECT a.name, b.ID, a.tele, b.mobile FROM EmplTeleTb a LEFT JOIN (SELECT * FROM temp_Org_employee WHERE DepartmentId IN (SELECT ID FROM org_Department WHERE CompanyID = 'T200812051418466710000194')) b ON a.Name = b.EmplName WHERE a.tele <> b.mobile) c WHERE temp_Org_employee.ID = c.ID
樣本3:
UPDATE temp_Org_employee SET mobile = c.tele FROM temp_Org_employee e,(SELECT a.name, b.ID, a.tele, b.mobile FROM EmplTeleTb a LEFT JOIN (SELECT * FROM temp_Org_employee WHERE DepartmentId IN (SELECT ID FROM org_Department WHERE CompanyID = 'T200812051418466710000194')) b ON a.Name = b.EmplName WHERE a.tele <> b.mobile) c WHERE e.ID = c.ID
二、FROM 子句中指定的表的別名不能作為 SET
column_name 子句中被修改欄位的限定符使用。
例如,下面的內容無效:
UPDATE temp_Org_employee
SET e.mobile = c.tele
FROM temp_Org_employee e,(SELECT a.name, b.ID, a.tele, b.mobile
FROM EmplTeleTb a
LEFT JOIN
(SELECT *
FROM temp_Org_employee
WHERE DepartmentId IN
(SELECT ID
FROM org_Department
WHERE CompanyID = 'T200812051418466710000194'))
b
ON a.Name = b.EmplName
WHERE a.tele <> b.mobile) c
WHERE e.ID = c.ID
若要使上例合法,請從列名中刪除別名 e或使用本身的表名