2014-12-31 100 views
2

在執行此查詢時,我在WHERE子句附近出現錯誤。更新語句中具有選擇子查詢的嵌套SQL查詢

update AssetData set EmployeeName = ISNULL(EmployeeName,'') [email protected] 
where ([AssetNumber] like'%" + WA_number.Text + "%') 
and ID IN (SELECT ID FROM AssetData ORDER BY ID DESC 
where ([AssetNumber] like'%" + WA_number.Text + "%') LIMIT 1) 

有人請幫我弄清楚這有什麼問題嗎?

+1

的數據庫,你的工作嗎? – th1rdey3

回答

3
and ID IN (SELECT ID FROM AssetData ORDER BY ID DESC 
where ([AssetNumber] like'%" + WA_number.Text + "%') LIMIT 1) 

where應該在ORDER BY之前成爲。儘管合法,in (... limit 1)沒有意義,因爲in應與列表一起使用。我建議使用= max(ID)代替

and ID = (SELECT max(ID) FROM AssetData where [AssetNumber] like'%" + WA_number.Text + "%') 

,你可以留下你的where子句的第一部分,因爲ID您一個WHEREORDER BY之前有同樣的標準已經

update AssetData set EmployeeName = ISNULL(EmployeeName,'') [email protected] 
where ID = (SELECT max(ID) FROM AssetData where [AssetNumber] like'%" + WA_number.Text + "%'); 
0

試試這個,如果你想根據ID選擇最新添加的行

UPDATE AssetData set EmployeeName = ISNULL(EmployeeName,'') [email protected] 
WHERE([AssetNumber] like'%" + WA_number.Text + "%') 
AND ID IN (SELECT MAX(ID) FROM AssetData 
where ([AssetNumber] like'%" + WA_number.Text + "%') LIMIT 1) 
+0

錯誤 - 「ORDER BY子句在視圖,內聯函數,派生表,子查詢和公用表表達式中無效,除非還指定了TOP或FOR XML」 – PuRaK

+0

沒錯,但我希望它選擇最後一個ID最新添加的行)從我的表中AssetData = ...這就是爲什麼我需要DESC – PuRaK

2

試試這個

我認爲你正在使用SQL Server

update AssetData set EmployeeName = ISNULL(EmployeeName,'') [email protected] 
where [AssetNumber] like'%" + WA_number.Text + "%' 
and ID IN (SELECT TOP 1 ID FROM AssetData 
where [AssetNumber] like'%" + WA_number.Text + "%' 
ORDER BY ID DESC) 
1

匹配。此外,基於錯誤消息,很明顯你使用SQL Server,所以你需要TOP代替LIMIT

update AssetData 
set EmployeeName = ISNULL(EmployeeName,'') [email protected] 
where ([AssetNumber] like'%" + WA_number.Text + "%') 
     and ID IN (SELECT TOP 1 ID 
        FROM AssetData 
        WHERE ([AssetNumber] like'%" + WA_number.Text + "%') 
        ORDER BY ID DESC 
        ) 

同樣,你可以選擇MAX()

update AssetData 
set EmployeeName = ISNULL(EmployeeName,'') [email protected] 
where ([AssetNumber] like'%" + WA_number.Text + "%') 
     and ID IN (SELECT MAX(ID) 
        FROM AssetData 
        WHERE ([AssetNumber] like'%" + WA_number.Text + "%') 
        )