How to use a table field as a parameter of a function? - vba

I'm trying to do something like this in an Access module:
sql = "UPDATE Carrera "
sql = sql & "SET Carrera.[carnombre]= '" & strFunction(Carrera.[CarreraNombre]) & "' "
sql = sql & "WHERE Carrera.[CarreraNombre]='ANIMACION';"
MsgBox (sql)
Application.CurrentDb.Execute (sql)
but I get the error "has not defined the variable" and has highlighted Carrera in strFunction(Carrera.[CarreraNombre]). If I use any other string the update works. How to use the field Carrera.[CarreraNombre] as a parameter for strFunction() that returns a string?

Carrera.[CarreraNombre] only has a value when the SQL query is being executed. You are asking VBA to call strFunction() while you are building the string, and VBA has no idea what Carrera.[CarreraNombre] means. I believe you want to do this:
sql = sql & "SET Carrera.[carnombre] = strFunction(Carrera.[CarreraNombre]) "

Related

using what I think is a variable in a SQL statement

I am very new to SQL and think I have a simple problem but was unable to figure it out from other posts. I have the following code:
INSERT INTO tblShortScores ( TradeNum, FilterNum, Rank, ScoreNum )
SELECT [Forms]![frmOpenTrades]![TradeNum] AS TradeNum, tblFilters.FilterNum, tblFilters.SBBExh AS Rank, tblFilters.SBBExh AS Score
FROM tblFilters
WHERE (((tblFilters.SBBExh) Is Not Null));
but instead of using the literal "SBBExh" in tblFilters.SBBExh, I want to do something like
tblFilters.("S" & [Forms]![frmOpenTrades]![Strategy])
where something like
[Forms]![frmOpenTrades]![Strategy] contains the value "BBExh".
It's in MS Access and I seem unable to find a syntax that works
any help is appreciated
Can't dynamically build field name in query object. Use VBA to construct and execute action SQL, like:
strField = "S" & Me.Strategy
CurrentDb.Execute "INSERT INTO tblShortScores (TradeNum, FilterNum, ScoreNum) " & _
"SELECT " & Me.TradeNum & " AS TradeNum, FilterNum, " & strField & " " & _
"FROM tblFilters WHERE " & strField & " Is Not Null;"
Assumes TradeNum is number type - if it is text, use apostrophe delimiters:
SELECT '" & Me.TradeNum & "' AS .
If SQL injection is a concern review, How do I use parameters in VBA in the different contexts in Microsoft Access?

Retrieve Data from SQL with input from table

I have a table in excel, with range : Sheets("Sheet1").Range("d4:d215"). These data are similar to PS.WELL in the server.
From that table, I want to retrieve data using this code (other SQL requisite has been loaded, this is the main code only):
strquery = "SELECT PS.WELL, PS.TYPE, PS.TOPSND " & _
"FROM ISYS.PS PS " & _
"WHERE PS.WELL = '" & Sheets("Sheet1").Range("D4:D215") "' AND (PS.TYPE = 'O' OR PS.TYPE = 'O_' OR PS.TYPE = 'GOW') " & _
"ORDER BY PS.WELL"
Unfortunately it didn't work. Can anyone help me how to write the code especially in the 'where' section?
You have to iterate through each item in the range and concatenate the results to a string variable so the contents look like this
'val1','val2','val3'
Then you have to adjust your query code to use the IN operator instead of equals operator. Let's say the string is concatenated to a variable called myrange.
"WHERE PS.WELL IN (" & myrange & ") AND ...
I have solved the problem. The key is to make 2 function of SQL:
to read and write each input
to count number of output per input (an input can have 0, 1, or more output).
then, just call using procedure

Syntax error in SQL update

I am new to both MS Access and SQL. Now I am trying to create an inventory database for our company in Ms Access. I try to extract data from the reception form to update the inventory balance. But I met a syntax error message when I executed a SQL update statement. This is weird for me because I used the same statements that successfully running in other tables. The only difference is my former successful update working by direct text replacement and my error occurring update is working in a numeric object.
Please help me to check where I am wrong.
This is my code:
Private Sub Command96_Click()
CurrentDb.Execute "UPDATE tbl_Current_Stock" & _
"SET Stock_Level= Stock_Level + " & Me!txtOrderQty & "" & _
"Where tbl_Current_Stock.Raw_Material= " & Me!cboPurchase.Column(1) & ""
End Sub
Thanks!
You need to add spaces before SET and Where. Otherwise, your command will look something like UPDATE tbl_Current_stockSET Stock_Level= Stock_Level + 3Where.....
Private Sub Command96_Click()
CurrentDb.Execute "UPDATE tbl_Current_Stock" & " " & _
"SET Stock_Level= Stock_Level + " & Me!txtOrderQty & " " & _
"Where tbl_Current_Stock.Raw_Material= " & Me!cboPurchase.Column(1) & ""
End Sub
You might also need to wrap the Raw_Material column in quotes if it is not numeric.
check your sentence correctly. there is no technical error. there are some space missing in you query.
just add white space before "SET" and "where" words.
CurrentDb.Execute "UPDATE tbl_Current_Stock" & _
" SET Stock_Level= Stock_Level + " & Me!txtOrderQty & "" & _
" Where tbl_Current_Stock.Raw_Material= " & Me!cboPurchase.Column(1) & ""
Friend, follow some tips to generate your updade correctly:
Check the spaces after concatenating your query
Be careful not to generate queries with keywords stuck together
UPDATE tableTestSET nome = 'My Name' WHERE active IS NOT NULL (wrong)
UPDATE tableTest SET name = 'My Name' WHERE active IS NOT NULL
Do not forget to use quotation marks when using strings
UPDATE tableTest SET name = My Name WHERE active IS NOT NULL (wrong)
UPDATE tableTest SET name = 'My Name' WHERE active IS NOT NULL
I hope it helps...
Good Luck!

