在更新语句中具有select子查询的嵌套SQL查询

时间:2014-12-31 04:47:17

标签: sql asp.net database

执行此查询时,WHERE子句附近出现错误。

update AssetData set EmployeeName = ISNULL(EmployeeName,'') +@reasEmp 
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)

有人请帮我弄清楚这有什么问题?

4 个答案:

答案 0 :(得分: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已经符合相同的标准

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

答案 1 :(得分:2)

试试这个

我认为你正在使用SQL SERVER

update AssetData set EmployeeName = ISNULL(EmployeeName,'') +@reasEmp 
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)

答案 2 :(得分:1)

ORDER BY之前您有WHERE。此外,基于错误消息,很明显您正在使用SQL Server,因此您需要TOP而不是LIMIT

update AssetData 
set EmployeeName = ISNULL(EmployeeName,'') +@reasEmp 
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,'') +@reasEmp 
where ([AssetNumber] like'%" + WA_number.Text + "%') 
        and ID IN (SELECT MAX(ID)
                    FROM AssetData 
                    WHERE ([AssetNumber] like'%" + WA_number.Text + "%') 
                    )

答案 3 :(得分:0)

如果要根据ID

选择最新添加的行,请尝试此选项
UPDATE AssetData set EmployeeName = ISNULL(EmployeeName,'') +@reasEmp 
WHERE([AssetNumber] like'%" + WA_number.Text + "%') 
AND ID IN (SELECT MAX(ID) FROM AssetData
where ([AssetNumber] like'%" + WA_number.Text + "%') LIMIT 1)