I have the following query that i need help with converting it to syntax that MS SQL 2005 would understand since FORMAT among other things in it are not supported by that old version.
"SELECT " & _
"TMP.*," & _
"COUNT(*) OVER () AS rCount " & _
"FROM (" & _
"SELECT venueID, " & _
"venueName AS venueName, " & _
"venueAddress + ', ' + venueCity + ', ' + venueState + ' ' + venueZip AS venueAddress, " & _
"venueLatLong AS coordinates, " & _
"FORMAT(venueEventDate, 'MM/dd/yyyy', 'en-US') + ' # ' + CONVERT(VARCHAR,venueTime) AS dateAndTime, " & _
"SUBSTRING(venueLatLong, 1, CHARINDEX(',', venueLatLong)-1) AS Lat, " & _
"SUBSTRING(venueLatLong, CHARINDEX(',', venueLatLong) + 1, 1000) AS Lng, " & _
"(round(" & _
"3959 * acos " & _
"(" & _
"cos(radians('" & center_lat & "')) " & _
"* cos(radians(SUBSTRING(venueLatLong, 1, CHARINDEX(',', venueLatLong)-1))) " & _
"* cos(radians(SUBSTRING(venueLatLong, CHARINDEX(',', venueLatLong) + 1, 1000)) " & _
"- radians('" & center_lng & "')) " & _
"+ sin(radians('" & center_lat & "')) " & _
"* sin(radians(SUBSTRING(venueLatLong, 1, CHARINDEX(',', venueLatLong)-1)))" & _
")" & _
", 1, 1)) AS distance " & _
"FROM meetUpMarkers) " & _
"TMP " & _
"WHERE distance < " & radius & " " & _
"ORDER BY venueName,distance DESC;"
I tried to replace FORMAT with CONVERT but it still seems to be incorrect.
When i change FORMAT to CONVERT i get the error:
Type venueEventDate is not a defined system type.
UPDATE
Uggg... now when I run it local i get this:
Now even when i run it local i get this error???!??! and its 2012:
Msg 8114, Level 16, State 5, Line 2
Error converting data type varchar to float.
Does this mean line 2, word 5 has the error?
Would appreciate the help.
Arguments for FORMAT() and CONVERT() are in a different order. The error message indicates you put the field name into the data type argument position. It's:
FORMAT ( value, format [, culture ] )
vs
CONVERT ( data_type [ ( length ) ] , expression [ , style ] )
Try replacing FORMAT(venueEventDate, 'MM/dd/yyyy', 'en-US') with this:
CONVERT(VARCHAR, venueEventDate, 101)`
Related
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] & "'")
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 );"
I've got this:
sql = "SELECT " & _
"proces_id, " & _
"proces_naam, " & _
"voorraad, " & _
"voorraad_te_laat, " & _
"voorraad_verificatie, " & _
"voorraad_verificatie_te_laat, " & _
"teamplanning, " & _
"teamplanning_verificatie, " & _
"Iif(IsNull(teamplanning_totaal), 0, teamplanning_totaal) + Iif(IsNull(teamplanning), 0, teamplanning) AS totaal_teamplanning, " & _
"Iif(IsNull(teamplanning_totaal_verificatie), 0, teamplanning_totaal_verificatie) + Iif(IsNull(teamplanning), 0, teamplanning_verificatie) AS totaal_teamplanning_verificatie, " & _
"Round(Iif(IsNull(teamplanning), 0, (teamplanning * proces_normtijd * Iif(IsNull(productiviteit_factor), 1, productiviteit_factor)) / 60), 2) AS teamplanning_uren, " & _
"Round(Iif(IsNull(teamplanning_verificatie), 0, (teamplanning_verificatie * proces_normtijd_verificatie * Iif(IsNull(productiviteit_factor), 1, productiviteit_factor)) / 60), 2) AS teamplanning_uren_verificatie, "
If IsNull(Datum) Then
sql = sql & "null AS verschil, " & _
"null AS verschil_verificatie, "
Else
sql = sql & "Iif(IsNull(voorraad), 0, voorraad) - Iif(IsNull(teamplanning), 0, teamplanning) - Iif(IsNull(teamplanning_totaal), 0, teamplanning_totaal) AS verschil, " & _
"Iif(IsNull(voorraad_verificatie), 0, voorraad_verificatie) - Iif(IsNull(teamplanning_verificatie), 0, teamplanning_verificatie) - Iif(IsNull(teamplanning_totaal_verificatie), 0, teamplanning_totaal_verificatie) AS verschil_verificatie, "
End If
sql = sql & "proces_normtijd, " & _
"proces_normtijd_verificatie, " & _
"Iif(IsNull(realisatie_cases), 0, realisatie_cases) AS realisatie_cases_aantal, " & _
"Iif(IsNull(realisatie_cases_verificatie), 0, realisatie_cases_verificatie) AS realisatie_cases_aantal_verificatie, " & _
"Iif(IsNull(ingeplande_cases), 0, ingeplande_cases) AS ingeplande_cases_aantal, " & _
"Iif(IsNull(ingeplande_cases_verificatie), 0, ingeplande_cases_verificatie) AS ingeplande_cases_aantal_verificatie, " & _
"volgorde, "
sql = sql & "Iif(IsNull(voorraad_gisteren), 0, voorraad_gisteren) AS instroom, " & _
"Iif(IsNull(voorraad_verificatie_gisteren), 0, voorraad_verificatie_gisteren) AS instroom_verificatie "
sql = sql & "FROM tmp_planning_proces " & _
"WHERE userid = '" & EscapeString(LCase(mod_global.RealUser)) & "' " & _
"AND team_id = " & TeamID & " " & _
IIf(IsNull(MedewerkerGroepID), "AND medewerker_groep_id is null ", "AND medewerker_groep_id = " & MedewerkerGroepID & " ") & _
IIf(IsNull(Datum), "AND week = " & week & " AND jaar = " & jaar & " ", "AND datum = #" & Format(Datum, "yyyy-mm-dd") & "# ") & _
"ORDER BY volgorde ASC "
What I need to change is:
"Iif(IsNull(voorraad_gisteren), 0, voorraad_gisteren) AS instroom".
It needs to be:
"Iif(IsNull(aantal_instroom), 0, aantal_instroom) AS instroom".
The problem is that it comes from another table called instroom. The query I didn't make myself and I have limited query skills so I tried this:
"Iif(IsNull(Select aantal_instroom From instroom), 0, aantal_instroom) AS instroom"
but that doesn't work, suddenly no data appears anymore.
Does anybody know how to do this?
First of all there is a much better way to do:
IIf(IsNull(voorraad_gisteren), 0, voorraad_gisteren)
It is:
Nz(voorraad_gisteren, 0)
Now to your question. First you have to make sure the table instroom is part of your FROM section of the SQL statement. Example:
FROM tmp_planning_proces INNER JOIN instroom ON ... [whatever fields link the two tables together]
Then you can refer to any field on the table like this:
instroom.aantal_instroom
IIf(IsNull(instroom.aantal_instroom), 0, instroom.aantal_instroom) AS instroom
or even better:
Nz(instroom.aantal_instroom,0) AS instroom
I also agree with the comment that using the same field alias as the table name is probably a bad idea and bound to cause confusion in the future.
The following Code prompts out with, according to google, a kind of random/default error that doenst really lead to the problem. (Query input must contain at least one table or query)
Private Sub ButtonInsertUntergruppe_Click()
Dim sql As String
sql = "INSERT INTO tblArbeitsschritte (Auftrag_FK, Prozesspunkt_FK, Prozesspunkt) " & _
"VALUES (" & _
Forms!frm_GUI!ID_Auftraege & _
", " & _
"(SELECT ID_Prozesspunkt " & _
"FROM tblProzesspunkt " & _
"WHERE Untergruppe_FK = " & _
Me.cbUntergruppe.Column(0) & _
") , " & _
"(SELECT Prozesspunkt " & _
"FROM tblProzesspunkt " & _
"WHERE Untergruppe_FK = " & _
Me.cbUntergruppe.Column(0) & _
"));"
Debug.Print sql
CurrentDb.Execute sql, dbFailOnError
End Sub
This is what the debugger gives me:
INSERT INTO tblArbeitsschritt
(
Auftrag_FK, Prozesspunkt_FK, Prozesspunkt
)
VALUES
(
1,
(SELECT ID_Prozesspunkt
FROM tblProzesspunkt
WHERE Untergruppe_FK = 1)
,
(SELECT Prozesspunkt
FROM tblProzesspunkt
WHERE Untergruppe_FK = 1)
);
Not sure if that syntax is supported. Personally I would do:
INSERT INTO tblArbeitsschritt
(
Auftrag_FK, Prozesspunkt_FK, Prozesspunkt
)
SELECT 1, ID_Prozesspunkt, Prozesspunkt
FROM tblProzesspunkt
WHERE Untergruppe_FK = 1
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.