Wednesday, March 7, 2012

How To Count how many ROWS are returned in SQL Data Reader

My code keeps reading for another row when none are present....

There's are only unique records in the dB so far, but dupes are possible

While reader.has rows

reader.read

if value not db.null

get values

end if

end while

The program gets the row and reads it. After processing the values, it goes to thru the While and reads the next row (none), it then crashes on if value not db.null... because the value is null or no record. The dB has Values Required option on - no empty fields allowed.

Is there a way to count the ROWS returned?

Thanks.

That depends on your coding language, which one are you using ? For example the .NET Framework has the read() method which returns false if no record can be read anymore, leading to the following code:

while dr.Read()
{}

and to the fact that you won′t get an error if no rows is read anymore.

In my good old ASP ages there was something similar like rs.EOF or something, I guess there has to be be something in your coding language too.

HTH, Jens K. Suessmeyer.

http://www.sqlserver2005.de|||

I'm using VB.

But I'm using the WHILE there are ROWS, READ, so it shouldn't read if no more rows are present. Only ONE ROW is returned, so the WHILE statement should return FALSE on the second run of the loop and exit the LOOP because no more ROWS are present.

Moverover, it continued to READ, so perhaps the framework (NET) detected another row (empty) and reads it (while rows are present, read). Howbeit, this ROW is empty so an error is generated at the if not null.db line - but even so, it should NOT generate an error because NOT db.Null should detect that there is a Null Value and return FALSE and exit the loop.

How to count existing items?

I want to check and see if an item exists within one of my tables
before I go and replicate. let's say that "John Doe" already exists in
a names database and the user tries to add him again, i want to notify
the user that this name already exists. also, i want to do this
programatically(sp?) in C#.
any help?Put a unique constraint on the identifying columns. When you try to
insert (using a stored procedure), SQL Server will throw an error
(2627). Handle the error in your C# app.
JLuv wrote:
> I want to check and see if an item exists within one of my tables
> before I go and replicate. let's say that "John Doe" already exists in
> a names database and the user tries to add him again, i want to notify
> the user that this name already exists. also, i want to do this
> programatically(sp?) in C#.
> any help?|||You could do this in this manner
USE Northwind
GO
IF NOT EXISTS
( SELECT (LastName)
FROM Employees
WHERE ( LastName = 'Fuller'
AND FirstName = 'Andrea'
)
) INSERT INTO Employees
( LastName
, FirstName
)
VALUES
( 'Fuller'
, 'Andrea'
)
Your application can check the RowCount (RowsAffected) to determine if more
0 (zero) rows were inserted. Then message the user appropriately.
--
Arnie Rowland, YACE*
"To be successful, your heart must accompany your knowledge."
*Yet Another certification Exam
"JLuv" <JLuv3k6@.gmail.com> wrote in message news:1151692692.332535.294860@.75g2000cwc.google
groups.com...
>I want to check and see if an item exists within one of my tables
> before I go and replicate. let's say that "John Doe" already exists in
> a names database and the user tries to add him again, i want to notify
> the user that this name already exists. also, i want to do this
> programatically(sp?) in C#.
> any help?
>|||i've never tried that before. is this method called a "unique
constraint"? what should i search for to find information on this?
Stu wrote:
> Put a unique constraint on the identifying columns. When you try to
> insert (using a stored procedure), SQL Server will throw an error
> (2627). Handle the error in your C# app.
>
> JLuv wrote:|||i did something like that. i went and updated the database with the
exact same information it already holds. it returns the correct # of
columns affected using ExecuteNonQuery().
Arnie Rowland wrote:
> You could do this in this manner
> USE Northwind
> GO
> IF NOT EXISTS
> ( SELECT (LastName)
> FROM Employees
> WHERE ( LastName = 'Fuller'
> AND FirstName = 'Andrea'
> )
> ) INSERT INTO Employees
> ( LastName
> , FirstName
> )
> VALUES
> ( 'Fuller'
> , 'Andrea'
> )
> Your application can check the RowCount (RowsAffected) to determine if mor
e 0 (zero) rows were inserted. Then message the user appropriately.
>
> --
> Arnie Rowland, YACE*
> "To be successful, your heart must accompany your knowledge."
> *Yet Another certification Exam
>
> "JLuv" <JLuv3k6@.gmail.com> wrote in message news:1151692692.332535.294860@.
75g2000cwc.googlegroups.com...|||You could also use the 'Primary Key' -it is by design a 'unique constraint'.
Arnie Rowland, YACE*
"To be successful, your heart must accompany your knowledge."
*Yet Another certification Exam
"JLuv" <JLuv3k6@.gmail.com> wrote in message
news:1151694549.094788.110810@.h44g2000cwa.googlegroups.com...
> i've never tried that before. is this method called a "unique
> constraint"? what should i search for to find information on this?
>
> Stu wrote:
>|||Not columns affected -BUT Rows Affected. Notice the use of IF NOT EXISTS.
That prevents adding a row that meets the WHERE clause criteria.
Arnie Rowland, YACE*
"To be successful, your heart must accompany your knowledge."
*Yet Another certification Exam
"JLuv" <JLuv3k6@.gmail.com> wrote in message
news:1151694709.234122.133440@.75g2000cwc.googlegroups.com...
>i did something like that. i went and updated the database with the
> exact same information it already holds. it returns the correct # of
> columns affected using ExecuteNonQuery().
>
> Arnie Rowland wrote:
>|||yea, i mean row, not column. and i'll try out IF NOT EXIST
Arnie Rowland wrote:
> Not columns affected -BUT Rows Affected. Notice the use of IF NOT EXISTS.
> That prevents adding a row that meets the WHERE clause criteria.
> --
> Arnie Rowland, YACE*
> "To be successful, your heart must accompany your knowledge."
> *Yet Another certification Exam
>
> "JLuv" <JLuv3k6@.gmail.com> wrote in message
> news:1151694709.234122.133440@.75g2000cwc.googlegroups.com...|||The only real reason to use this 'IF NOT EXISTS' form is if you wish to have
an ELSE -such as update an existing record.
Otherwise, just insert the data and let the unique constraint or Primary key
force an error and your application can capture the error and react
accordingly.
Arnie Rowland, YACE*
"To be successful, your heart must accompany your knowledge."
*Yet Another certification Exam
"JLuv" <JLuv3k6@.gmail.com> wrote in message
news:1151695591.304350.187130@.i40g2000cwc.googlegroups.com...
> yea, i mean row, not column. and i'll try out IF NOT EXIST
>
> Arnie Rowland wrote:
>

