sqlsql-serverjoincasepatindex

Find matching values between two tables when using cross apply in SQL


I am trying to extract 5 or more consecutive numbers from from Table A Column x and match the extracted numbers to Table B column z. If the value exists, that is fine but if the value does not exist it needs to be inserted into Table B. I have managed to extract the numbers from Table A but I am stuck when trying to JOIN because I am using CROSS APPLY and CASE. Perhaps I am just not understanding how to do this.

Code I am using to extract the numbers:

SELECT nvt.AdditionalInformation,
       CASE
           WHEN M.FirstMatch > 0
           THEN SUBSTRING(AdditionalInformation, M.FirstMatch-1, N.SecondMatch-1)
          
           --check IF TPNumber EXISTS in ChangeRequests table then add ChangeRequest Id to ReportVersionChangeRequests table
           ELSE NULL
       END
FROM
(
    SELECT ':'+nvt.AdditionalInformation+':' AdditionalInformation
    FROM dbo.NSReportVtest nvt
) nvt

CROSS APPLY(VALUES(PATINDEX('%[0-9][0-9][0-9][0-9][0-9]%', ':'+nvt.AdditionalInformation+':'))) M(FirstMatch)
CROSS APPLY(VALUES(PATINDEX('%[^0-9]%', SUBSTRING(AdditionalInformation, M.FirstMatch-1, LEN(AdditionalInformation))))) N(SecondMatch)

At the moment this is the result of the code:

Table A:

AdditionalInformation (No Column name)
:Test Results: NULL
:Test Results: 256985
:Test Results: NULL
:Test Results: NULL
:Test Results: NULL
:Test Results: 85965

Expected Results:

Table A:

AdditionalInformation (No Column name)
:Test Results: NULL
:Test Results: 256985
:Test Results: NULL
:Test Results: NULL
:Test Results: NULL
:Test Results: 85965

Table B:

Id Number
1 61758
2 85965
3 56456
4 78945

Expected Output after Join

Table C:

Id Number
1 61758
2 85965
6 56456
8 78945
9 256985 (Added entry)

Solution

  • I found a solution that works. I INSERT INTO a #temp table which then I can select specific columns and join that to a second table which makes it easier to manage data.

    SELECT nv.AdditionalInformation, 
           nv.Id,
           CASE
               WHEN M.FirstMatch > 0
               THEN SUBSTRING(AdditionalInformation, M.FirstMatch-1, N.SecondMatch-1)
               ELSE NULL
           END AS ExtractedTP
    INTO #temp
    FROM
    (
        SELECT ':'+nv.AdditionalInformation+':' AdditionalInformation, 
               nv.Id
        FROM dbo.NSReportVtest nv
    ) nv
    CROSS APPLY(VALUES(PATINDEX('%[0-9][0-9][0-9][0-9][0-9]%', ':'+nv.AdditionalInformation+':'))) M(FirstMatch)
    CROSS APPLY(VALUES(PATINDEX('%[^0-9]%', SUBSTRING(AdditionalInformation, M.FirstMatch-1, LEN(AdditionalInformation))))) N(SecondMatch);
    
    --select and join temp table to ChangeRequests table to see which TP Numbers exist
    
    SELECT t.Id, 
           t.ExtractedTP, 
           nrt.TPNumber, 
           nrt.Id
    FROM #temp t
         LEFT JOIN dbo.NSChangeRequestsTest nrt ON t.ExtractedTP = nrt.TPNumber
    ORDER BY t.ExtractedTP DESC;