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