简体   繁体   中英

UPDATE Sql cannot have aggregate in set

What's the work around to this error:

An aggregate may not appear in the set list of an UPDATE statement.

I've looked at a few examples but not really sure.

This is what I have now:

 UPDATE UserAnswer 
 SET userId = (SELECT id FROM Users WHERE id=max(id)) 
 WHERE userId = NULL

This may solve the issue, you need to make the max in the select list.

UPDATE UserAnswer 
SET userId = (SELECT Max(id) FROM Users) 
WHERE userId is NULL

You can try MAX OR Order By :

MAX:

UPDATE UserAnswer 
SET userId = (SELECT MAX(id) FROM Users) 
WHERE userId = NULL

Order By:

UPDATE UserAnswer 
SET userId = (SELECT TOP(1) id FROM Users Order By id DESC) 
WHERE userId = NULL

Try using a variable, like this:

DECLARE @maxId INT;

SELECT @maxId = MAX(id)
FROM Users;

UPDATE UserAnswer
SET userId = @maxId
WHERE userId IS NULL;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM