I am trying to convert my SQL query to VBA code, and after conversion, when I run my macro in excel, it is not showing up any results. I just made some basic changes to VBA code. Any one can provide me a insight. I am using SQL server. Thanks in Advance !
objMyCmd.CommandText = "SELECT c1.[RDT_FileID], C1.[Master Policy Number], c1.[Work item /Submission no#],c1.[Insured Name], c1.[Credited Office]," & _
" c1.[Credited Underwriter], c1.[Product Line], c1.[Product Line Subtype], c1.[Current Status], c1.[Effective Date], c1.[Expiry Date], c1.[Original Currency], c1.[Premium in Local Currency] " & _
" FROM Actuarial.dbo.View_Property_Rater_Of_Record a " & _
" left join " & _
"( SELECT b.[Current Status], a.* FROM" & _
"( SELECT [Master Policy Number],SUM(CAST([Premium in Local Currency] AS numeric)) AS SumPremium, MAX([Work item /Submission no#]) AS MaxSubmissionNumber" & _
" FROM IT.dbo.View_Property_Rater_Of_Record " & _
" WHERE [Master Policy Number] IS NOT NULL AND [Master Policy Number] <> ''" & _
" Group by [Master Policy Number] ) a" & _
" INNER JOIN IT.dbo.View_Property_Rater_Of_Record b on a.[MaxSubmissionNumber] = b.[Work item /Submission no#]" & _
" WHERE [Current Status] = 'Cancellation' and SumPremium = 0 " & _
" ) c2 on c1.[Master Policy Number] = c2.[Master Policy Number]" & _
" WHERE c2.[Master Policy Number] Is Null " & _
" AND c1.[RDT_FileID] is null " & _
" AND c1.[Product Line Subtype] <> '0102-Marine' " & _
" AND c1.[Master Policy Number] NOT LIKE '___PRI__________'" & _
" AND c1.[Master Policy Number] NOT LIKE '___BLA__________'" & _
" AND c1.[Effective Date] >= '2014-04-01' " & _
" AND c1.[Effective Date] >= " & PED(0) - 2 & " and c1.[Effective Date] <= " & PED(1) - 2 & " " & _
" AND c1.[Current Status] ='Bound' " & _
" ORDER BY c1.[Effective Date] ASC"
and my SQL query is as follows:-
select
c1.[RDT_FileID],
C1.[Master Policy Number],
c1.[Work item /Submission no#],
c1.[Insured Name],
c1.[Credited Office],
c1.[Product Line Subtype],
c1.[Effective Date],
c1.[Current Status],
c1.[Premium in Local Currency]
from IT.dbo.View_Property_Rater_Of_Record c1
left join
(
select
b.[Current Status],
a.*
from
(
select
[Master Policy Number],
sum(cast([Premium in Local Currency] as numeric)) as SumPremium,
max([Work item /Submission no#]) as MaxSubmissionNumber
from Actuarial.dbo.View_Property_Rater_Of_Record
where [Master Policy Number] is not null and [Master Policy Number] <> ''
group by
[Master Policy Number]
) a
inner join IT.dbo.View_Property_Rater_Of_Record b on a.[MaxSubmissionNumber] = b.[Work item /Submission no#]
where [Current Status] = 'Cancellation' and SumPremium = 0
) c2 on c1.[Master Policy Number] = c2.[Master Policy Number]
where
c1.[Effective Date] >= '2016-01-01'
and c1.[Effective Date] <= '2017-01-01'
and C1.[Current Status] = 'Bound'
and c1.[Credited Office]= '002 - New York'
and c1.[Product Line Subtype] <> '0102-Marine'
and c1.[Master Policy Number] NOT LIKE '___PRI__________'
and c1.[Master Policy Number] NOT LIKE '___BLA__________'
and c1.[RDT_FileID] is null
and c2.[Master Policy Number] is null
There are many differences and notes about your code, some are here:
I think you need to change your query string as follow:
objMyCmd.CommandText = "" & _
"SELECT" & _
" c1.[RDT_FileID]," & _
" c1.[Master Policy Number]," & _ 'Edit C1 to c1 => in newest version of SQL Server case-sensitivity is important
" c1.[Work item /Submission no#]," & _
" c1.[Insured Name]," & _
" c1.[Credited Office]," & _
" c1.[Credited Underwriter]," & _
" c1.[Product Line]," & _
" c1.[Product Line Subtype]," & _
" c1.[Current Status]," & _
" c1.[Effective Date]," & _
" c1.[Expiry Date]," & _
" c1.[Original Currency]," & _
" c1.[Premium in Local Currency] " & _
" FROM IT.dbo.View_Property_Rater_Of_Record c1 " & _ 'Edit `Actuarial.dbo.View_Property_Rater_Of_Record a` to `IT.dbo.View_Property_Rater_Of_Record c1`
" left join (" & _
" SELECT " & _
" b.[Current Status]," & _
" a.*" & _
" FROM (" & _
" SELECT " & _
" [Master Policy Number]," & _
" SUM(CAST([Premium in Local Currency] AS numeric)) AS SumPremium," & _
" MAX([Work item /Submission no#]) AS MaxSubmissionNumber" & _
" FROM Actuarial.dbo.View_Property_Rater_Of_Record " & _ 'Edit IT.dbo.View_Property_Rater_Of_Record to Actuarial.dbo.View_Property_Rater_Of_Record
" WHERE [Master Policy Number] IS NOT NULL AND [Master Policy Number] <> ''" & _
" Group by" & _
" [Master Policy Number] ) a" & _
" INNER JOIN IT.dbo.View_Property_Rater_Of_Record b on a.[MaxSubmissionNumber] = b.[Work item /Submission no#]" & _
" WHERE [Current Status] = 'Cancellation' and SumPremium = 0 " & _
" ) c2 on c1.[Master Policy Number] = c2.[Master Policy Number]" & _
" WHERE " & _
" c2.[Master Policy Number] Is Null " & _
" AND c1.[RDT_FileID] is null " & _
" AND c1.[Product Line Subtype] <> '0102-Marine' " & _
" AND c1.[Master Policy Number] NOT LIKE '___PRI__________'" & _
" AND c1.[Master Policy Number] NOT LIKE '___BLA__________'" & _
" AND c1.[Effective Date] >= '2014-04-01' " & _ 'I think you should remove this line
" AND c1.[Effective Date] >= '" & PED(0) - 2 $ "' " & _ 'Add `'` around a string input
" and c1.[Effective Date] <= '" & PED(1) - 2 & "' " & _ 'Add `'` around a string input
" AND c1.[Current Status] ='Bound' " & _
" AND c1.[Credited Office]= '002 - New York' " & _ 'Add this missing criteria
" ORDER BY c1.[Effective Date] ASC"
Note: You can use COALESCE([Master Policy Number], '') <> '' instead of [Master Policy Number] IS NOT NULL AND [Master Policy Number] <> ''.
Note: There's a very bad design in your date filtering, If you have datetime field in your database I recommend you to use CAST([Effective Date] as date) >= '20160101'.
HTH ;)
Related
I'm reasonably new to SQL and I'm trying to create a string that collects the following:
Code from [Catalogue Info] as c
Description from [Product Information] as p
Weight from p
PPB from p
CP-UK from p
CP-EU from p
1 from an external password protected database C:\mypath\db.accdb as
pl
The code below keeps giving me a Syntax error in From clause. I'm assuming this is something to do with my brackets around the INNER JOINS but I'm not sure.
This code worked perfectly fine before adding in the second INNER JOIN clause (external DB), My WHERE & ORDER BY clauses work fine.
sqlProd = "SELECT c.Code," _
& " p.Description, p.weight, p.[Pack Size], p.PPB, p.[CP-UK], p.[CP-EU]," _
& " pl.1" _
& " FROM ([Catalogue Info] c" _
& " INNER JOIN [Product Information] p" _
& " on c.code = p.code)" _
& " INNER JOIN [;database=C:\mypath\db.accdb;PWD=password123].table_name pl" _
& " on c.code = pl.code" _
& " WHERE c.Sub_Cat_1 = '" & rstSub1!Sub_Cat_1 & "'" _
& " AND c.Sub_Cat_2 = '" & rstSub2!Sub_Cat_2 & "'" _
& " ORDER BY c.Page ASC, c.Page_Position ASC;"
Any thoughts?
Access 2016, Excel 2016, Windows 10
Thanks!
Dom
I believe this should work, as I think you have unnecessary brackets around part of your FROM clause:
sqlProd = "SELECT c.Code," _
& " p.Description, p.weight, p.[Pack Size], p.PPB, p.[CP-UK], p.[CP-EU]," _
& " pl.1" _
& " FROM [Catalogue Info] c" _
& " INNER JOIN [Product Information] p" _
& " on c.code = p.code" _
& " INNER JOIN [;database=C:\mypath\db.accdb;PWD=password123].table_name pl" _
& " on c.code = pl.code" _
& " WHERE c.Sub_Cat_1 = '" & rstSub1!Sub_Cat_1 & "'" _
& " AND c.Sub_Cat_2 = '" & rstSub2!Sub_Cat_2 & "'" _
& " ORDER BY c.Page ASC, c.Page_Position ASC;"
I think I have found a solution to this - it wasn't the bracketing, it was the password I was using.
The password I was using (not in original question) used special characters (#>`{(= which seemed to be giving the syntax error. I changed the password in my Access Database to letters/numbers only and the original code works fine.
Hope this helps anyone else out. Final code:
sqlProd = "SELECT c.Code," _
& " p.Description, p.weight, p.[Pack Size], p.PPB, p.[CP-UK], p.[CP-EU]," _
& " pl.[1]" _
& " FROM [Catalogue Info] as c" _
& " INNER JOIN [Product Information] as p" _
& " on c.code = p.code" _
& " INNER JOIN [;database=C:\mypath\db.accdb;PWD=password123].table_name as pl" _
& " on c.code = pl.code" _
& " WHERE c.Sub_Cat_1 = '" & rstSub1!Sub_Cat_1 & "'" _
& " AND c.Sub_Cat_2 = '" & rstSub2!Sub_Cat_2 & "'" _
& " ORDER BY c.Page ASC, c.Page_Position ASC;"
Thanks for your feedback.
How to modify below sql query in Access VBA, where 6021, 1, and EachYear are variables.
SELECT & Edgar_Gen.[SIC Code], Edgar_Fin.EntityID, Edgar_Fin.IsANN, Edgar_Fin.[Fiscal Year],
Formula AS val
FROM Edgar_Fin INNER JOIN Edgar_Gen ON Edgar_Fin.EntityID = Edgar_Gen.EntityID
WHERE (((Edgar_Gen.[SIC Code]) = 6021) AND
((Edgar_Fin.IsANN)="1") AND ((Edgar_Fin.[Fiscal Year])="EachYear"));
It's not 100% clear what you are referring to when you're asking to "modify below sql query" for 6021 1 and EachYear, but this is the basic idea and structure of what you seem to be trying to accomplish:
Variable1 = 6021
Variable2 = 1
Variable3 = 2018
CurrentDb.Execute "SELECT Edgar_Gen.[SIC Code], " & _
"Edgar_Fin.EntityID, " & _
"Edgar_Fin.IsANN, " & _
"Edgar_Fin.[Fiscal Year], " & _
"Formula AS val " & _
"FROM Edgar_Fin " & _
"INNER JOIN Edgar_Gen ON Edgar_Fin.EntityID = Edgar_Gen.EntityID " & _
"WHERE ( " & _
"((Edgar_Gen.[SIC Code]) = " & Variable1 & ") " & _
"AND ((Edgar_Fin.IsANN) = " & Variable2 & ") " & _
"AND ((Edgar_Fin.[Fiscal Year]) = " & Variable3 & ") " & _
") "
I'm trying to run a SQL report Query and get the result to a datagrid. My query works in SSMS, but in my code I get errors complaining about a '(' and 'as' I've gone through the code but can't seem to find the error.
Here is the part with the query:
myCmd = New SqlCommand("Declare #StartDate datetime," & _
"#StopDate datetime, " & _
"#location float; " & _
"set #StartDate='" & DateF & "'" & _
"set #StopDate='" & DateT & "'" & _
"set #Location = '1'" & _
"SELECT " & _
"MAX(CASE WHEN [Purchases].[Type]=1 OR [Purchases].[Type]=2 THEN -1 ELSE CONVERT(nvarchar,[LEVEL1].[Department Number]) END) as 'Department Number', " & _
"MAX(CASE WHEN [Purchases].[Type]=1 OR [Purchases].[Type]=2 THEN 'Unallocated'ELSE ISNULL([LEVEL1].[Department Name],'Deleted') END) as 'Department Name', " & _
"SUM(isnull([View_StockMovement].[Opening],0)) as 'Opening', " & _
"SUM(isnull([View_StockMovement].[Goods Received],0)) as 'Goods Received', " & _
"SUM(isnull([View_StockMovement].[Claims],0)) as 'Claims', " & _
"SUM(isnull([View_StockMovement].[Goods Received/Claim],0)) as 'Goods Received/Claim', " & _
"SUM(isnull([View_StockMovement].[Sales],0)) as 'Sales', " & _
"SUM(isnull([View_StockMovement].[Consumed],0)) as 'Consumed', " & _
"SUM(isnull([View_StockMovement].[Produced],0)) as 'Produced', " & _
"SUM(isnull([View_StockMovement].[Produced/Consumed],0)) as 'Produced/Consumed', " & _
"SUM(isnull([View_StockMovement].[Transfered],0)) as 'Transferred', " & _
"SUM(isnull([View_StockMovement].[Adjusted],0)) as 'Adjusted', " & _
"SUM(isnull([View_StockMovement].[Accepted],0)) as 'Accepted', " & _
"SUM(isnull([View_StockMovement].[Cost Adjustment],0)) as 'Cost Adjustment', " & _
"SUM(isnull([View_StockMovement].[Closing],0)) as 'Closing', " & _
"SUM(isnull([View_Sales Journal].[Gross Sales (Excl)],0)) as 'Gross Sales (Excl)', " & _
"SUM(isnull(Purchases.[Nett Purchase Value],0)) as 'Nett Cost Adjustment (Excl)', " & _
"SUM(isnull([View_StockMovement].[Opening],0) - isnull([View_StockMovement].[Closing],0) + isnull(Purchases.[Nett Purchase Value],0)) " & _
"as 'Operating Cost', " & _
"SUM(isnull([View_Sales Journal].[Gross Sales (Excl)],0) - (isnull([View_StockMovement].[Opening],0) - isnull([View_StockMovement].[Closing],0) + isnull(Purchases.[Nett Purchase Value],0))) " & _
"as 'Gross Operating Profit', " & _
"SUM(isnull([Cost Adjustment System],0)) as [Cost Adjustment System], " & _
"SUM(isnull([Cost Adjustment User], 0)) as [Cost Adjustment User] " & _
"From [product details] " & _
"LEFT OUTER JOIN [department details] as [LEVEL5] ON [LEVEL5].[department number]=[Product Details].[Department Number] " & _
"LEFT OUTER JOIN [department details] as [LEVEL4] ON [LEVEL4].[Department Number]=[LEVEL5].[Reporting Department] " & _
"LEFT OUTER JOIN [department details] as [LEVEL3] ON [LEVEL3].[Department Number]=[LEVEL4].[Reporting Department] " & _
"LEFT OUTER JOIN [department details] as [LEVEL2] ON [LEVEL2].[Department Number]=[LEVEL3].[Reporting Department] " & _
"LEFT OUTER JOIN [department details] as [LEVEL1] ON [LEVEL1].[Department Number]=[LEVEL2].[Reporting Department] " & _
"FULL(Join) " & _
"(SELECT [Type], [Product Code], " & _
"SUM([Nett Purchase Value]) AS 'Nett Purchase Value' " & _
"FROM dbo.fn_Table_PurchaseSummary(#StartDate, #StopDate,-1,-1,-1,-1) as [Consolidated] " & _
"GROUP BY [Consolidated].[Type],[Consolidated].[Product Code]) as [Purchases] ON [Product Details].[Product Code] = [Purchases].[Product Code] AND 0 = [Purchases].[Type] " & _
"LEFT OUTER JOIN " & _
"(SELECT [Sales Journal].[Product Code], " & _
"sum([Sales Journal].[Line Total] - [Sales Journal].[Sales Tax]) as 'Gross Sales (Excl)' " & _
"From [Sales Journal] WITH (NOLOCK) " & _
"WHERE [Sales Journal].[Function Key] in (4,5,6,7,8) AND [Sales Journal].[Date & _ Time] > #StartDate AND [Sales Journal].[Date & _ Time] < #StopDate " & _
"GROUP BY [Sales Journal].[Product Code]) as 'View_Sales Journal' ON [View_Sales Journal].[Product Code]=[Product Details].[Product Code] " & _
"LEFT OUTER JOIN dbo.fn_Table_StockMovement(#StartDate, #StopDate, #Location) as 'View_StockMovement' ON [product details].[product code]=[View_StockMovement].[product code] " & _
"WHERE (isnull(convert(tinyint, [Product Details].[Deleted]), 0) <> 1 AND " & _
"((isnull([View_StockMovement].[Opening],0) <> 0 or isnull([View_StockMovement].[Goods Received],0) <> 0 or " & _
"isnull([View_StockMovement].[Claims],0) <> 0 or isnull([View_StockMovement].[Goods Received/Claim],0) <> 0 or isnull([View_StockMovement].[Sales],0) <> 0 or " & _
"isnull([View_StockMovement].[Consumed],0) <> 0 or isnull([View_StockMovement].[Produced],0) <> 0 or " & _
"isnull([View_StockMovement].[Produced/Consumed],0) <> 0 or isnull([View_StockMovement].[Transfered],0) <> 0 or " & _
"isnull([View_StockMovement].[Adjusted],0) <> 0 or isnull([View_StockMovement].[Accepted],0) <> 0 or " & _
"isnull([View_StockMovement].[Cost Adjustment],0) <> 0 or isnull([View_StockMovement].[Closing],0) <> 0))) " & _
"GROUP BY [LEVEL1].[Department Number], isnull([Purchases].[Type], 0) ORDER BY [Department Name]", myConn)
Missing a trailing space on this line? This causes the query to run into the SELECT statement
"set #Location = '1'" & _
I am trying to run this SQL statement in VBA and for some reason it says there are too few parameters and that it expected 1. I cannot figure out which line its on. Any help would be greatly appreciated.
strCount = "INSERT INTO MarketSegmentTotals([State Medicaid], [Commercial], [HIX], [MMP], [CMS Part D (CY " & intYear & ")], [CMS Part D (CY " & (intYear + 1) & ")] ) " & _
"SELECT A.cnt, B.cnt, C.cnt, D.cnt, E.cnt, F.cnt " & _
"FROM ( " & _
"SELECT COUNT([FORMULARY ID]) as cnt " & _
"FROM ImportMetricsIDs " & _
"WHERE [Market Segment]= 'State Medicaid' " & _
") AS A " & _
", ( " & _
"SELECT COUNT([FORMULARY ID]) as cnt " & _
"FROM ImportMetricsIDs " & _
"WHERE [Market Segment]= 'Commercial' " & _
") as B " & _
", ( " & _
"SELECT COUNT([FORMULARY ID]) as cnt " & _
"FROM ImportMetricsIDs " & _
"WHERE [Market Segment]= 'HIX' " & _
") AS C " & _
", ( " & _
"SELECT COUNT([FORMULARY ID]) as cnt " & _
"FROM ImportMetricsIDs " & _
"WHERE [Market Segment]= 'MMP' " & _
") AS D "
strCount2 = strCount & _
", ( " & _
"SELECT COUNT([FORMULARY ID]) as cnt " & _
"FROM ImportMetricsIDs " & _
"WHERE [Market Segment]= 'CMS Part D (CY ' & (intYear) & ')'" & _
") AS E " & _
", ( " & _
"SELECT COUNT([FORMULARY ID]) as cnt " & _
"FROM ImportMetricsIDs " & _
"WHERE [Market Segment]= 'CMS Part D (CY ' & (intYear + 1) & ')'" & _
") AS F "
I think you have a problem with quotes in your statement text. Look at this excerpt based on your code when I tested in the Immediate window:
intYear = 2015
? "WHERE [Market Segment]= 'CMS Part D (CY ' & (intYear) & ')'"
WHERE [Market Segment]= 'CMS Part D (CY ' & (intYear) & ')'
That can't be right. And when Access tries to execute the query and sees intYear, it interprets that to be a parameter because the db engine knows nothing about a VBA variable named intYear.
I think it should look like this:
? "WHERE [Market Segment]= 'CMS Part D (CY " & (intYear) & ")'"
WHERE [Market Segment]= 'CMS Part D (CY 2015)'
I encourage you to follow KevenDenen's advice to add Debug.Print strCount2 to the code after it has finished building the strCount2 string. Then you can run the code and view the text of the completed statement in the Immediate window. (You can use Ctrl+g to go to the Immediate window.) It helps tremendously to examine the actual statement your code is asking Access to execute.
I am trying to combine 3 SQL statemnets in VBA so that they show up as one record in a table. For some reason VBA throws a too few parameters error. Here is what my debug print statement outputs:
INSERT INTO Totals
([TOTAL VERIFIED FORMULARIES],[TOTAL AVAILABLE FOR IMPORT],[TOTAL SHOULD BE IMPORTED])
SELECT A.cnt,B.cnt,C.cnt
FROM (SELECT Count([FORMULARY ID]) AS cnt
FROM VerifiedFormularies) AS A,
(SELECT Count([FORMULARY ID]) AS cnt
FROM ImportMetricsIDs) AS B,
(SELECT Count([FORMULARY ID]) AS cnt
FROM ShouldImportMetricsIDsTable
WHERE [IMPORT STATUS] = 'Yes') AS C
And here is my code:
totalVerified = "INSERT INTO Totals([TOTAL VERIFIED FORMULARIES], [TOTAL AVAILABLE FOR IMPORT], [TOTAL SHOULD BE IMPORTED]) " & _
"SELECT A.cnt, B.cnt, C.cnt " & _
"FROM ( " & _
"SELECT COUNT([FORMULARY ID]) as cnt " & _
"FROM VerifiedFormularies " & _
") AS A " & _
", ( " & _
"SELECT COUNT([FORMULARY ID]) as cnt " & _
"FROM ImportMetricsIDs " & _
") as B " & _
", ( " & _
"SELECT COUNT([FORMULARY ID]) as cnt " & _
"FROM ShouldImportMetricsIDsTable " & _
"WHERE [IMPORT STATUS]= 'Yes' " & _
") AS C "
I have tried to debug it but was unsuccessful. Any help would be greatly appreciated!
I think i got it. You missed last )
totalVerified = "INSERT INTO Totals([TOTAL VERIFIED FORMULARIES], [TOTAL AVAILABLE FOR IMPORT], [TOTAL SHOULD BE IMPORTED]) " & vbcr & _
"SELECT [TOTAL VERIFIED FORMULARIES], [TOTAL AVAILABLE FOR IMPORT], [TOTAL SHOULD BE IMPORTED] " & vbcr & _
"FROM ( " & vbcr & _
"SELECT COUNT([FORMULARY ID]) as cnt " & vbcr & _
"FROM VerifiedFormularies " & vbcr & _
") AS [TOTAL VERIFIED FORMULARIES], " & vbcr & _
"( " & vbcr & _
"SELECT COUNT([FORMULARY ID]) as cnt " & vbcr & _
"FROM ImportMetricsIDs " & vbcr & _
") AS [TOTAL AVAILABLE FOR IMPORT], " & vbcr & _
"( " & vbcr & _
"SELECT COUNT([FORMULARY ID]) as cnt " & vbcr & _
"FROM ShouldImportMetricsIDsTable " & vbcr & _
"WHERE [IMPORT STATUS]= 'Yes' " & vbcr & _
") AS [TOTAL SHOULD BE IMPORTED] " & vbcr & _
")"
I'd suggest to use the same names in query. Note, that data type must be the same!