to use module in sql ms-Access-2010 - sql

I have defined a procedure in my module, returning the path of the database and I want to use that path in my sql query.
Procedure in module :
Public Function pathOfBillingSoftware() As String
pathOfBillingSoftware = """path"""
End Function
I am using the function above in my sql query :
SELECT *
FROM tableName IN pathOfBillingSoftware();
It is giving me the error: "error in from clause"
but when I am using it in vba code , it is working fine
a = pathOfBillingSoftware()
sql = "INSERT INTO tableName " & _
"IN " & a & _
" SELECT * FROM tableName"
currentdb.Execute sql
Any Solution ?

This is dynamic SQL. You seem to already have found the solution: use VBA code. You can only use functions to return values in static SQL.
If you want to return operators or other things that aren't standard values, you need to use dynamic SQL, and thus need to use VBA.
You can create queries through VBA if you want, but note that once they are created, they are static.
Sample code to create a query with your function
CurrentDb.CreateQueryDef "MyQuery", "SELECT * FROM tableName IN " & pathOfBillingSoftware();

Related

Run one MS Access SQL script on a particular Table chosen by user

I have a MS Access 2016 database (*.accdb) with 20+ Tables. Fields in each of them vary slightly from Table to Table. I've no VBA experience, so I'm sticking only to the SQL query below (redacted).
SQL script
myvar below is the parameter I'd like to be prompted when the script is run so that I enter the Table I want the changes applied to.
PARAMETERS
[myvar] TableID;
UPDATE
[myvar]
INNER JOIN
Excel_Data ON [myvar].[Part Number] = Excel_Data.[Part Number]
SET
[myvar].[Value] = '?',
[myvar].Description = Excel_Data.Description,
[myvar].[Ref] = '?'
.
.
.
WHERE
[myvar].Description Is Null;
Output
Error message:
Too few parameters. Expected 0.
What I need
I prefer a solution for above in a SQL script form as above, not involving VBA, preferably. I'd like to enter the Table name when prompted so the script knows which table to UPDATE. FYI: The PARAMETERS work when it is not a Table as I've shown in my script above.
Help/advise is highly appreciated.
EDIT 1
Since it seems not possible to use parameters as Table names, could you suggest a VBA solution? A sample code, perhaps?
As said in the comments, you can't really solve this without VBA.
You can store your SQL query in a string, and use a placeholder to indicate the tablename. Then get the tablename using an inputbox and replace the placeholder with the tablename.
Dim sqlString As String
sqlString = "UPDATE [%Placeholder%] " & vbCrLf & _
"INNER JOIN Excel_Data ON [%Placeholder%].[Part Number] = Excel_Data.[Part Number] " & vbCrLf & _
"SET [%Placeholder%].[Value] = '?', " & vbCrLf & _
...
"WHERE [%Placeholder%].Description Is Null;"
sqlString = Replace(sqlString, "%PlaceHolder%", InputBox("Enter a tablename"))
CurrentDb.Execute sqlString
In a more mature solution, I'd create a form with a combobox containing all available table names, and add a function to sanitize tablenames (replace "]" with "]]")

MS Access parameterized queries VB

dbs.Execute " INSERT INTO Log " _
& "(UserName, DateAccessed) VALUES " _
& "(#GetLogonName, #Today);"
GetLogonName and Today are variables but I get error "error- too few parameters, expected two". If I run the function using actual values like &"('abce', '2/2/2012') it works.
What am I doing wrong?
Thanks
Database.Execute doesn't accept query parameters, only the execution options defined in RecordsetOptionEnum.
To run a parameterized query you need to create a QueryDef object:
Dim query As QueryDef
Set query = dbs.CreateQueryDef("", "INSERT INTO LOG (UserName,DateAccessed)" & _
" VALUES(#user,#time)")
query.Parameters("#user").Value = "Moo"
query.Parameters("#time").Value = Now
query.Execute
The empty string means this is a temporary QueryDef. If you enter any other name, or omit the name entirely, a new Query object will be created in the database.
If you use the same query frequently, it's a good idea to create a Query and call it by name:
Set query = dbs.QueryDefs("myQueryName")
...
QueryDef.Execute accepts the same execution parameters as Database.Execute

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

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]) "

Expected function / variable error message

