developthestars
developthestars

Reputation: 185

SQL Query not working

I have these four tables:

SELECT [B_Key]
  ,[B_FiscalYear]
  ,[B_OrgCode]
  ,[B_SubObject]
  ,[B_Explanation]
  ,[B_CIPrefNo]
  ,[B_OrgBudgetAmt]
  ,[B_BudgetAmt]
  ,[B_Initials]
FROM [NAOLI].[dbo].[BudgetTbl]

SELECT [F_Fykey]
  ,[F_FiscalYear]
  ,[F_Year]
FROM [NAOLI].[dbo].[codeFiscalYearTbl]

SELECT [O_OrgKey]
  ,[O_OrgCode]
  ,[O_OrgDesc]
  ,[O_Divisions]
FROM [NAOLI].[dbo].[codeOrgCodeTbl]

SELECT [S_SubKey]
  ,[S_SubObject]
  ,[S_SubDescrip]
FROM [NAOLI].[dbo].[codeSubObjectTbl]

I need to combine different pieces of the information in these tables in order to make the table of information below:

   [B_FiscalYear]
  ,[O_OrgCode]
  ,[O_OrgDesc]
  ,[S_SubObject]
  ,[S_SubDescrip]
  ,[B_BudgetAmt]
  ,[B_Initials]
  ,[B_CIPrefNo]
  ,[B_OrgBudgetAmt]

I tried the below query but it returns 0 of the 20750 records.. How do I accomplish this? thanks

SELECT [B_FiscalYear]
  ,[B_OrgCode]
  ,[O_OrgDesc]
  ,[B_SubObject]
  ,[S_SubDescrip]
  ,[B_BudgetAmt]
  ,[B_Initials]
  ,[B_CIPrefNo]
  ,[B_OrgBudgetAmt]

INTO dbo.BudgetsTbl
  FROM [BudgetTbl] BT, [codeFiscalYearTbl] FY, [codeOrgCodeTbl] OC, [codeSubObjectTbl] SO
WHERE BT.B_FiscalYear = FY.F_Year and BT.B_OrgCode = OC.O_OrgCode and BT.B_SubObject = SO.S_SubObject

Upvotes: 0

Views: 68

Answers (2)

arpad
arpad

Reputation: 539

The join should be like this:

SELECT [B_FiscalYear]
  ,[B_OrgCode]
  ,[O_OrgDesc]
  ,[B_SubObject]
  ,[S_SubDescrip]
  ,[B_BudgetAmt]
  ,[B_Initials]
  ,[B_CIPrefNo]
  ,[B_OrgBudgetAmt]
FROM BudgetTbl BT
JOIN codeFiscalYearTbl FY ON BT.B_FiscalYear = FY.F_Year
JOIN codeOrgCodeTbl OC ON BT.B_OrgCode = OC.O_OrgCode
JOIN codeSubObjectTbl SO ON BT.B_SubObject = SO.S_SubObject

You can look at http://sqlfiddle.com/#!3/8ff6b/7 for more info. Also you can add left joins if needed.

Upvotes: 1

Gordon Linoff
Gordon Linoff

Reputation: 1271051

The proper join syntax is:

SELECT [B_FiscalYear], [B_OrgCode], [O_OrgDesc], [B_SubObject], [S_SubDescrip],
       [B_BudgetAmt], [B_Initials], [B_CIPrefNo], [B_OrgBudgetAmt]
INTO dbo.BudgetsTbl
FROM BudgetTbl BT join
     codeFiscalYearTbl FY
     on BT.B_FiscalYear = FY.F_Year  join
     codeOrgCodeTbl OC
     on BT.B_OrgCode = OC.O_OrgCode join
     codeSubObjectTbl SO
     on BT.B_SubObject = SO.S_SubObject

Presumably, one or more of your lookup tables are empty. If you want all rows, replace the "join" with "left outer join" in the above query.

Upvotes: 0

Related Questions