SQL concatenation inside a vbscript - sql

I have a problem with a SQL concatenation used in VB script.
I'm trying to contatenate a variable inside a SQL request but whatever the concatenation method i use, it fails !
Here is my code
dim nbr3Eu as integer = 6
dim waa2Eu as string
waa2Eu = "" _
& "SELECT riblib" _
& " ," & nbr3Eu _
& " FROM PCH" _
& " WHERE RibPaysNuf <> 'NufSocPaysMU'" _
& " AND PchID in " & XPchID _
& " GROUP BY DevCode"
I've tried it with the PLUS sign concatenation but i still have the same result
dim nbr3Eu as integer = 6
dim waa2Eu as string
waa2Eu = "" _
+ "SELECT riblib" _
+ " ," + nbr3Eu _
+ " FROM PCH" _
+ " WHERE RibPaysNuf <> 'NufSocPaysMU'" _
+ " AND PchID in " + XPchID _
+ " GROUP BY DevCode"
Need help, THANKS

You must concatenate String, try replacing & nbr3Eu by & CStr(nbr3Eu)

Related

VBA - Get all value in Array as subsequent strings

I have connected VBA & SQL Database in order to pull information.
I have written a script that returns exactly what I want but I would like to make it dynamical (Change years used etc.) and I am here running into problems.
I need to have a special line in my SQL Query which only has 1 thing that changes between the lines (Number of lines need to change and the Case when y.Date_Year = )
I get an Error message in the below code saying that there is a Type mismatch at the " & " sign right above my "period ()" array.
Sub test()
Dim SQLDB As ADODB.Connection
Dim sQuery As String
Dim info()
Dim Start_D As String
Dim End_D As String
Dim Numerator_Used As String
Dim Denominator_Used As String
Dim Number_Years As Integer
Dim period()
Numerator_Used = Range("Numerator")
Denominator_Used = Range("Denominator")
Start_D = Range("Start_Date")
End_D = Range("End_Date")
Range("A11:J100000").Cells.ClearContents
Number_Years = End_D - Start_D
ReDim period(Number_Years + 1)
For i = 0 To Number_Years
period(i + 1) = ",sum(case when y.date_year = " & Start_D + i & " then n." & Numerator_Used & " end) / sum(case when y.date_year = " & Start_D + i & " then s." & Denominator_Used & " end) as '" & Numerator_Used & "/" & Denominator_Used & " " & Start_D + i & "' & _ "
Next i
' Get Margin Expectation Changes
sQuery ="select m.date_month" & _
" m.date_month " & _
period() & _
" from " & Numerator_Used & " as n" & _
" inner join " & Denominator_Used & " as s on s.company_id = n.company_id" & _
" and s.date_month_id = n.date_month_id" & _
" and s.date_year_id = n.date_year_id" & _
" inner join date_year as y on y.date_year_id = n.date_year_id" & _
" inner join date_month as m on m.date_month_id = n.date_month_id" & _
" where y.date_year between " & Start_D & " and " & End_D & " " & _
" and n." & Numerator_Used & " <> 0" & _
" and s." & Denominator_Used & " <> 0" & _
" group by m.date_month;"
Set rs = Common.SQL_Read(SQLDB, sQuery)
ThisWorkbook.Worksheets("Sheet1").Range("A11").CopyFromRecordset rs
Set SQLDB = Common.SQL_Close(SQLDB)
End Sub
As i mentioned in the ocmment to the question, you can not explicity convert period() data into string as it is an array of variant data type (each undefined variable is treated as variant data type). You have to loop through the array data, i.e.:
For i = LBound(period()) To UBound(period())
sQuery = sQuery & period(i) & "...."
Next
'finally:
sQuery = "SELECT ... " & sQuery & " ...."
Change the code as i mentioned above and let me know if it works.

item cannot be found in the collection corresponding to the requested name or ordinal