i am trying to write a simple append query using SQL for my access database. Upon trying to execute the code, the message i am getting is:
Complilation error. Exepected function or variable
The query is a query which joins 4 tables and pastes the fields into another table. When using a standard MS Access query it works fine. I then generated and copied the SQL code (below) but unfortunately cannot get the query to work.
A final note about something strange. Unlike all the other SQL queries i have successfully written, this one, upon writing the Application.DoCmd.RunSQL (st_sql) into VBA, the space between the "L" and the "(st_sql) for some reason gets truncated.. Strange, this doesnt happen for any other string in the Whole routine where i successfully have other append queries.
Below is the code:
st_sql = "INSERT INTO[tblContactReporting03]([ID Project],[tblProjManagementPhaseHierarchy],[tblProjManagementSubPhaseHierarchy],[ID_Event],[SubTask_Hierarchy],[Project],[Sub project],[Project_Phase],[Project_Sub_Phase],[ContactFullName],[Role_Type],[type],[Event],[Effective_date],[Commitment],[Sub_task_name],[Status],[Notes])" & _
"SELECT[tblProjectMasterList].[ID Project],[tblProjManagementPhase].[Hierarchy],[tblProjManagementSubPhase].[Hierarchy],[tblContactReporting02].[ID_Event],[tblContactReporting02].[SubTask_Hierarchy],[tblProjectMasterList].[Project],[tblProjectMasterList].[Sub project],[tblProjManagementPhase].[Project_Phase],[tblProjManagementSubPhase].[Project_Sub_Phase],[tblContactReporting02].[ContactFullName],[tblContactReporting02].[Role_Type],[tblContactReporting02].[type]," & _
"[tblContactReporting02].[Event], [tblContactReporting02].[Effective_date],[tblContactReporting02].[Commitment],[tblContactReporting02].[Sub_task_name],[tblContactReporting02].[Status],[tblContactReporting02].[Notes]" & _
"FROM[tblProjectMasterListINNER JOIN ([tblProjManagementPhase] INNER JOIN ([tblContactReporting02] INNER JOIN [tblProjManagementSubPhase] ON [tblContactReporting02].[ID_Project_Sub_Phase] = [tblProjManagementSubPhase].[ID_Project_Sub_Phase]) ON ([tblContactReporting02].[ID_Project_Phase] = [tblProjManagementPhase].[ID_Project_Phase]) AND ([tblProjManagementPhase].[ID_Project_Phase] = [tblProjManagementSubPhase].[ID_Project_Phase])) ON [tblProjectMasterList].[ID Project] = [tblProjManagementPhase].[ID_Project]" & _
"ORDER BY [tblProjectMasterList].[ID Project], [tblProjManagementPhase].[Hierarchy], [tblProjManagementSubPhase].[Hierarchy], [tblContactReporting02].[ID_Event], [tblContactReporting02].[SubTask_Hierarchy];" & _
Application.DoCmd.RunSQL(st_sql)
I'd recommend a Debug.Print st_sql before running so that you'll be able to debug the constructed SQL.
The error you're getting is because RunSQL is a sub, not a function, so you need to call it 1) without parentheses:
Application.DoCmd.RunSQL st_sql
or 2) preceed it with Call and use parentheses:
Call Application.DoCmd.RunSQL(st_sql)
You can use syntax 2 for functions that when you don't need to use their return value.

"Null" value in Queries

I'm trying to run code that will copy fields into a new table, moving them from a _New table to the original table. The VBA code that does this works as such:
SQLStatement = CStr("INSERT INTO " & TName & " SELECT * FROM " & TName & "_New")
Log.WriteLine "Running query with string """ & SQLStatement & """ "
QueryTimer = Timer
DoCmd.RunSQL SQLStatement
Log.WriteLine "Query time: " & (Timer - QueryTimer)
The log is just a handful of procedures in a class module I threw together. Its output on the error is
#142921: Running query with string "INSERT INTO Records SELECT * FROM Records_New"
#142941: Error Date/Time: 7/21/2009 2:29:40 PM
#142941: Error # & Description: 3162, You tried to assign the Null value to a variable that is not a Variant data type.
I can confirm that TName and SQLStatement are both valid strings at the time the SQL operation is run, and that the sources (Records and Records_New) are both valid. Option Explicit is set elsewhere in the file to avoid any confusion from typos. The error is thrown on the DoCmd line.
Why would this have a Null value, even though DoCmd.RunSQL doesn't return a value?
Can you post the table descriptions for Records and Records_New tables?
I would wager that you are trying to insert a NULL value into one of the columns of the "Records" table (and the column description is NOT NULL).
Hope this helps.
I think it will help if you also change the insert statement to be more specific about which columns it is inserting/selecting. You are asking for bugs by being so non-specific.
This may seem like it is non-responsive to your answer, but I suspect that the columns in the select table and destination table are either not lined up, or there is a field in the destination table that disallows null.
Try this:
In a new Query (in SQL view) paste your query "INSERT INTO Records SELECT * FROM Records_New" in and try to run it manually. I bet you get a more specific error and can troubleshoot the query there before running it with the added complexity of the code around it.
INSERT INTO Statement (Microsoft Access SQL)
Your SQL INSERT statement is incorrect - it should be:
INSERT INTO Records SELECT * FROM [Records_New];
Here's what you need to use:
CStr("INSERT INTO " & TName & " SELECT * FROM [" & TName & "_New)"];")
Maybe Timer needs parens?
QueryTimer = Timer()