IN query in SQL Server

2ic8powd  于 2023-03-22  发布在  SQL Server
关注(0)|答案(2)|浏览(204)

Is this structure with IN is right or wrong this gives me error

SELECT TblProjectResources.UserId 
FROM TblTasks,TblProjectResources 
WHERE TblTasks.ProjectId=TblProjectResources.ProjectId 
AND TblTasks.TaskId=@TaskId AND TblProjectResources.IsRemoved=0 
AND TblProjectResources.UserId IN(
     (SELECT UserId 
      FROM TblProjectResources 
      WHERE IsRemoved=0 
      AND ProjectApproval=1 
      AND ProjectId=@ProjectId) 
     or 
     (SELECT TblAssignments.AssigneeId 
      FROM TblTasks,TblAssignments 
      WHERE TblTasks.TaskId=TblAssignments.AssignmentEntityId 
      AND TblAssignments.AssignmentEntity='Task' 
      AND TblTasks.TaskId=@TaskId) 
     or 
      (SELECT UserId FROM TblProjects WHERE ProjectId=@ProjectId)
)
isr3a4wc

isr3a4wc1#

I think you are trying to use TblProjectResources.UserId IN trice with OR try like this:

AND (TblProjectResources.UserId IN
         (SELECT UserId 
         FROM TblProjectResources 
         WHERE IsRemoved=0 
         AND ProjectApproval=1 
         AND ProjectId=@ProjectId) 
     OR
     TblProjectResources.UserId IN 
         (SELECT TblAssignments.AssigneeId 
         FROM TblTasks,TblAssignments 
         WHERE TblTasks.TaskId=TblAssignments.AssignmentEntityId 
         AND TblAssignments.AssignmentEntity='Task' 
         AND TblTasks.TaskId=@TaskId) 
     OR
     TblProjectResources.UserId IN
      (SELECT UserId FROM TblProjects WHERE ProjectId=@ProjectId)
)
vshtjzan

vshtjzan2#

@hims056 answer should work for you. Just as an alternate, you can try replace the OR with UNION / UNION ALL instead. That should work too.

SELECT TblProjectResources.UserId 
FROM TblTasks,TblProjectResources 
WHERE TblTasks.ProjectId=TblProjectResources.ProjectId 
AND TblTasks.TaskId=@TaskId AND TblProjectResources.IsRemoved=0 
AND TblProjectResources.UserId IN(
     (SELECT UserId 
      FROM TblProjectResources 
      WHERE IsRemoved=0 
      AND ProjectApproval=1 
      AND ProjectId=@ProjectId) 
     UNION 
     (SELECT TblAssignments.AssigneeId 
      FROM TblTasks,TblAssignments 
      WHERE TblTasks.TaskId=TblAssignments.AssignmentEntityId 
      AND TblAssignments.AssignmentEntity='Task' 
      AND TblTasks.TaskId=@TaskId) 
     UNION 
      (SELECT UserId FROM TblProjects WHERE ProjectId=@ProjectId)
)

相关问题