MS Access SQL query within VBA code

I need a second set of eyes on this SQL query embedded in the VBA code. I'm making an MS Access app that returns a dataset based on the to & from date criteria set by the user in the specific date picker boxes. The sql query that you see actually has been tested statically within MS Access query design view. I tested it with actual dates where you see the Me.from_filter and Me.to_filter. It worked perfectly! If you chose something like from 1/1/2015 to 5/1/2015 it returns columns of all the months you need. Perfect. Now when I embed it in the VBA code and assign it to a control variable, I get the "Run-time error '2342': A RunSQL action requires an argument consisting of an SQL statement." Can someone please eyeball this and tell me what might be wrong?
Option Compare Database
Option Explicit
Dim strSQL As String
Private Sub Command0_Click()
If IsNull(Me.from_filter) Or IsNull(Me.to_filter) Then
MsgBox "You have not entered a start date or end date"
Else
strSQL = "TRANSFORM Sum(dbo_ASSET_HISTORY.MARKET_VALUE) AS SumOfMARKET_VALUE " _
& "SELECT [dbo_FIRM]![NAME] AS [FIRM NAME], dbo_FUND.CUSIP, dbo_FUND.FUND_NAME, dbo_FUND.PRODUCT_NAME " _
& "FROM (dbo_ASSET_HISTORY INNER JOIN dbo_FIRM ON dbo_ASSET_HISTORY.FIRM_ID = dbo_FIRM.FIRM_ID) INNER JOIN dbo_FUND ON dbo_ASSET_HISTORY.FUND = dbo_FUND.FUND " _
& "WHERE (((dbo_FIRM.Name) Like 'Voya F*') And ((dbo_ASSET_HISTORY.PROCESS_DATE) >= #" & Me.from_filter & "# And (dbo_ASSET_HISTORY.PROCESS_DATE) <= #" & Me.to_filter & "#)) " _
& "GROUP BY [dbo_FIRM]![NAME], dbo_FUND.CUSIP, dbo_FUND.FUND_NAME, dbo_FUND.PRODUCT_NAME " _
& "PIVOT [dbo_ASSET_HISTORY]![ASSET_YEAR] & '-' & [dbo_ASSET_HISTORY]![ASSET_MONTH];"
DoCmd.RunSQL (strSQL)
End If
End Sub
RunSQL is for running action queries like update, insert, select into, delete, etc as per Microsoft definition https://msdn.microsoft.com/en-us/library/office/ff194626.aspx , you should probably use OpenQuery or similar to run your query.

VBScript not executing sql statment properly

I write you this time because a VBScript that one of the application my company uses to retrieve information from an Oracle database does not seem to be working properly. Here are the facts:
There's part of the code that does the following:
sSql = "SELECT REQ_PAYMODE" & _
" FROM SYSADM.GBPRESTATIEGROEP" & _
" WHERE 1=1" & _
" AND SLEUTEL = " & sKeyPrestatiegroep
Set oRSGBPrest = connADO.execute(sSql)
If Not oRSGBPrest.EOF Then
sRequestPaymodeKey = oRSGBPrest("REQ_PAYMODE")
Else
//error handling
End If
Using a Statement Tracer for Oracle (www.aboves.com) I can capture that same statement with its corresponding value:
SELECT REQ_PAYMODE FROM
SYSADM.GBPRESTATIEGROEP WHERE 1=1 AND
SLEUTEL = 1572499
Now, the VBScript is supposed to take that value and execute another query:
sSql = "SELECT PAM_CODE" & _
" FROM SYSADM.PAYMODES" & _
" WHERE 1=1" & _
" AND PAM_KEY = " & sRequestPaymodeKey
Set oRSPaymodes = connADO.execute(sSql)
Right in this last line of code, the script throws an error that says:
ORA-00936: missing expression at line XXX --> Set oRSPaymodes = connADO.execute(sSql) <--
Which basically means that the query in (3) is not correct, which also means that for some reason sRequestPaymodeKey is empty. I cannot tell this for sure because this failing sql statement does not appear in the statement tracer, but that's the only explanation I could find. However, the worst part is that when running the query (2) on SQLDeveloper (that's where value sRequestPaymodeKey comes from) it shows a row with a value other than null or zero.
I can't think of anything else that might be happening here, maybe it's just a server thing... no idea.
Any suggestions from you guys? Any way I can actually debug a VBE file?
Your help is much appreciated!
You need to cast sRequestPaymodeKey as a vbLong which corresponds to sql's INT. I'm assuming PAM_KEY is an INT. A recordset will return a string value. So, your code would look like this:
If IsNumeric(sRequestPaymodeKey) Then
sSql = "SELECT PAM_CODE" & _
" FROM SYSADM.PAYMODES" & _
" WHERE 1=1" & _
" AND PAM_KEY = " & CLng(sRequestPaymodeKey)
Set oRSPaymodes = connADO.execute(sSql)
Else
'do error handling due to bad returned data(empty string?)
End If
Also, consider parameterizing your queries to prevent sql injection.
A few ideas to try:
Before Set oRSPaymodes = connADO.execute(sSql), put in a MsbBox and see what SQL is being executed. Is it valid? Will it run in a Oracle query analyzer(if there is one)?
Hard code a valid value in place of sRequestPaymodeKey. Does it work then?