How to count distinct members and keep good performance

Hi all,

I have a simple cube with only one measure : "Amount", I have three dimensions Supplier, Category and Company.

I would like to display a matrix with Categories as rows, company as columns, the amount and the number of distinct suppliers who appaers for each category/company.

I tried to create a calculated measure like this:

Count(Crossjoin({[D Supplier].[Supplier Code].members}, {[Measures].[Amount]}), EXCLUDEEMPTY)

The result is OK, but when I add this calculated Measure to my query the execution time jumps from a few seconds (<10) to a few minutes. Am I missing something ?

Anyone have an idea to do this in a better way ?

On-the-fly distinct counting will be always slow. Any reason not to implement a distinct count on a separate measure group?|||

Indeed adding a separate measure group did the trick.

Thanks.

|||

Now I have another problem, for aggregating the Distinct Count, in the Cube browser it works properly, but in SSRS in a matrix it doesn't. As the query returns flat result, if I Sum the distinct count measure I have more suppliers than I should in the totals, the matrix just sum the values from the query.

How can I keep my Distinct Count working in a matrix ?

Is there any way to create the same measure but without the link to a particular dimension. What I have in mind is returning two columns for my distinctcount, one with the detailed count, one for the aggregated total by category. But I don't see how I can achieve this. Any idea ?

|||Create a calculated measure that includes the distinct count measure and the ALL member of all dimensions included in the query.|||Try using the Aggregate() function in the matrix instead of Sum() as exlained in more details here.|||Thanks a lot that solved my problem.

How to count distinct members and keep good performance

Hi all,

