Skip to content
Advertisement

Looping in SQL with TempTable

I am new to SQL Server, can you please help me to write query for my scenario?

I have this Table1 :

PostingDate     ReturnCheckReason   PaymentStatus   PolicyNumber
----------------------------------------------------------------
7/23/2020 15:30 Null                    Payment         1234
8/6/2020 17:40  Null                    Payment         1234
8/4/2020 14:29  Null                    Payment         1234
8/5/2020 6:09   Null                    Payment         1234
8/5/2020 12:47  Cancel Payment          Return          1234

Input to my stored procedure is a PolicyNumber e.g 1234 and the code should return 5 rows.

I need to cover these cases:

  1. If the first payment is not cancelled, I need return that row.

  2. If the first payment is cancelled, look for a next non-cancelled payment. If a next payment is found that was not cancelled, I need to return that row.

My question is: I think I need to loop all the data for that policy till I get a non-cancelled payment, please let me know how do I that.

SELECT TOP 1
    [PolicyNumber],
    [PostingDate],
    [PaymentStatus]
FROM 
    [dbo].[Bil_PaymentSearch] WITH (NOLOCK)
WHERE 
    (PolicyNumber = @PolicyNumber) AND
    (ReturnCheckreason <> 'Cancel payment') AND 
    (PaymentOrReturn <> 'Return')
ORDER BY 
    PostingDate ASC 

Advertisement

Answer

I think you just need to take NULLs into account:

SELECT TOP 1 [PolicyNumber], [PostingDate], [PaymentStatus]
FROM [dbo].[Bil_PaymentSearch]
WHERE PolicyNumber = @PolicyNumber AND
      (ReturnCheckreason <> 'Cancel payment' OR ReturnCheckreason IS NULL) AND 
      PaymentOrReturn <> 'Return'
ORDER BY PostingDate ASC 
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement