Correlated subquery in SQL

后端 未结 2 1234
野性不改
野性不改 2021-01-23 23:12

I have two tables: Table A and Table B

  1. Table A and Table B both have RowId column.
  2. Table A and Table B both have ModifiedAt col
相关标签:
2条回答
  • 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
    
    0 讨论(0)
  • 2021-01-23 23:54

    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
    
    0 讨论(0)
提交回复
热议问题