I have a simple cube with only one measure : "Amount", I have three dimensions Supplier, Category and Company.

I would like to display a matrix with Categories as rows, company as columns, the amount and the number of distinct suppliers who appaers for each category/company.

I tried to create a calculated measure like this:

Count(Crossjoin({[D Supplier].[Supplier Code].members}, {[Measures].[Amount]}), EXCLUDEEMPTY)

The result is OK, but when I add this calculated Measure to my query the execution time jumps from a few seconds (<10) to a few minutes. Am I missing something ?

Anyone have an idea to do this in a better way ?

On-the-fly distinct counting will be always slow. Any reason not to implement a distinct count on a separate measure group?|||

Indeed adding a separate measure group did the trick.

Thanks.

|||

Now I have another problem, for aggregating the Distinct Count, in the Cube browser it works properly, but in SSRS in a matrix it doesn't. As the query returns flat result, if I Sum the distinct count measure I have more suppliers than I should in the totals, the matrix just sum the values from the query.

How can I keep my Distinct Count working in a matrix ?

Is there any way to create the same measure but without the link to a particular dimension. What I have in mind is returning two columns for my distinctcount, one with the detailed count, one for the aggregated total by category. But I don't see how I can achieve this. Any idea ?

|||Create a calculated measure that includes the distinct count measure and the ALL member of all dimensions included in the query.|||Try using the Aggregate() function in the matrix instead of Sum() as exlained in more details here.|||Thanks a lot that solved my problem.

Friday, February 24, 2012

How to count distinct members and keep good performance

Hi all,

I have a simple cube with only one measure : "Amount", I have three dimensions Supplier, Category and Company.

I would like to display a matrix with Categories as rows, company as columns, the amount and the number of distinct suppliers who appaers for each category/company.

I tried to create a calculated measure like this:

Count(Crossjoin({[D Supplier].[Supplier Code].members}, {[Measures].[Amount]}), EXCLUDEEMPTY)

The result is OK, but when I add this calculated Measure to my query the execution time jumps from a few seconds (<10) to a few minutes. Am I missing something ?

Anyone have an idea to do this in a better way ?

Try

Count(NonEmptyCrossjoin({[D Supplier].[Supplier Code].members}, {[Measures].[Amount]})

|||Thanks for the answer, but I still have very long execution time when using this expression.|||How many cells are there in the query? If there are many cells, then the poor performance is likely due to the AS server using a slow cell-by-cell query execution plan. If you see a single CPU pegged during query execution on the AS server then it is an indication of running such a slow query plan. Improving performance for this kind of queries is one of the proposed work items for the next major release of the product.

How to count across multiple tables in a DB?

Thank you in advance for your assitance. I am trying to write a query that will query multiple tables for the same column. All the tables have thsi column "szF11". I am wanting something similar to this:

Code Snippet

SELECT count(ulID)

FROM (dbo.F_ACCOU_Data UNION dbo.F_AGNCY_Data UNION dbo.F_APPEA_Data UNION etc.....)

WHERE szF11 = ' '

Note: ulID is the name of a column that every table has and szF11 is also in every table.

Pseudo Code: I want to count how many ulID's (if there is a row then something is in the ulID column it is never blank) in all the tables that are listed that have a blank in the szF11 column.

I am getting a very cryptic error message and of course I can't find anything in the documentation to help me understand the error.

Thanks,

Erik

You have a few options.

You could do use a derived table:

Code Snippet

SELECT COUNT(uID)
FROM
(SELECT uID, szF11
FROM F_ACCOU_Data
UNION ALL
SELECT uID, szF11
FROM F_AGNCY_Data
UNON ALL
SELECT uID, szF11
FROM F_APPEA_Data
UNION
etc....) AS Tbl
WHERE sF11 = ''


A variation on this could be that you include the WHERE clause for each table within Tbl

Code Snippet

SELECT COUNT(uID)
FROM
(SELECT uID, szF11
FROM F_ACCOU_Data
WHERE sF11 = ''
UNION ALL
SELECT uID, szF11
FROM F_AGNCY_Data
WHERE sF11 = ''
etc...) AS Tbl


Another option would be to include the tablename in the derived table so you can find out how many rows per table

Code Snippet

SELECT TableName, COUNT(uID)
FROM
(SELECT uID, 'F_ACCOU_Data' AS TableName, sF11
FROM F_ACCOU_Data
UNION ALL
SELECT uID, 'F_AGNCY_Data', sF11
FROM F_AGNCY_Data
etc...
) AS tbl
WHERE sF11 = ''
GROUP BY TableName


HTH!

How to count a very large volume of request

Hello,
What is the best way to accomplish the following.
1) An ASP.NET program (consiting of one file somepage.aspx) receives about
25,000,000 requests pay day.
2) The requests come from a limited set of IP addresses.
3) How to count the total number of request from each IP address per day.
SQL Server 2000 is used on the backend.
Currently we used the following architecture:
* Each request to somepage.aspx generates an INSERT into a LogTable1
* There is a clustered index on the LogTable1 on the dateStamp field which
is of the type smalldatetime
* The dateStamp field has a default that sets it to the getdate()
* At the end of each day at 12:01AM there is a simple query that runs and
does a group by to count the number of requests from each IP in the given
date range (past 24 hours). This query works great and takes only 2 minutes
to run.
Is there a better way to accomplish this without having to do INSERTS into
the LogTable1 for each request?
It would not work to have the ASP.NET program execute an UPDATE each time to
increment the total number of request, since this would cause LOTSSS of
locking in the database layer.
Thanks in advance.
ArsenYou could store the data in your Application Cache, and update it
periodically to the database.
HTH,
Kevin Spencer
.Net Developer
Microsoft MVP
Big things are made up
of lots of little things.
"Arsen V." <arsen.NoSpamPlease@.emergency24.com> wrote in message
news:emdbHKo6DHA.2412@.TK2MSFTNGP09.phx.gbl...
quote:

