Sql Update語句使用表別名的方法
使用Sql Update語句,同樣可以使用表別名,下面就將為您介紹Sql Update語句使用表別名的方法,希望對您學(xué)習(xí)Sql Update語句有所啟迪。
在編寫Sql腳本時通過表別名可以大大縮減Sql代碼,同時表別名也是解決同表多次引用的手段之一。在select中使用表別名大家應(yīng)該都很熟悉了:
- select * from TableA as A inner join TableB as B on A.Key1 = B.Key1
但是在Sql Update中使用表別名可能就沒那么多人知道了。
- update T
- set T.Key1 = 'xxxx'
- from TableA T
這些天在寫Sql Update語句腳本的時候需要引用兩次同個表對象,如果直接像下面這樣引用兩次TableA則會拋出“The multi-part identifier ‘TableA.Index’ could not be bound”的錯誤。這是因為Sql引擎無法知道你在where子句中的TableA到底指的是要Update的表還是from后面的表。
- update TableA
- set TTableA.NextKey = T.Key
- from TableA T
- where T.Index = TableA.Index + 1
#p#如果不對Update后面的TableA使用別名的話,我們只能通過以下方法來實現(xiàn)。
- update TableA
- set TTableA.NextKey = T.Key
- from
- (
- select * from TableA
- )T
- where T.Index = TableA.Index + 1
使用別名可以得到更簡潔的寫法:
- update T1
- set T1.NextKey = T2.Key
- from TableA T1, TableA T2
- whereT2.Index = T1.Index + 1
【編輯推薦】