473,587 Members | 2,479 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Can I perform a DCount of records returned by SQL statement (not a saved query)

MLH
Suppose I have this simple SQL string...

SELECT tblDrivers.Driv erID, tblDrivers.DNam e
FROM tblDrivers
WHERE (((tblDrivers.D Name) Like "N*"))
ORDER BY tblDrivers.Driv erID;

And suppose that its not a saved querydef -
just an SQL string that I cooked up in code
and assigned to a global var strMySQL.

How best to count the records returned by
the query? DCount doesn't seem to be the
tool to do it with.
Nov 13 '05 #1
13 6575

"MLH" <CR**@NorthStat e.net> wrote in message
news:i3******** *************** *********@4ax.c om...
Suppose I have this simple SQL string...

SELECT tblDrivers.Driv erID, tblDrivers.DNam e
FROM tblDrivers
WHERE (((tblDrivers.D Name) Like "N*"))
ORDER BY tblDrivers.Driv erID;

And suppose that its not a saved querydef -
just an SQL string that I cooked up in code
and assigned to a global var strMySQL.

How best to count the records returned by
the query? DCount doesn't seem to be the
tool to do it with.


That query will select all records from tblDrivers where DName starts with
'N'. The practical solution would be simply:

SELECT Count(*)
FROM tblDrivers
WHERE DName Like 'N*'

If for some reason you absolutely must use that original query, you could
use:

"SELECT Count(*) From (" & strMySQL & ")"

HTH,
Randy

Nov 13 '05 #2
MLH <CR**@NorthStat e.net> wrote in
news:i3******** *************** *********@4ax.c om:
Suppose I have this simple SQL string...

SELECT tblDrivers.Driv erID, tblDrivers.DNam e
FROM tblDrivers
WHERE (((tblDrivers.D Name) Like "N*"))
ORDER BY tblDrivers.Driv erID;

And suppose that its not a saved querydef -
just an SQL string that I cooked up in code
and assigned to a global var strMySQL.

How best to count the records returned by
the query? DCount doesn't seem to be the
tool to do it with.

Since DCount opens a separate instance of the query, it can't be
done if the sql isn't saved. You can create a recordset, that
uses an SQL string as its source, and get the number of records
from that.

set rs = currentdb.openR ecordset(strMyS QL, dbOpenSnapshot)
rs.movelast
msgbox "the query returns " & rs.recordcount & " Records"
--
Bob Quintal

PA is y I've altered my email address.
Nov 13 '05 #3
MLH
<snip>

That query will select all records from tblDrivers where DName starts with
'N'. The practical solution would be simply:

SELECT Count(*)
FROM tblDrivers
WHERE DName Like 'N*' Sounds like a plan. If X is my variable dim'd as Long,
what VBA syntax is used to assign X its value of the
number of records in tblDrivers WHERE DName Like 'N*'?

If for some reason you absolutely must use that original query, you could
use:

Not at all, Randy. I like the above - as long as I can assign the
count to the variable, X. 'preciate it.
Nov 13 '05 #4

"MLH" <CR**@NorthStat e.net> wrote in message
news:rq******** *************** *********@4ax.c om...
<snip>

That query will select all records from tblDrivers where DName starts with'N'. The practical solution would be simply:

SELECT Count(*)
FROM tblDrivers
WHERE DName Like 'N*'

Sounds like a plan. If X is my variable dim'd as Long,
what VBA syntax is used to assign X its value of the
number of records in tblDrivers WHERE DName Like 'N*'?

If for some reason you absolutely must use that original query, you could
use:

Not at all, Randy. I like the above - as long as I can assign the
count to the variable, X. 'preciate it.


In ADO, you could use something like this:

Dim varCount
Dim SQL as string
Dim lngX
Dim cn as New ADODB.Connectio n

Set cn = CurrentProject. Connection

SQL = "Select Count(*) " & _
"From tblDrivers " & _
"Where DName Like 'N*'"

varCount = cn.Execute(SQL) .GetString
lngX = Nz(varCount, 0)

Some comments:
I'm in the habit of using a var with .GetString. I do that in case the query
returns a Null value. Anything other than a var will get an error. In this
particular case, it wouldn't be necessary to do so, because a Count always
returns a value, even if it's 0. If you prefer, you could simply use:

lngX = cn.Execute(SQL) .GetString

HTH,
Randy