My code gives the following error. How can I correct this?
Item cannot be found in the collection corresponding to the requested name or ordinal
ElseIf Me.chkItem.Checked = True Then
Dim CheckNumber As String = ""
Dim CheckRef As String = ""
dsvoucheritem.Clear()
DSVoucher_Expense.Clear()
DSVoucher_Check.Clear()
Try
Me.lstCV.Items.Clear()
strDiscount = Nothing
rec.Open("select billpaymentcheckline.txnnumber, billpaymentcheckline.txndate" _
& ", billpaymentcheckline.payeeentityreffullname" _
& ", billpaymentcheckline.amount, billitemline.itemlineitemreffullname" _
& ", billitemline.memo" _
& ", billpaymentcheckline.appliedtotxndiscountamount" _
& ", billpaymentcheckline.appliedtotxnrefnumber, billpaymentcheckline.bankaccountreffullname" _
& ", billpaymentcheckline.appliedtotxndiscountaccountreffullname" _
& ", billpaymentcheckline.appliedtotxntxndate, billpaymentcheckline.appliedtotxnamount" _
& ", billpaymentcheckline.refnumber, account.AccountNumber from (billitemline inner join" _
& " billpaymentcheckline on billitemline.refnumber=billpaymentcheckline.appliedtotxnrefnumber) left outer join" _
& " account on billitemline.APAccountreflistid=account.listid where" _
& " billpaymentcheckline.bankaccountreflistid='" &Me.lblBankID.Text & "' and" _
& " billpaymentcheckline.refnumber between '" & CInt(Me.txtRefFR.Text)
& "' and '" & CInt(Me.txtRefTO.Text) & "'", con, ADODB.CursorTypeEnum.adOpenForwardOnly, ADODB.LockTypeEnum.adLockReadOnly)
It's saying it doesn't recognize one of your column names. Double check all of them. You can also try removing fields until you find the culprit.
memo is a reserved word in Access SQL.
Try billitemline.[memo]

Requery using a variable within string

I am having trouble to requery my subform using a SQL string, here is my code:
Dim Day As Integer
Day = txt_Days.Value
SQL = "SELECT [qry_Records].[Tool_ID], [qry_Records].[Cal_Date]," _
& "[qry_Records].[Cal_By], [qry_Records].[As_Received], " _
& "[qry_Records].[Result], [qry_Records].[Next_Due], " _
& "[qry_Records].[Due] FROM [qry_Records]" _
& " WHERE [qry_Records].[Due] < Day;"
subform_View_Search_Records.Form.RecordSource = SQL
I tried to use different variations to quote the Day variable at the end of the SQL String such as below but nothing works:
& " WHERE [qry_Records].[Due] < ""Day"";"
& " WHERE [qry_Records].[Due] < '"Day"';"
Your help is much appreciated!
You just need to add a couple of ampersands
& " WHERE [qry_Records].[Due] < " & Day & ";"
I would try this:
SQL = "SELECT [Tool_ID], [Cal_Date]," _
& "[Cal_By], [As_Received], " _
& "[Result], [Next_Due], " _
& "[Due] FROM [qry_Records]" _
& " WHERE [Due] < " & format$(txtDays, "\#dd\/mm\/yyyy\#")
subform_View_Search_Records.Form.RecordSource = SQL
The final ";" is useless.

access 2013 increasing quantity in a table field

