简体   繁体   中英

Update Query using Subquery

I would like to update my field TicketUser in one table where records are fetched from another table with the field CreatedBy .

I am facing the error below:

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

My query is as below:

UPDATE Incidence SET TicketUser = (select CreatedBy from AssignedRoles inner join Incidence on 
Incidence.RegistrationID=AssignedRoles.RegistrationID
    WHERE AssignedRoles.CreatedOn = Incidence.DateServed and TicketUser=0) 
          FROM Incidence INNER JOIN AssignedRoles on 
AssignedRoles.RegistrationID=Incidence.RegistrationID
          WHERE Incidence.RegistrationID = AssignedRoles.RegistrationID 

How do I resolve this?

As in the error, your subquery is returning more than one value and can't properly do your update. I'm not sure of the end result your looking for, but you could eliminate this with a TOP (1) added to your subquery as below, possibly with an ORDER BY depending on what you need to return.

UPDATE Incidence SET TicketUser = (select TOP(1) CreatedBy from AssignedRoles inner join Incidence on 
Incidence.RegistrationID=AssignedRoles.RegistrationID
    WHERE AssignedRoles.CreatedOn = Incidence.DateServed and TicketUser=0) 
          FROM Incidence INNER JOIN AssignedRoles on 
AssignedRoles.RegistrationID=Incidence.RegistrationID
          WHERE Incidence.RegistrationID = AssignedRoles.RegistrationID

I suspect you want a correlated subquery , not a join in the subquery. Then I am thinking you only want to update 0 values. So I am speculating that this is what you want:

UPDATE Incidence
    SET TicketUser = (select ar.CreatedBy
                      from AssignedRoles ar
                      where ar.RegistrationID = Incidence.RegistrationID and
                           ar.CreatedOn = Incidence.DateServed 
                     ) 
    WHERE TicketUser = 0;

I got rid of the join and the following SQL script worked for me.

update incidence

set ticketuser = Assignedroles.createdby from Assignedroles inner join incidence on  
Incidence.registrationID = Assignedroles.registrationid 
where  Incidence.registrationID = Assignedroles.registrationid  and 
Assignedroles.ModifiedOn = dateserved and incidence.ticketuser = 0

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