Nov 13 '05 #5
MLH
Thank-you, Randy. To my knowledge, this is my first look
at ADO. Mind you, I've done my homework in DAO and this
looks similar. 'preciate the advice. I was beginning to think
that DAO might be the way to go and I'm glad to get an
introduction to DAO via this issue.

In ADO, you could use something like this:

Dim varCount
Dim SQL as string
Dim lngX
Dim cn as New ADODB.Connectio n

Set cn = CurrentProject. Connection

SQL = "Select Count(*) " & _
"From tblDrivers " & _
"Where DName Like 'N*'"

varCount = cn.Execute(SQL) .GetString
lngX = Nz(varCount, 0)

Some comments:
I'm in the habit of using a var with .GetString. I do that in case the query
returns a Null value. Anything other than a var will get an error. In this
particular case, it wouldn't be necessary to do so, because a Count always
returns a value, even if it's 0. If you prefer, you could simply use:

lngX = cn.Execute(SQL) .GetString

HTH,
Randy

I like that extra bit of effort. It may seem redundant to some (like
putting a forward or backward slash at the end when you're DIRing
for a directory at the command prompt to specify a directory rather
than a file). I'm always questioning my work and any little thing to
provide reassurance that stuff is working helps me sleep better.
Nov 13 '05 #6
Personally, I find this DAO/ADO dichotomy absolutely maddening. I curse
Microsoft for the stop - start - misdirection of the whole mess. A lot of
the guru types that post here effectively use them together. I find it
confusing to do so. I stick with ADO - not because it's better - but,
because it is what I am comfortable with.

Perhaps someone else would post some DAO-centric code that will accomplish
the same thing?
"MLH" <CR**@NorthStat e.net> wrote in message
news:b4******** *************** *********@4ax.c om...
Thank-you, Randy. To my knowledge, this is my first look
at ADO. Mind you, I've done my homework in DAO and this
looks similar. 'preciate the advice. I was beginning to think
that DAO might be the way to go and I'm glad to get an
introduction to DAO via this issue.

In ADO, you could use something like this:

Dim varCount
Dim SQL as string
Dim lngX
Dim cn as New ADODB.Connectio n

Set cn = CurrentProject. Connection

SQL = "Select Count(*) " & _
"From tblDrivers " & _
"Where DName Like 'N*'"

varCount = cn.Execute(SQL) .GetString
lngX = Nz(varCount, 0)

Some comments:
I'm in the habit of using a var with .GetString. I do that in case the queryreturns a Null value. Anything other than a var will get an error. In thisparticular case, it wouldn't be necessary to do so, because a Count alwaysreturns a value, even if it's 0. If you prefer, you could simply use:

lngX = cn.Execute(SQL) .GetString

HTH,
Randy

I like that extra bit of effort. It may seem redundant to some (like
putting a forward or backward slash at the end when you're DIRing
for a directory at the command prompt to specify a directory rather
than a file). I'm always questioning my work and any little thing to
provide reassurance that stuff is working helps me sleep better.


Nov 13 '05 #7
Dim varCount
Dim SQL as string
Dim lngX
Dim rs as DAO.Recordset

SQL = "Select Count(*) As Records " & _
"From tblDrivers " & _
"Where DName Like 'N*'"

Set rs = CurrentDb.Creat eRecordset(SQL)
If rs.EOF = False
lngX = Nz(rs!Records, 0)
End If

rs.Close
Set rs = Nothing

--
Doug Steele, Microsoft Access MVP
http://I.Am/DougSteele
(no e-mails, please!)

"Randy Harris" <ra***@SpamFree .com> wrote in message
news:Mm******** ******@newssvr1 7.news.prodigy. com...
Personally, I find this DAO/ADO dichotomy absolutely maddening. I curse
Microsoft for the stop - start - misdirection of the whole mess. A lot of
the guru types that post here effectively use them together. I find it
confusing to do so. I stick with ADO - not because it's better - but,
because it is what I am comfortable with.

