Trouble with syntax in VBA for SQL query - sql

I've got the below VBA that I am trying to use to run an SQL query (that works fine in SSMS).
I am not very good at using VBA and am having trouble getting the correct syntax for the SQL query. I'm currently stuck on incorrect syntax near '+', but once this is works, I no doubt will get the same for others!
Can anybody help with this where I am going wrong, or can anyone point me to where I can learn about the correct syntax's required in VBA for SQL?
Thanks in advance!
Set Conn = CreateObject("ADODB.Connection")
Set recset = CreateObject("ADODB.Recordset")
'set parameters
ServerSource = Sheets("Sheet1").Range("A1").Value 'choose the server the database is located
'insert server name and database name
sConnect = "Provider=SQLOLEDB.1;" & _
"Password=ExcelRep0rt;" & _
"User ID=ExcelReport;" & _
"Data Source=" & ServerSource & ";" & _
"Use Encryption for Data=False"
Conn.Open sConnect
'SQL query
SQLQry = " DECLARE #Sql NVARCHAR(MAX);" & _
" SET #Sql =" & _
" STUFF(" & _
" (SELECT" & _
" NCHAR (10) + N 'UNION ALL' + NCHAR(10) +" & _
" N 'SELECT" & _
" + QUOTENAME(d.name, '''') + N' AS dbName," & _
" c_broker COLLATE Latin1_General_CI_AS," & _
" det_costheader COLLATE Latin1_General_CI_AS," & _
" cuname COLLATE Latin1_General_CI_AS," & _
" ch_name COLLATE Latin1_General_CI_AS," & _
" CONVERT(VARCHAR(11), ch_date_req, 103) AS [Flight_Date]," & _
" IIF(OUT.outstanding > 0, ''Yes'', ''No'') AS [Anything_Outstanding?]," & _
" sum(c_grossmargin) / 2 AS [Gross_Margin]" & _
" FROM ' + QUOTENAME(d.name) + N'.dbo.AT_ACS_COMMISSIONS AS COM" & _
" Left Join ' + QUOTENAME(d.name) + N'.dbo.AT_ACS_PROJECTOUTSTANDING AS OUT" & _
" ON COM.det_costheader = OUT.project" & _
" WHERE c_broker = ''HKGCGOJT''" & _
" GROUP BY det_costheader, c_broker, cuname, ch_name, ch_date_req, outstanding'" & _
" FROM sys.databases d" & _
" where name like '%AccountsLive'" & _
" FOR XML PATH(''), TYPE)" & _
" .value('text()[1]','nvarchar(max)'), 1, 11, '');" & _
" exec( #Sql );"
'import table - choose range of where to put the table
Set recset = New ADODB.Recordset
recset.Open SQLQry, Conn
Range("B10").CopyFromRecordset recset
recset.Close
'Import Headers
'For i = 0 To recset.Fields.Count - 1
' Sheets("Sheet1").Range("B9").Offset(0, i) = recset.Fields(i).Name
'Next i
Conn.Close
Set recset = Nothing

