Search code examples
sqlsql-server-2008sql-scripts

True or False Indicator when matching two tables


I need some assistance, I need to pull data from my DB, now I have a FD_Documents table and FD_Revision tables.

I need to match the GUID from both tables and also need to be a revision greater than 2, once the match has been made it must add a new column within the result, QC'ed "1" for matching criteria or a "0" for not matching criteria.

I wrote the below but it does not give me result.

select Case when EXISTS (
       SELECT FD_Documents.GUID,
      FD_Documents.FD_C231FD9A as [Store],
      FD_Documents.FD_97CDB35A as [Store 2],
      FD_Documents.FD_8B9BD5C6 as [Transaction Date],
      FD_Documents.FD_84A4EF1A as [Account Number],
      FD_Documents.FD_1A3D602F as [Name],
      FD_Documents.FD_F8EFD019 as [Date of Birth],
      FD_Documents.FD_9DAADEC8 as [Document Type],
      FD_Documents.FD_8B43AE0B as [Year],
      FD_Documents.FD_E77BE253 as [File Name]
      FROM FD_Documents, FD_Revisions
      WHERE FD_Documents.GUID = FD_Revisions.GUID
      AND FD_Documents.Deleted = '0'
      AND FD_Revisions.Revision < '3')
      THEN CAST(1 as bit)
      ELSE CAST(0 AS bit) END

Solution

  • I am assuming that FD_Documents.Deleted is an int or bit (not a string as in your post), and that Revision is an int (and should be greater than 2 as in your question description as opposed to your code),

    SELECT FD_Documents.GUID,
      FD_Documents.FD_C231FD9A as [Store],
      FD_Documents.FD_97CDB35A as [Store 2],
      FD_Documents.FD_8B9BD5C6 as [Transaction Date],
      FD_Documents.FD_84A4EF1A as [Account Number],
      FD_Documents.FD_1A3D602F as [Name],
      FD_Documents.FD_F8EFD019 as [Date of Birth],
      FD_Documents.FD_9DAADEC8 as [Document Type],
      FD_Documents.FD_8B43AE0B as [Year],
      FD_Documents.FD_E77BE253 as [File Name],
      CASE ISNULL(FD_Revisions.GUID,'') WHEN '' THEN 0 ELSE 1 END AS IsMatching
      FROM FD_Documents LEFT JOIN FD_Revisions
      ON FD_Documents.GUID = FD_Revisions.GUID
      AND FD_Documents.Deleted = 0
      AND FD_Revisions.Revision > 2