在从自身更新同一个表时,如何对表进行别名?
我的查询:
update accounts set adusername = x.adusername
from Accounts x
where x.AccountName = accounts.rev and x.ok>10 and accounts.ok in (0,1,2,3)
and x.ADUserName is not null and accounts.ADUserName is null
错误
Msg 4104, Level 16, State 1, Line 9
The multi-part identifier "accounts.rev" could not be bound.
Msg 4104, Level 16, State 1, Line 9
The multi-part identifier "accounts.ok" could not be bound.
Msg 4104, Level 16, State 1, Line 9
The multi-part identifier "accounts.ok" could not be bound.
Msg 4104, Level 16, State 1, Line 9
The multi-part identifier "accounts.ok" could not be bound.
Msg 4104, Level 16, State 1, Line 9
The multi-part identifier "accounts.ok" could not be bound.
Msg 4104, Level 16, State 1, Line 9
The multi-part identifier "accounts.ADUserName" could not be bound.
答案 0 :(得分:3)
这个怎么样:
UPDATE a
SET a.adusername = x.adusername
FROM Accounts x
INNER JOIN Accounts a ON x.AccountName = a.rev
WHERE x.ok>10
AND a.ok in (0,1,2,3)
AND x.ADUserName is not null
AND a.ADUserName is null
答案 1 :(得分:2)
这仅适用于子查询或联接:
UPDATE accounts SET adusername = 'ABC'
FROM Accounts AS x
WHERE x.ID IN (SELECT ID FROM Accounts WHERE Accounts.Username = 'XYZ') AND x.OK in (0,1,2,3)
或
UPDATE accounts SET adusername = x.adusername
FROM Accounts
JOIN Accounts AS x ON Accounts.ID = x.ID
WHERE x.Username = 'XYZ' AND Accounts.OK in (0,1,2,3)
应该做的。