2017-08-01 20 views
1

我有下面的SQL查詢,這個查詢檢測缺少序列的目的:例如,如果我有seq 1,2,3,5。它應該更新記錄5並顯示消息「以前的序列丟失」。在同一個表上使用內部連接的SQL - (Update,From)語句

正在嘗試如下,但它給錯誤在第1行是TblA是模糊的,從inner join語句來做到使用更新此邏輯:

update  dbo.TblA 
set   Msg = 'Previous sequence is missing' 
from  dbo.TblA R1 
left join dbo.TblA R2 
on   (R2.Sequence = R1.Sequence -1) 
and   (R2.StatementNumber = R1.StatementNumber) 
where  R2.TransID is null and R1.Sequence <> 1 

我知道,這可以很容易通過嵌套查詢固定的,但我思考更有組織和整潔的東西:)

+0

爲什麼不是子查詢「有組織和整潔」? – Richard

+0

使用你定義的別名:更新R1設置Msg ='上一個.... .... –

+0

@MarcGuillot這給了「多部分標識符」錯誤 –

回答

1

使用此查詢。它沒有在表上設置別名來更新,只是在左連接上。

update  dbo.TblA 
set   Msg = 'Previous sequence is missing' 
from  dbo.TblA 
left join dbo.TblA R 
on   (R.Sequence = TblA.Sequence -1) 
and   (R.StatementNumber = TlbA.StatementNumber) 
where  R.TransID is null and Tbla.Sequence <> 1 
+0

儘管我沒有得到邏輯爲什麼這是行得通的......但它的工作正常......非常感謝 –

+1

Sufyan,正如你對評論所說的,你不能通過別名執行更新(多部分標識符錯誤)。所以我們在加入TablA時不會設置兩個別名,我們只爲左連接設置一個別名(這不是我們正在更新的)。 –