Question

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?

Was it helpful?

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 

OTHER TIPS

First, you need to learn the JOIN syntax. Second, the answer to your question is left outer join:

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 left outer join
     [codeLedgerTbl] LT
     on LT.LedgerKey = CT.OC_LedgerCode left outer join
     [VendorTbl] VT
      on VT.V_VenKey = CT.OC_VendorName

Third, I'm a big fan on primary keys and foreign keys having the same name. So, if you built the original table, then you might use a consistent naming convention.

The INNER JOIN excludes the null entries, try with left join

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
LEFT JOIN [codeLedgerTbl] LT ON LT.LedgerKey = CT.OC_LedgerCode 
LEFT JOIN [VendorTbl] VT ON VT.V_VenKey = CT.OC_VendorName
WHERE VT.V_VenKey = CT.OC_VendorName and LT.LedgerKey = CT.OC_LedgerCode 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top