declare @email as nvarchar(256)
DECLARE
db_cursor CURSOR FOR
SELECT [Email]
FROM [Users]
group by [Email]
having count([Email])>1
OPEN
db_cursor
FETCH NEXT FROM db_cursor INTO
@email
WHILE @@FETCH_STATUS = 0
BEGIN
UPDATE dbo.UserPortals
SET
IsDeleted
= 1
WHERE
PortalId = 0
and UserId in (
SELECT [UserID]
FROM [Users]
where Email =@email and ([UserID] not in (SELECT [UserID]
FROM [RelatedTable1]
where [UserID] in(SELECT [UserID]
FROM [Users]
where Email =@email)
UNION
SELECT [UserID]
FROM [RelatedTable2]
where [UserID] in(SELECT [UserID]
FROM [Users]
where Email =@email))))
FETCH NEXT FROM
db_cursor INTO @email
END
CLOSE
db_cursor
DEALLOCATE db_cursor