> Hello,
> What is the best way to accomplish the following.
> 1) An ASP.NET program (consiting of one file somepage.aspx) receives about
> 25,000,000 requests pay day.
> 2) The requests come from a limited set of IP addresses.
> 3) How to count the total number of request from each IP address per day.
> SQL Server 2000 is used on the backend.
> Currently we used the following architecture:
> * Each request to somepage.aspx generates an INSERT into a LogTable1
> * There is a clustered index on the LogTable1 on the dateStamp field which
> is of the type smalldatetime
> * The dateStamp field has a default that sets it to the getdate()
> * At the end of each day at 12:01AM there is a simple query that runs and
> does a group by to count the number of requests from each IP in the given
> date range (past 24 hours). This query works great and takes only 2

minutes
quote:

> to run.
> Is there a better way to accomplish this without having to do INSERTS into
> the LogTable1 for each request?
> It would not work to have the ASP.NET program execute an UPDATE each time

to
quote:

> increment the total number of request, since this would cause LOTSSS of
> locking in the database layer.
> Thanks in advance.
> Arsen
>
|||Hi,
What about using the IIS log file?
you could set it in the way you need it, basically the client IP and maybe
the time, if you configure it to update daily all you have to do at 12:01
is run a process that read the file generated and do what you need.
Cheers,
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation
"Arsen V." <arsen.NoSpamPlease@.emergency24.com> wrote in message
news:emdbHKo6DHA.2412@.TK2MSFTNGP09.phx.gbl...
quote:

> Hello,
> What is the best way to accomplish the following.
> 1) An ASP.NET program (consiting of one file somepage.aspx) receives about
> 25,000,000 requests pay day.
> 2) The requests come from a limited set of IP addresses.
> 3) How to count the total number of request from each IP address per day.
> SQL Server 2000 is used on the backend.
> Currently we used the following architecture:
> * Each request to somepage.aspx generates an INSERT into a LogTable1
> * There is a clustered index on the LogTable1 on the dateStamp field which
> is of the type smalldatetime
> * The dateStamp field has a default that sets it to the getdate()
> * At the end of each day at 12:01AM there is a simple query that runs and
> does a group by to count the number of requests from each IP in the given
> date range (past 24 hours). This query works great and takes only 2

minutes
quote:

> to run.
> Is there a better way to accomplish this without having to do INSERTS into
> the LogTable1 for each request?
> It would not work to have the ASP.NET program execute an UPDATE each time

to
quote:

> increment the total number of request, since this would cause LOTSSS of
> locking in the database layer.
> Thanks in advance.
> Arsen
>
|||Hi Kevin,
Do you suggest storing the TOTALs in the Cache?
Or storing the actual requests: date and ip
Would there be a locking problem?
How to do the "periodic updates" to the database from the Cache?
Thanks,
Arsen
"Kevin Spencer" <kevin@.takempis.com> wrote in message
news:ezSYvso6DHA.1936@.TK2MSFTNGP12.phx.gbl...
quote:

> You could store the data in your Application Cache, and update it
> periodically to the database.
> --
> HTH,
> Kevin Spencer
> .Net Developer
> Microsoft MVP
> Big things are made up
> of lots of little things.
> "Arsen V." <arsen.NoSpamPlease@.emergency24.com> wrote in message
> news:emdbHKo6DHA.2412@.TK2MSFTNGP09.phx.gbl...
about[QUOTE]
day.[QUOTE]
which[QUOTE]
and[QUOTE]
given[QUOTE]
> minutes
into[QUOTE]
time[QUOTE]
> to
>
|||Hi Arsen,
You could put a DataTable in the Application Cache, and add records to it
with each Request. As for periodic updating, you could put a routine in the
Session_OnStart Sub that checks an Application DateTime variable, and at
certain intervals, inserts all the records from the DataTable into the
database and clears out the DataTable.
To be safe, you would want to add code to your Application_OnEnd sub to
update the database if the Application stops or times out; however, with 25M
requests per day, that might not be necessary.
HTH,
Kevin Spencer
.Net Developer
Microsoft MVP
Big things are made up
of lots of little things.
"Arsen V." <arsen.NoSpamPlease@.emergency24.com> wrote in message
news:#daQL6o6DHA.2908@.tk2msftngp13.phx.gbl...
quote:

> Hi Kevin,
> Do you suggest storing the TOTALs in the Cache?
> Or storing the actual requests: date and ip
> Would there be a locking problem?
> How to do the "periodic updates" to the database from the Cache?
> Thanks,
> Arsen
> "Kevin Spencer" <kevin@.takempis.com> wrote in message
> news:ezSYvso6DHA.1936@.TK2MSFTNGP12.phx.gbl...
> about
> day.
> which
> and
> given
> into
> time
of[QUOTE]
>
|||what i have done is cache the last 15 minutes. the cache has the ipaddress,
the start of the 15 min interval, pagename, and number of hits during the
interval. as most users cluster their hits, this cuts down the number of
inserts.
i flush the cache every 15 minutes of when too large.
you can then get daily or hourly stats from the db with simple queries.
-- bruce (sqlwork.com)
"Arsen V." <arsen.NoSpamPlease@.emergency24.com> wrote in message
news:emdbHKo6DHA.2412@.TK2MSFTNGP09.phx.gbl...
quote:

> Hello,
> What is the best way to accomplish the following.
> 1) An ASP.NET program (consiting of one file somepage.aspx) receives about
> 25,000,000 requests pay day.
> 2) The requests come from a limited set of IP addresses.
> 3) How to count the total number of request from each IP address per day.
> SQL Server 2000 is used on the backend.
> Currently we used the following architecture:
> * Each request to somepage.aspx generates an INSERT into a LogTable1
> * There is a clustered index on the LogTable1 on the dateStamp field which
> is of the type smalldatetime
> * The dateStamp field has a default that sets it to the getdate()
> * At the end of each day at 12:01AM there is a simple query that runs and
> does a group by to count the number of requests from each IP in the given
> date range (past 24 hours). This query works great and takes only 2

minutes
quote:

> to run.
> Is there a better way to accomplish this without having to do INSERTS into
> the LogTable1 for each request?
> It would not work to have the ASP.NET program execute an UPDATE each time

to
quote:

> increment the total number of request, since this would cause LOTSSS of
> locking in the database layer.
> Thanks in advance.
> Arsen
>