Perhaps someone else would post some DAO-centric code that will accomplish
the same thing?
"MLH" <CR**@NorthStat e.net> wrote in message
news:b4******** *************** *********@4ax.c om...
Thank-you, Randy. To my knowledge, this is my first look
at ADO. Mind you, I've done my homework in DAO and this
looks similar. 'preciate the advice. I was beginning to think
that DAO might be the way to go and I'm glad to get an
introduction to DAO via this issue.
>
>In ADO, you could use something like this:
>
>Dim varCount
>Dim SQL as string
>Dim lngX
>Dim cn as New ADODB.Connectio n
>
>Set cn = CurrentProject. Connection
>
>SQL = "Select Count(*) " & _
> "From tblDrivers " & _
> "Where DName Like 'N*'"
>
>varCount = cn.Execute(SQL) .GetString
>lngX = Nz(varCount, 0)
>
>Some comments:
>I'm in the habit of using a var with .GetString. I do that in case the query >returns a Null value. Anything other than a var will get an error. In this >particular case, it wouldn't be necessary to do so, because a Count always >returns a value, even if it's 0. If you prefer, you could simply use:
>
>lngX = cn.Execute(SQL) .GetString
>
>HTH,
>Randy

I like that extra bit of effort. It may seem redundant to some (like
putting a forward or backward slash at the end when you're DIRing
for a directory at the command prompt to specify a directory rather
than a file). I'm always questioning my work and any little thing to
provide reassurance that stuff is working helps me sleep better.

Nov 13 '05 #8
MLH
I have a sneaky suspicion that CreateRecordset isn't
going to work for me in A97. Am I wrong about that?
Or, is my hunch correct?
I'm guessing that OpenRecordset is the method I'll
use in A97. Here's what I tried but 'yikes' it isn't
working...
MySQL = "SELECT DISTINCTROW qryVehiclesNown ers5.SerialNum,
qryVehiclesNown ers5.VDescr, qryVehiclesNown ers5.Owner,
qryVehiclesNown ers5.VehicleJob ID , tblVehicleJobs. Reclaimed,
tblVehicleJobs. VSaleID, tblVehicleJobs. ENF262Written FROM
qryVehiclesNown ers5 INNER JOIN tblVehicleJobs ON
qryVehiclesNown ers5.VehicleJob ID = tblVehicleJobs. VehicleJobID WHERE
(tblVehicleJobs .Reclaimed=No AND tblVehicleJobs. VSaleID Is Null AND
tblVehicleJobs. ENF262Written=T rue);"

Dim dbs As Database, rst As Recordset

' Return reference to current database.
10 Set dbs = CurrentDb
20 Set rst = dbs.OpenRecords et(MySQL)
30 rst.MoveLast
40 Me!TheCount = rst.RecordCount
50 rst.Close
60 Set dbs = Nothing

But error handler says line #20 is a problem...
"The following unexpected error occurred in Sub Form_Open, Line #20,
CBF on frmVehicleChoos erForm. 3061: "Too few parameters, Expected 5."
Kind-a-blows my mind. A simple piece of SQL works. For instance: If
MySQL = "select VehicleJobID from tblVehicleJobs; " - there's no
error. Any ideas why? The SQL works find pasted into a query and ran.
xxxxxxxxxxxxxxx xxxxxxxxxxxxxxx xxxxxxxxxxxxxxx xxxxxx

Dim varCount
Dim SQL as string
Dim lngX
Dim rs as DAO.Recordset

SQL = "Select Count(*) As Records " & _
"From tblDrivers " & _
"Where DName Like 'N*'"

Set rs = CurrentDb.Creat eRecordset(SQL)
If rs.EOF = False
lngX = Nz(rs!Records, 0)
End If

rs.Close
Set rs = Nothing


Nov 13 '05 #9

"MLH" <CR**@NorthStat e.net> wrote in message
news:a4******** *************** *********@4ax.c om...
I have a sneaky suspicion that CreateRecordset isn't
going to work for me in A97. Am I wrong about that?
Or, is my hunch correct?
I'm guessing that OpenRecordset is the method I'll
use in A97. Here's what I tried but 'yikes' it isn't
working...
MySQL = "SELECT DISTINCTROW qryVehiclesNown ers5.SerialNum,
qryVehiclesNown ers5.VDescr, qryVehiclesNown ers5.Owner,
qryVehiclesNown ers5.VehicleJob ID , tblVehicleJobs. Reclaimed,
tblVehicleJobs. VSaleID, tblVehicleJobs. ENF262Written FROM
qryVehiclesNown ers5 INNER JOIN tblVehicleJobs ON
qryVehiclesNown ers5.VehicleJob ID = tblVehicleJobs. VehicleJobID WHERE
(tblVehicleJobs .Reclaimed=No AND tblVehicleJobs. VSaleID Is Null AND
tblVehicleJobs. ENF262Written=T rue);"

Dim dbs As Database, rst As Recordset