Good day. I'm a little stumped about what is happening in my code. I have a userform which collects txtQntyRecd and cboSupplySource. I calculate the lookupValue. And it works just fine. It successfully places the txtQntyRecd in the correct tblWarehouseLocations.WQuantity location. The code is:
updateQnty = "UPDATE tblSupplySources INNER JOIN ((tblWarehouseLocations " & _
"INNER JOIN tblSupplySource_WarehouseLocation ON tblWarehouseLocations.WLocation_ID = tblSupplySource_WarehouseLocation.SWLocation_ID)) " & _
"ON tblSupplySources.SupplySourceID = tblSupplySource_WarehouseLocation.Supply_Source_ID " & _
"SET tblWarehouseLocations.WQuantity = '" & Me.txtQntyRecd & "'" & _
"WHERE (((tblSupplySource_WarehouseLocation.Supply_Source_ID)= " & Me.cboSupplySource & ") " & _
" AND ((tblWarehouseLocations.WLocation_ID)=" & lookupValue & "))"
CurrentDb.Execute updateQnty, dbFailOnError
What I want to do is add the next quantity to the same location. I get weird results if I change the SET statement to the following:
SET tblWarehouseLocations.WQuantity = tblWarehouseLocations.WQuantity + '" & Me.txtQntyRecd & "'"
If I put 200 in the first statement, I get 200 in my WQuantity field. When I change to the second statement and I try to add 1 to the 200 I get a result of 211. If I add 1 again, the result is 223. Add 1 again, the result is 236.
Could someone explain what is happening and why the results aren't 201, 202 and 203? In the future I will need to subtract quantities from WQuantity as well.
Thanks
You're adding quotes around an integer and appending it as a string. Change it to:
".....
SET tblWarehouseLocations.WQuantity = tblWarehouseLocations.WQuantity + " & val(Me!txtQntyRecd) & "....
...."
I've changed the . to a ! as I think it's still a nice distinction between objects properties and controls, and used the val function as it converts the string number value to the integer value.
This is your query in full:
' When I use values from controls, I like to store them in vars
Dim quantityReceived As integer
quantityReceived = val(Me!txtQntyRecd)
updateQnty = "UPDATE tblSupplySources INNER JOIN ((tblWarehouseLocations " & _
"INNER JOIN tblSupplySource_WarehouseLocation ON tblWarehouseLocations.WLocation_ID = tblSupplySource_WarehouseLocation.SWLocation_ID)) " & _
"ON tblSupplySources.SupplySourceID = tblSupplySource_WarehouseLocation.Supply_Source_ID " & _
"SET tblWarehouseLocations.WQuantity = tblWarehouseLocations.WQuantity + " & quantityReceived & _
" WHERE (((tblSupplySource_WarehouseLocation.Supply_Source_ID)= " & Me.cboSupplySource & ") " & _
" AND ((tblWarehouseLocations.WLocation_ID)=" & lookupValue & "))"
I solved the problem. I created a SELECT query to get the present amount in WQuantity. Now quantityReceived = Me!txtQntyRecd + the present amount. With SET tblWarehouseLocations.WQuantity = " & quantityReceived it works fine. However, if just seems so cumbersome.
' lookupValue gives the index into the tblWarehouseLocations where WQuantity resides
Dim lookupValue As Integer
lookupValue = DLookup("[WLocation_ID]", "[tblWarehouseLocations]", "[Location_Name] = '" & Me.cboWLocation & "'")
'Define SQL Query
strSQL = "select tblWarehouseLocations.WQuantity FROM tblWarehouseLocations WHERE (((tblWarehouseLocations.WLocation_ID)= " & lookupValue & "))"
Set rs = db.OpenRecordset(strSQL)
If IsNull(rs!WQuantity) Then
dbvalue = 0
Else
dbvalue = rs!WQuantity
End If
Dim quantityReceived As Integer
quantityReceived = Val(Me!txtQntyRecd) + dbvalue
updateQnty = "UPDATE tblSupplySources INNER JOIN ((tblWarehouseLocations " & _
"INNER JOIN tblSupplySource_WarehouseLocation ON tblWarehouseLocations.WLocation_ID = tblSupplySource_WarehouseLocation.SWLocation_ID)) " & _
"ON tblSupplySources.SupplySourceID = tblSupplySource_WarehouseLocation.Supply_Source_ID " & _
"SET tblWarehouseLocations.WQuantity = " & quantityReceived & _
" WHERE (((tblSupplySource_WarehouseLocation.Supply_Source_ID)= " & Me.cboSupplySource & ") " & _
" AND ((tblWarehouseLocations.WLocation_ID)=" & lookupValue & "))"
CurrentDb.Execute updateQnty, dbFailOnError

ERROR [22P02] ERROR: invalid input syntax for integer: "";

