1

I am trying to update multiple rows in one table, based on a select statement on another table.

This is my query:

UPDATE dbo.[user_message_content]
SET [status] = 1
WHERE [message_id] = (SELECT [message_id] FROM dbo.[user_message] WHERE [receiver_id] = @userID)
AND [status] = 0

This select statement may return multiple rows, which leads me to this error:

Msg 512, Level 16, State 1, Procedure usp_profileUserMessageMarkAsRead, Line 11 Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

What is the correct way to achieve what I need?

Thanks very much

3 Answers 3

5

If you want to update all those records, change the = to IN:

UPDATE dbo.[user_message_content]
SET [status] = 1
WHERE [message_id] IN 
    ( SELECT [message_id] FROM dbo.[user_message] WHERE [receiver_id] = @userID )
AND [status] = 0
Sign up to request clarification or add additional context in comments.

Comments

1

You can also use UPDATE with FROM clause http://msdn.microsoft.com/en-us/library/aa260662(SQL.80).aspx.

USE tempdb; 
    GO

    create table #user_message_content([status] int, message_id int)
    create table #user_message (message_id int,receiver_id int)

    declare @UserID int

    UPDATE mc
    SET mc.[status] = 1
    FROM #user_message_content mc join #user_message m on mc.message_id = m.message_id 
    WHERE m.receiver_id = @userID
          AND mc.[status]=0;

    drop table #user_message_content
    drop table #user_message

Comments

0

I think you need to use a join to do this

USE dbo; // Sets the current database to dbo, I did this for readability

UPDATE user_message_content join user_message on user_message_content.message_id = user_message.message_id 
SET user_message_content.status = 1
WHERE user_message.receiver_id = @userID;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.