I have four tables named Task, ProjectTeamMemeber, Hierarchy and Assignment.
Each Task is related to a Project through a Heirarchy and each Project has Team members which can be seen through ProjectTeamMember.
select TH.TaskId As TaskID, P.PersonId As PersonID from Task T Inner join Hierarchy TH on T.Id = TH.TaskId Inner join ProjectTeamMemeber PTM on TH.ProjectId = P.TaskId where T.name = 'work' The above query returns all the person allocated to a certain project where the Task name is 'work'
TaskId PersonId 1347 50 1350 50 3377 50 3403 598 3411 1450 3411 1454 3411 1472 And I have another table Assigment from which i can see the Id of persons which are assigned to a particular task.
select T.Id, A.PersonId from Task T inner join Assignment A ON T.Id = A.TaskId where T.name = 'work' The above query return all the persons allocated to Task called 'work'.
TaskId PersonId 1347 50 1350 50 3411 1472 Now, what i have to achieve here is to allocate all the persons to a task with name 'work' which are allocated to projects which have a task name 'work'. Putting it simply i have to write some sql statements after which my second query above writtens the same result as my first query.
So far, I have tried to do this with cusrsors but it would not work. Below is the code for that
DECLARE @TaskId int DECLARE @PersonId int DECLARE @Id int DECLARE db_cursor CURSOR FOR select TH.TaskId As TaskID, P.PersonId As PersonID from Task T Inner join Hierarchy TH on T.Id = TH.TaskId Inner join ProjectTeamMemeber PTM on TH.ProjectId = P.TaskId where T.name = 'work' OPEN db_cursor FETCH NEXT FROM db_cursor INTO @TaskId, @PersonId BEGIN If not exists ( select 1 from Assignment where TaskId=@TaskId and PersonId=@PersonId) BEGIN EXEC GetUniqueIdentifier @Id OUTPUT; Insert INTO Assignment (Id, TaskId, PersonId) values (@Id, @TaskId, @PersonId) END END CLOSE db_cursor DEALLOCATE db_cursor (NOTE : I have to use the statement EXEC GetUniqueIdentifier @Id OUTPUT; to generate the Id. I know there maybe different and more reliable ways to generate Ids but due to some limitations i cannot change how the Id is being generated.)
EDIT :
Based on LAMAK answer i ran this
DECLARE @ids int INSERT INTO Assignment (Id, TaskId, PersonId) EXEC GetUniqueIdentifier @ids OUTPUT; SELECT @ids, TH.TaskId As TaskID, P.PersonId As PersonID, FROM Task T INNER JOIN Hierarchy TH on T.Id = TH.TaskId INNER JOIN ProjectTeamMember P on TH.ProjectId = P.TaskId WHERE T.name = 'Customer work' AND NOT EXISTS( SELECT 1 FROM Assignment WHERE TaskID = TH.TaskId AND PersonId = P.PersonId)