I have two tables: Table A and Table B
RowId
column. ModifiedAt
col
DECLARE @RowId INT
DECLARE CurRowId CURSOR FOR SELECT RowId FROM Patients
OPEN CurRowId
FETCH NEXT FROM CurRowId INTO @RowId
WHILE @@FETCH_STATUS = 0
BEGIN
if not exists (select * from dbo.ResultsStored where ModifiedAt >
(select ModifiedAt from dbo.Patients where RowId =
@RowId))
begin
print'not exists'
end
else
begin
print 'exists'
END
FETCH NEXT FROM CurRowId INTO @RowId
END
The problem is in your data. If I understand correctly you want to know if there are such rows in Results which date is greater then Patients date. If no such row is found then it is OK.
If so your query looks correct. You can directly select incorrect data by:
SELECT *
FROM Patients p
CROSS APPLY ( SELECT MAX(ModifiedAt) AS ModifiedAt
FROM ResultsStored rs
WHERE p.RowId = rs.RowId
) a
WHERE a.ModifiedAt > p.ModifiedAt