473,738 Members | 2,492 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Running a SELECT query from code

Hi All,

How do you run a SELECT query from code? I know that DoCmd.RunSQL only
works with action or DDF queries but I need to run a query from VBA and
add variables into the query as defined by entries on a form.

Many thank, Dean...

Jul 10 '06 #1
6 49390
AccessAl
7 New Member
Have you used ADO? You need to set a reference to Microsoft Active Data Object Library. Then you can use code like:

dim cmd as adodb.command

cmd.activeconne ction = currentproject. connection
cmd.CommandType = adCmdText
cmd.CommandText = "SELECT * FROM myTable " & _
"WHERE primaryKey = " & comboBoxPrimary Key
cmd.Execute


This is elementary but might get you in a good direction
Jul 10 '06 #2

DeanL wrote:
Hi All,

How do you run a SELECT query from code? I know that DoCmd.RunSQL only
works with action or DDF queries but I need to run a query from VBA and
add variables into the query as defined by entries on a form.

Many thank, Dean...
SELECT ....
FROM ....
WHERE [Field1] = Forms![MyOpenForm]![ControlName]
AND [Field2] Val(Forms![MyOpenForm]![NumericControlV alue]

Jul 10 '06 #3

pietlin...@hotm ail.com wrote:
DeanL wrote:
Hi All,

How do you run a SELECT query from code? I know that DoCmd.RunSQL only
works with action or DDF queries but I need to run a query from VBA and
add variables into the query as defined by entries on a form.

Many thank, Dean...

SELECT ....
FROM ....
WHERE [Field1] = Forms![MyOpenForm]![ControlName]
AND [Field2] Val(Forms![MyOpenForm]![NumericControlV alue]
Thanks, I already have the SQL but need to find out HOW to execute it
from code when a button is pressed on a form.

Jul 10 '06 #4
"DeanL" <de************ *@yahoo.comwrot e in
news:11******** **************@ m79g2000cwm.goo glegroups.com:
>
pietlin...@hotm ail.com wrote:
>DeanL wrote:
Hi All,

How do you run a SELECT query from code? I know that
DoCmd.RunSQL only works with action or DDF queries but I
need to run a query from VBA and add variables into the
query as defined by entries on a form.

Many thank, Dean...

SELECT ....
FROM ....
WHERE [Field1] = Forms![MyOpenForm]![ControlName]
AND [Field2] Val(Forms![MyOpenForm]![NumericControlV alue]

Thanks, I already have the SQL but need to find out HOW to
execute it from code when a button is pressed on a form.
You attach it to a form (or report) and open that. You can make
the form look like a query grid very easily.

Alternatively, you can write the SQL to a querydef and
docmd.OpenQuery which is not reccomended in multiuser
situations.

--
Bob Quintal

PA is y I've altered my email address.

--
Posted via a free Usenet account from http://www.teranews.com

Jul 10 '06 #5
Hi Dean,

What you ask is exactly the way I work with all my Access-applications.
In the way I can tune the next form exactly depending on the values of
the former forms.

In the Form_open-procedure you make your SQL-string.
Such a string looks like: cur_sql = "SELECT " & cur_fields & " FROM " &
cur_tables & cur_criteria & cur_order.

e.g.
cur_fields = "*,Concat(First _name,Middle_na me,Last_name) AS Person"
cur_tables = "(Person_tb l INNER JOIN Member_tbl ON Person_tbl.Pers on_id
= Member_tbl.Pers on_tbl)"
cur_criteria = " WHERE First_name = " & As_text ("Jan")
cur_order = " ORDER BY Last_name"

Concat is an own_made string-function which adds a space and a value if
this value <Null, for each parameter.
As_text is an own_made string-function that returns the quoted
parameter (you don't have to bother about the right number of quotes).

Finally, if you are happy with your cur_sql, assign it to the forms'
Recordsource:

Me.RecordSource = cur_sql.

In fact I build a systematic, in which this cur_sql is generated
automatically, appliclable for any database.

Success, HBinc.
DeanL wrote:
Hi All,

How do you run a SELECT query from code? I know that DoCmd.RunSQL only
works with action or DDF queries but I need to run a query from VBA and
add variables into the query as defined by entries on a form.

Many thank, Dean...
Jul 11 '06 #6
First you will have to create a QueryDef.

'Normal Query
Dim qryDef as QueryDef
Dim txtSQL as string

txtSQL = "Select * FROM MyTable"
DBEngine.BeginT rans
Set qdf = db.CreateQueryD ef("MyQuery", txtSQL)

CurrentDB.Query Defs.Refresh
DBEngine.Commit Trans

DoCmd.OutputTo acOutputQuery, "MyQuery", , , 1
'If you want to create pass-through query

Dim qryDef as QueryDef
Dim txtSQL as string

txtSQL = "select * from MyTable"

Set qrydef = CurrentDb.Creat eQueryDef("MyQu ery")

qrydef.Connect = _
"ODBC;DATABASE= MyDatabase;UID= sa;PWD=;DSN=MyD SN"

txtSQL.SetFocus
qrydef.SQL = txtSQL
qrydef.ReturnsR ecords = True

DoCmd.OutputTo acOutputQuery, "MyQuery", , , 1

Jul 12 '06 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
14477
by: VMI | last post by:
How can I run a Select query from a datatable so that it only brings the fields I want? For example, if my datatable has 30 fields, a query would be "select custId, Name" because those are the only two fields I need. Then I'd like to put the result in another datatable. Thanks.
3
3236
by: isetea | last post by:
Hi, I've got the follwing issue. I have a command button on a form, which selects a query after beeing pressed. The data from the query is a combination of data from 3 tables. Now I want to make a step in between. I want to give the users the possibility to restrict the output of the query. E.g. The query previously showed all staff. Now the user selects only one department (maybe a combo box having an event procedure...) and when they press...
6
1704
by: Zairay | last post by:
Hi All, I have a problem with running a query. Str = "SELECT Biographies.BID, Biographies.family_name AS , " & _ "Biographies.first_name AS , Biographies.sonof AS , " & _ "Biographies.alias, " & _ "Biographies.pob, Biographies.dob,
9
4021
by: JJM0926 | last post by:
I'm trying to create a running totals query in access 97. I have followed the directions on how to do it from Microsofts website article id 138911. I took their code they had and replaced it with my fields. When I try to run it I get #errors in my RunTot column. I'm kinda new to this. Not sure if maybe I mistyped something wrong or is there a better way to do this? I have pasted the code. Any help would be greatly appreciated....
2
9035
by: DotNetDanjo | last post by:
I want a stored procedure to run a select query on it's own like this: Select *, user_id As UserId FROM CC_host.dbo.usr_table Where(email LIKE N'%@%usa.com') But from these results I want the same stored procedure to INSERT any new records (user_id as primary key) into the next table.. If Not Exists (Select As UserId2 From Usr_Type_Data WHERE UserId2 = UserId) INSERT INTO Usr_Type_Data (user_id, CustomerTypeId) VALUES(t1.UserId, 7) ...
6
5322
by: Nano | last post by:
I have created ASP file from MS Access. It has the following Code. But it gives an error at: rs.Open sql, conn, 3, 3 The Error is: Error Type: Microsoft OLE DB Provider for ODBC Drivers (0x80040E10) Too few parameters. Expected
8
2243
by: Trevor2007 | last post by:
I have this select query : SELECT DISTINCT ReferredToLU.ReferredTo FROM ReferredToLU ORDER BY ReferredToLU.ReferredTo; I would like to do two thing but not sure if they are possable or how to do them 1) using this query I would like to omitt the value "N/A" (w/o quotes) 2 ) omitt "N/A"(w/o quotes) and omite a persons name in a value in column where colume does not equal "lead" (w/o quotes) The reason, I have 3 tables with basicly...
0
1466
by: GEETHA LAKSHMI | last post by:
I want to use where conditions in both update and select query cmd1.CommandText = "Update AttRegister set Present= (Select count(Working) from Attendance where Attendance.Working='P' and Attendance.EmpCode=" & row!Empcode & " and Attendance.AttDate between #" & Convert.ToDateTime(CmbFromDate.Text.Substring(6, 4) + "/" + CmbFromDate.Text.Substring(3, 2) + "/" + CmbFromDate.Text.Substring(0, 2)) & "# and #" &...
1
2717
by: Tami Robinson | last post by:
I keep getting !Overflow error when running this query: SELECT DISTINCTROW FamilyInfo.FamilyInfoID , Sum(IIf(IsNull(VitalPartnerCreditsQuery.VPCreditT),0,VitalPartnerCreditsQuery.VPCreditT)) AS TotVPCredit FROM VitalPartnerCreditsQuery RIGHT JOIN FamilyInfo ON VitalPartnerCreditsQuery.FamilyInfoID = FamilyInfo.FamilyInfoID GROUP BY FamilyInfo.FamilyInfoID; Any help would be appreciated. Thx
0
8968
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9473
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9334
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9259
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8208
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6750
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6053
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4824
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3279
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.