' Return reference to current database.
10 Set dbs = CurrentDb
20 Set rst = dbs.OpenRecords et(MySQL)
30 rst.MoveLast
40 Me!TheCount = rst.RecordCount
50 rst.Close
60 Set dbs = Nothing

But error handler says line #20 is a problem...
"The following unexpected error occurred in Sub Form_Open, Line #20,
CBF on frmVehicleChoos erForm. 3061: "Too few parameters, Expected 5."
Kind-a-blows my mind. A simple piece of SQL works. For instance: If
MySQL = "select VehicleJobID from tblVehicleJobs; " - there's no
error. Any ideas why? The SQL works find pasted into a query and ran.
xxxxxxxxxxxxxxx xxxxxxxxxxxxxxx xxxxxxxxxxxxxxx xxxxxx


It's likely that you've got a syntax error in the WHERE clause. Try running
the code after removing the entire WHERE clause.

What datatypes are Reclaimed and ENF262Written?

Nov 13 '05 #10

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

Similar topics

7
5565
by: jdph40 | last post by:
I posted this problem previously and received excellent help from Wayne Morgan. However, I still have an unanswered question. My form (frmVacationWeeks) is opened from the OnClick event of a button on another form (frmEmpList) which has a list box that contains the names of all employees. When a name is selected in the list box and the button is clicked, frmVacationWeeks opens and is filtered using the following: ". IN (" & Left(strSQL,...
5
8288
by: Terri | last post by:
I have a form with a multi-select combo. I dynamically build a SELECT statement, open a report, and set the recordsource to my dynamic SELECT statement. I count the records returned in the report by setting a text box to =Count(*). This works fine. Now I want to count the unique records in my report. I can dynamically create a SELECT statement that counts unique records. My statement looks like this: SELECT DISTINCT...
4
7535
by: Will | last post by:
Hi, I had a DCount within a module on records in a table where CustSuffix = 0. I now need to DCount where CustSuffix = 0 and the type of cost Suffix (Suffix in table) = G. I can't get both requirements to work and have tried a number of different formats. At the moment I am getting an object required error message. This is the current code: Function UpdateDistributionCost(Suff As String) ' adds new record if none exists, prompting...
6
3312
by: Mike Conklin | last post by:
This one really has me going. Probably something silly. I'm using dcount for a report to determine the number of different types of tests proctored in a semester. My report is based on a parameter query which is the recordsource for the report. The parameter is <=. The query returns the correct amounts upto the date entered (no need for "between" dates here). There are 8 textboxes with dcounts; 2 other boxes Sum some of these
3
3320
by: BerkshireGuy | last post by:
I am having difficulty with using the Dcount function. I am trying to return the number of records from qryIndividualFeedbackDetail where the TimelyManner field is set to 4. So, in the new query I am trying the following: NumOfYes: Dcount(,"qryIndividualFeedbackDetail",=4) The query is counting ALL of the timely manners and is ignoreing my
6
17916
by: Rajat Katyal | last post by:
Hi: In postgres documentation its written that if we execute query as PERFORM query inside our stored procedure; then the special variable FOUND is set totrue if the query produced at least one row, or false if it produced no rows. But FOUND variable is always returning true even my query is returning 0 records. Please suggest me the solution. Thanks and Regards, Rajat.
7
1832
by: MLH | last post by:
?dcount("","qryOwnrsDueITSwMissingAddr") when run in the immediate window return a number greater than the number of rows that display when the saved query is run - opening in the database window? I consistently see 2 rows in qryOwnrsDueITSwMissingAddr opening with a dbl-clik. Yet ?dcount("","qryOwnrsDueITSwMissingAddr") returns 3 and
6
5466
by: InnoCreate | last post by:
Hi everyone. I've recently written a classic asp website which uses an MS Access datasource. I know this is less than an ideal data source as it has limited functionality. I have a search form on my website which allows users to define parameters and return results accordingly. The problem i have is a need to return these results in a random order each time. With SQLServer i know NEWID() would do the trick - used this many times before...
3
4870
by: ringer | last post by:
I am trying to add a functionality into a db I use for my checkbook that will help me plan for and save money for future large expenses. Into a table called tblFutureTransactions I want to enter records for upcoming large expenses, the dollar amount needed, the date the money is needed, and the date I want to start saving. Then I want the db to automatically figure and deduct from my balance an amount of money from each paycheck to save for...
0
7852
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8216
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
8349
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
7974
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
5395
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
3845
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2364
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
1
1455
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1192
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.