Never seen such error:
ERROR [22P02] ERROR: invalid input syntax for integer: ""; Error while executing the query
Creating table:
Public Function PrimkCreate(ByVal myPrimkTable As String, ByVal nCon As OdbcConnection) As Integer
Dim ans As Integer
Dim cCommand As OdbcCommand = New OdbcCommand("CREATE TABLE IF NOT EXISTS " + myPrimkTable + "(" & _
"prm_id int NOT NULL, " & _
"pkni text, " & _
"pdatum text, " & _
"pdatumnaplate text, " & _
"pdanaodgode int, " & _
"puldok text, " & _
"puldokbroj text, " & _
"pdatumk text, " & _
"pvrijemek text, " & _
"pdobid int, " & _
"pdoboib text, " & _
"pnabc double precision, " & _
"purab double precision, " & _
"ppdv double precision, " & _
"ppnak double precision, " & _
"pprodc double precision, " & _
"pvrstaprimke int, " & _
"pzapisniktekst text, " & _
"prez text, " & _
"CONSTRAINT " & myPrimkTable & "_pkey PRIMARY KEY(prm_id))", nCon)
ans = cCommand.ExecuteNonQuery()
cCommand.Dispose()
Return ans
End Function
Update code:
Public Function update_LPrimk(ByRef primk As Integer, ByVal mCon As OdbcConnection) As Integer
Dim retval As Integer
Dim uCmd As OdbcCommand = New OdbcCommand("UPDATE " & myPrimkTable & " SET " & _
"prm_id=" & primk & ", " & _
"pkni='" & prm.pKni & "', " & _
"pdatum='" & prm.pDatum & "', " & _
"pdatumnaplate='" & prm.pDatumNaplate & "', " & _
"pdanaodgode=" & prm.pDanaodgode & ", " & _
"puldok='" & prm.pUlDok & "', " & _
"puldokbroj='" & prm.pUlDokBroj & "', " & _
"pdatumk='" & prm.pDatumk & "', " & _
"pvrijemek='" & prm.pVrijemek & "', " & _
"pdobid='" & prm.pDobID & "', " & _
"pdoboib='" & prm.pDobOib & "', " & _
"pnabc='" & Replace(prm.pNabc.ToString, ",", ".") & "', " & _
"purab='" & Replace(prm.pURab.ToString, ",", ".") & "', " & _
"ppdv='" & Replace(prm.pPdv.ToString, ",", ".") & "', " & _
"ppnak='" & Replace(prm.pPnak.ToString, ",", ".") & "', " & _
"pprodc='" & Replace(prm.pProdc.ToString, ",", ".") & "', " & _
"pvrstaprimke=" & prm.pVrstaPrimke & ", " & _
"pzapisniktekst='" & prm.pZapisnikTekst & "', " & _
"prez='" & prm.pRez & "' " & _
"WHERE prm_id=" + primk.ToString, mCon)
retval = uCmd.ExecuteNonQuery()
uCmd.Dispose()
Return retval
End Function
Query looks exactly like this:
UPDATE primke SET prm_id=1, pkni='U', pdatum='07.01.2013', pdatumnaplate='10.01.2013',
pdanaodgode=3, puldok='ghkzug gugug', puldokbroj='jkhk', pdatumk='', pvrijemek='',
pdobid='', pdoboib='', pnabc='0', purab='0', ppdv='0', ppnak='0', pprodc='0',
pvrstaprimke=0, pzapisniktekst='', prez='' WHERE prm_id=1
I have many tables where I run similar commands but have never seen such an error.
What might be the problem?
I would advice to read the chapter Constants in the manual. It's a brief and informative read.
The cause for the error message is that '' is an empty string that has no representation in a numeric type like integer.
#a_horse_with_no_name: To be precise, '0' is a string constant to PostgreSQL that can be cast to integer just as well as it can be cast to text, only text is the default for string constants. Consider this demo:
CREATE TEMP TABLE t (i int);
INSERT INTO t VALUES (1);
INSERT INTO t VALUES ('2'); -- single row inserts to make sure ..
INSERT INTO t VALUES ('3'::int); -- .. type is not coerced to type
INSERT INTO t VALUES (4::bigint); -- .. of first row by VALUES expression.
INSERT INTO t VALUES (5::numeric);
INSERT INTO t VALUES (6);
UPDATE t SET i = '0' WHERE i = '6';
SELECT * FROM t;
SQL Fiddle.