Search code examples
sql-servert-sqlselect-into

SQL query data join has null values that it ignores


I have a table in SQL Server that contains a column for a ledger code that is linked to the ledgercode table via keyfield. Currently the column displays the keyfield value instead of the code number I used this query to create a new table:

SELECT [OC_Key]
  ,[OC_PO_PO_DPNo]
  ,[OC_DateofInv]
  ,[V_VendorNo]
  ,[OC_ExpDescrip]
  ,[LedgerCode]
  ,[OC_InvoiceNo]
  ,[OC_DatePosted]
  ,[OC_TotAmount]
  ,[OC_Type]
  ,[OC_Initials]
INTO dbo.OCommittedTbl
FROM [CommittedTbl] CT, [codeLedgerTbl] LT, [VendorTbl] VT
WHERE VT.V_VenKey = CT.OC_VendorName and LT.LedgerKey = CT.OC_LedgerCode 

I problem I have is some of the rows in the table have a null value for the ledgercode column so this new table only pulls 34 of the 484 rows into the table.

How do I bypass the null values so that they will still be pulled into my table?


Solution

  • Use a LEFT JOIN instead of an (implicit) INNER JOIN.

    SELECT ...
    INTO dbo.OCommittedTbl
    FROM [CommittedTbl] CT
    LEFT JOIN [codeLedgerTbl] LT ON LT.LedgerKey = CT.OC_LedgerCode 
    LEFT JOIN [VendorTbl] VT ON VT.V_VenKey = CT.OC_VendorName