With great direction from #Nick.McDermaid, I followed the below steps from https://www.wallstreetmojo.com/vba-debug-print/:
In VBA:
Ctrl+G - bring up the Immediate Window
Add Debug.Print SQLQry
Run the macro and copy & paste the SQL in the Immediate Window into SSMS (or whatever you're using)
Then can see where you are going wrong in your query.
Just for reference, below is the correct SQL for my particular issue.
SQLQry = " DECLARE #Sql NVARCHAR(MAX);" & _ " SET #Sql =" & _ " STUFF(" & _ " (SELECT" & _ " NCHAR (10) + N'UNION ALL' + NCHAR(10) +" & _ " N'SELECT" & _ " '+ QUOTENAME(d.name, '''') + N' AS dbName," & _ " c_broker COLLATE Latin1_General_CI_AS," & _ " det_costheader COLLATE Latin1_General_CI_AS," & _ " cuname COLLATE Latin1_General_CI_AS," & _ " ch_name COLLATE Latin1_General_CI_AS," & _ " CONVERT(VARCHAR(11), ch_date_req, 103) AS [Flight_Date]," & _ " IIF(OUT.outstanding > 0, ''Yes'', ''No'') AS [Anything_Outstanding?]," & _ " sum(c_grossmargin) / 2 AS [Gross_Margin]" & _ " FROM ' + QUOTENAME(d.name) + N'.dbo.AT_ACS_COMMISSIONS AS COM" & _ " Left Join ' + QUOTENAME(d.name) + N'.dbo.AT_ACS_PROJECTOUTSTANDING AS OUT" & _ " ON COM.det_costheader = OUT.project" & _ " WHERE c_broker = ''HKGCGOJT''" & _ " GROUP BY det_costheader, c_broker, cuname, ch_name, ch_date_req, outstanding'" & _ " FROM sys.databases d" & _ " where name like '%AccountsLive'" & _ " FOR XML PATH(''), TYPE)" & _ " .value('text()[1]','nvarchar(max)'), 1, 11, '');" & _ " exec( #Sql );"

Related

Having issues with how to use ' or " in sql statement and query using concatrelated function

I have the following code using the ConcatRelated function. the current sql works with 1 where condition but I can't figure out how to get the sql to work with 2 conditions. It works when use it in a query. I get issues and the code does not debug.
ItemsShpdInvSQL = "SELECT InvoiceAllShippedItems.ShipmentID, InvoiceAllShippedItems.ShipType, " _
& "InvoiceAllShippedItems.BillTo, InvoiceAllShippedItems.CustID AS Consignee, " _
& "InvoiceAllShippedItems.PayMethod, InvoiceAllShippedItems.PaidInFull, " _
& "First(InvoiceAllShippedItems.Units) AS Units, " _
& "'Freight Charges - Ref. WR: ' & (ConcatRelated('[WR]'," _
& "'[InvoiceAllShippedItems]','[BillTo] =' & [BillTo])) & " _
& "' - (' & Sum([Chargeable]) & ' ' & [Units] & ' " _
& ") - Number of Pieces: ' & [NoPieces] AS InvDetails, " _
& "Sum(InvoiceAllShippedItems.[# of Pieces]) AS NoPieces, " _
& "Sum(InvoiceAllShippedItems.Chargeable) AS Charge, " _
& "CustRate([custid],[ShipType]) AS CustomerRate, " _
& "IIf(([Charge])<6.1,20/[Charge],[CustomerRate]) AS RateMin " _
& "FROM InvoiceAllShippedItems " _
& "GROUP BY InvoiceAllShippedItems.ShipmentID, " _
& "InvoiceAllShippedItems.ShipType, InvoiceAllShippedItems.BillTo, " _
& "InvoiceAllShippedItems.CustID, InvoiceAllShippedItems.PayMethod, " _
& "InvoiceAllShippedItems.PaidInFull, InvoiceAllShippedItems.Units, " _
& "CustRate([custid],[ShipType]) " _
& "ORDER BY InvoiceAllShippedItems.BillTo;"
'& "CustRate([custid],[ShipType]);"
with this it works in a query but not in the code above:
'concatrelated("[WR]","InvoiceAllShippedItems","[BillTo]&[PayMethod] ='" & [BillTo] & [PayMethod] & "'")

SQL JOIN Master group to Result group

I am using Excel VBA and connecting to PGSQL using OleDB. I have 2 lines of SQL code that work fine on there own, but I now need to merge them.
The 1st query is the master group that finds the people I need for the 2nd query
Const sqlconnection = "Provider=oledb;"
Dim conn As New Connection
conn.ConnectionString = sqlconnection
conn.Open
Dim rs As Recordset
Sheets("Sheet1").Select
Range("A1").Select
Dim GRP As String
GRP = "SELECT h.master_id, p.surname, p.forename1, h.eventdate, h.code " _
& "FROM hist h INNER JOIN person p ON h.master_id=p.entity_id " _
& "AND code LIKE 'C10%' " _
& "ORDER BY h.master_id "
The 2nd query needs to show the results based on the 1st group of people it found.
Dim DATA As String
DATA = "SELECT latest.master_id, p.surname, p.forename1, " _
& "SUBSTRING(latestAP,1,10) eventdate, " _
& "SUBSTRING(latestAP,12,3) TX1, " _
& "SUBSTRING(latestAP,16,3) TX2 " _
& "FROM ( " _
& "SELECT master_id, " _
& "MAX(CAST(eventdate AS VARCHAR(10)) + '.' + RIGHT('00' + TEXT1,3)+ '.' + RIGHT('00' + TEXT2,3)) as latestAP " _
& "FROM ap " _
& "GROUP BY master_id) AS latest " _
& "LEFT JOIN person p ON latest.master_id = p.entity_id " _
& "ORDER BY master_id "
Set rs = conn.Execute(DATA)
With ActiveSheet.QueryTables.Add(Connection:=rs, Destination:=Range("A1"))
.Refresh
End With
rs.Close
Consider adding first query as an additional derived table to second query:
Dim DATA As String
DATA = "SELECT latest.master_id, p.surname, p.forename1, " _
& " SUBSTRING(latestAP,1,10) eventdate, " _
& " SUBSTRING(latestAP,12,3) TX1, " _
& " SUBSTRING(latestAP,16,3) TX2 " _
& "FROM ( " _
& " SELECT master_id, " _
& " MAX(CAST(eventdate AS VARCHAR(10)) + '.' + " _
& " RIGHT('00' + TEXT1,3) + '.' + " _
& " RIGHT('00' + TEXT2,3)) as latestAP " _
& " FROM ap " _
& " GROUP BY master_id) AS latest " _
& "INNER JOIN ( " _
& " SELECT h.master_id, p.surname, p.forename1, "_
& " h.eventdate, h.code " _
& " FROM hist h " _
& " INNER JOIN person p ON h.master_id=p.entity_id " _
& " AND code LIKE 'C10%') AS grp "
& "ON grp.master_id = latest.master_id"
& "LEFT JOIN person p ON latest.master_id = p.entity_id " _
& "ORDER BY master_id "

Trying to process SQL query within Excel VBA; incorrect syntax near 'a'

I'm a novice programmer at work and I'm struggling with a little snippet of code I need. I've read through various posts but I did not find anything that helped at last.
What I'm trying to do is to launch my SQL-Query within my vba macro but i keep getting "incorrect syntax near 'a'" error and i couldn't figure out why.
Set con = New ADODB.Connection
Set rs = CreateObject("ADODB.Recordset")
con.Open sConStr
Set rs = con.Execute("SELECT CONVERT(char(10), a.[Starttime], 104) as Date " & _
",CONVERT(char(8),a.[Starttime], 114) AS Starttime " & _
",CONVERT(char(8),a.[Endtime], 114) AS Endtime " & _
",DATEDIFF(s,a.[Starttime], a.[Endtime]) AS Duration " & _
",a.[BCMLogin] " & _
",a.[Type] " & _
",a.[PRSProfil] " & _
",b.[Location] " & _
"FROM [xxxxxxx].[dbo].[Report] AS a LEFT JOIN [xxxxxxx].[dbo].[Stammdaten] AS b on a.[Loginname] = b.[Username] " & _
"where " & _
"cast(a.[Starttime] as date) between #" & str_DFrom & "# AND #" & str_DUntil & "#" & _
"AND " & _
"a.[PRSProfil] != ''" & _
"AND " & _
"a.[Type] != 'StatusWorking'" & _
"Order BY " & _
"1,2")

Query - Error assigning value to variable in VB

I have the following code to query in VB6:
SQL = " if object_id('tempdb..#MovSeq','U') is not null drop table #MovSeq;" & _
" declare #Data_Inicio datetime, #Data_Fim datetime; set dateformat dmy; set #Data_Inicio = DataInicio; set #Data_Fim = DataFinal; set #Data_Fim = DateAdd(day, +1, #Data_Fim); " & _
" with Mov as ( SELECT EI.Cod_Empresa, EI.Cod_Estoque, EI.Cod_Produto, 'E' as Tipo_Mov, E.Dta_Entrada as Data_Mov, EI.id_Doc as NF, EI.Qtde, EI.V_Unitario, EI.V_Total " & _
" from Entrada_Itens as EI inner join Entrada as E on EI.Cod_Empresa=E.Cod_Empresa and EI.id_Doc=E.id_Doc " & _
" where E.Dta_Entrada >= #Data_Inicio and EI.Cod_Empresa='" & Sys.Empresa & "' and EI.Cod_Estoque='" & dcEstoque.BoundText & "' and EI.Cod_Produto='" & dtProdutos.BoundText & "' " & _
" Union " & _
" SELECT SI.Cod_Empresa, SI.Cod_Estoque, SI.Cod_Produto, 'S', S.Dta_Entrada , SI.id_Doc, -SI.Qtde, SI.V_Unitario, SI.V_Total " & _
" from Saida_Itens as SI inner join Saida as S on SI.Cod_Empresa=S.Cod_Empresa and SI.id_Doc=S.id_Doc " & _
" where S.Dta_Entrada >= #Data_Inicio and SI.Cod_Empresa='" & Sys.Empresa & "' and SI.Cod_Estoque='" & dcEstoque.BoundText & "' and SI.Cod_Produto='" & dtProdutos.BoundText & "' " & _
" Union " & _
" SELECT Cod_Empresa, Cod_Estoque, Cod_Produto, 'A', #Data_Inicio, null, null, null, null " & _
" From Estoque " & _
" where Cod_Empresa='" & Sys.Empresa & "' and Cod_Estoque='" & dcEstoque.BoundText & "' and Cod_Produto='" & dtProdutos.BoundText & "') " & _
" SELECT *, Seq= row_number() over (partition by Cod_Empresa, Cod_Estoque, Cod_Produto order by Data_Mov desc, Tipo_Mov desc) into #MovSeq from Mov; " & _
" create unique clustered index IndMovSeq on #MovSeq (Cod_Empresa, Cod_Estoque, Cod_Produto, Seq); " & _
" SELECT M.Cod_Empresa, M.Cod_Estoque, M.Cod_Produto, P.Descricao," & _
" Estoque= case when M.Seq=1 then E.Qtde_Estoque else (E.Qtde_Estoque - (SELECT sum(Mi.Qtde) from #MovSeq as Mi " & _
" Where Mi.Cod_Empresa = M.Cod_Empresa And Mi.Cod_Estoque = M.Cod_Estoque And Mi.Cod_Produto = M.Cod_Produto and Mi.Seq < M.Seq)) end " & _
" from #MovSeq as M inner join " & _
" Estoque as E on M.Cod_Empresa=E.Cod_Empresa and M.Cod_Estoque=E.Cod_Estoque and M.Cod_Produto=E.Cod_Produto inner join " & _
" Produtos as P on M.Cod_Empresa=P.Cod_Empresa and M.Cod_Estoque=P.Cod_Estoque and M.Cod_Produto=P.Cod_Produto " & _
" where Data_Mov < #Data_Fim " & _
" order by M.Cod_Empresa, M.Cod_Estoque, M.Cod_Produto, Seq desc; " & _
" drop table #MovSeq;"
the error appears 'invalid columm name' when run showing DataInicio as a reason
I know the error is in the assignment of the variable. but how to solve.
Thanks for the help...
Your type of code is very prone to SQL Injection attacks...
Are you escaping the variable values correctly? A simple quote (') in one of the variables can change the SQL string completely...
You should consider using parameters to pass values instead of building SQL commands using string concatenation.

The OLE DB provider "MSDASQL" for linked server "(null)" reported an error

I'm very very stuck here, help is greatly appreciated.
What am I trying to do?
There is an ASP-page (classic ASP) with a CSV upload that gives the following error:
Microsoft OLE DB Provider for SQL Server error '80040e14'
The OLE DB provider "MSDASQL" for linked server "(null)" reported an error. The provider did not give any information about the error.
/ùùù.stocklist.be/importCSVProcess.asp, line 86
I have created two linked servers:
EXEC master.dbo.sp_addlinkedserver
#server = N'txtsrv'
, #srvproduct=N'Jet 4.0'
, #provider=N'Microsoft Text Driver (*.txt; *.csv)'
, #datasrc=N'D:\WEBSITES\ùùù.stocklist.be\csv\upload'
, #provstr=N'Text'
and
EXEC sp_addlinkedserver
#server = 'Server1',
#srvproduct = '',
#provider = 'MSDASQL',
#datasrc = '
'
When I replace MSDASQL by txtsrv in the following query I get this error:
The OLE DB provider "txtsrv" has not been registered.
This is the code where the insert is done:
If upl.Form("rdbType") = "lot" Then
updFileNameSQL ="insert into cos_lot(lot_vin) " & _
"SELECT vin " & _
"FROM OPENROWSET " & _
"('MSDASQL', " & _
"'Driver={Microsoft Text Driver (*.txt; *.csv)};DBQ=" & sServerPath & ";', " & _
"'SELECT vin from " & UplFileName & "') " & _
"where not vin IS NULL AND vin collate SQL_Latin1_General_CP1_CI_AS not in (select lot_vin from cos_lot) "
Set updCmd = Server.CreateObject("ADODB.Command")
updCmd.ActiveConnection = MM_COS_STRING
updCmd.CommandText = updFileNameSQL
updCmd.Execute
ElseIf upl.Form("rdbType") = "premie" Then
updFileNameSQL ="INSERT INTO [ùùùSTOCKLIST].[dbo].[COS_ANNEX] " & _
"([annex_type] " & _
",[annex_chassisnr] " & _
",[annex_datum] " & _
",[annex_userid] " & _
",[annex_stockid] " & _
",[annex_commentNL] " & _
",[annex_commentFR] " & _
",[annex_premie] " & _
",[annex_premie_type] " & _
",[annex_consignatie] " & _
",[annex_eindeconsignatie] " & _
",[annex_online] " & _
",[annex_onlinefrom] " & _
",[annex_onlineto] " & _
",[annex_libelle]) " & _
"SELECT 2 " & _
",[VIN] " & _
",Getdate() " & _
", " & Session("user_id") & " " & _
",[STOCK] " & _
",'' " & _
",'' " & _
",Replace([PREMIE],',','.') " & _
",'E' " & _
",Null " & _
",Null " & _
",1 " & _
",cast([ONLINEFROM] as smalldatetime) " & _
",cast([ONLINETO] as smalldatetime) " & _
",[TYPE] " & _
"FROM OPENROWSET " & _
"('MSDASQL', " & _
"'Driver={Microsoft Text Driver (*.txt; *.csv)};DBQ=" & sServerPath & ";', " & _
"'SELECT vin,stock,type,premie,onlinefrom,onlineto from " & UplFileName & "') " & _
"WHERE NOT VIN IS NULL "
Set updCmd = Server.CreateObject("ADODB.Command")
updCmd.ActiveConnection = MM_COS_STRING
updCmd.CommandText = updFileNameSQL
updCmd.Execute
End If
at the end: updCmd.Execute I get the above error.
What could I be doing wrong?
Thanks in advance!
PS: server is Win2003 R2 x86
I wonder would it be worth trying a different connection string?
updFileNameSQL ="insert into cos_lot(lot_vin) " & _
"SELECT vin " & _
"FROM OPENROWSET " & _
"('Microsoft.Jet.OLEDB.4.0'," & _
"'Text;HDR=Yes;FMT=Delimited;DATABASE=" & sServerPath & ";'," & _
"'SELECT vin from [" & UplFileName & "]') " & _
"where not vin IS NULL AND vin collate SQL_Latin1_General_CP1_CI_AS " & _
"not in (select lot_vin from cos_lot) "