Showing posts with label rowcount. Show all posts
Showing posts with label rowcount. Show all posts

Wednesday, March 28, 2012

RowCount VS TOP

Is Set RowCount @.RowCount

More efficient than simply using TOP?

Thanks for any input.On 25 Jul 2005 11:00:01 -0700, wackyphill@.yahoo.com wrote:

>Is Set RowCount @.RowCount
>More efficient than simply using TOP?
>Thanks for any input.

Hi wackyphill,

Depends. They have different characteristics.

SET ROWCOUNT:
- takes a variable as well as a constant,
- affects ALL future queries, until another SET ROWCOUNT is executed,
- affects only the end result of the complete query.

TOP:
- takes only a constant,
- affects only the current query,
- may be used to limit the number of rows in a subquery.

If you want to limit output from all your queries to twenty rows for
testing and debugging purposes, SET ROWCOUNT is easily the best: just
issue the command once, then run all your queries without the need to
change. If you want to limit the output to a number determined at
runtime, SET ROWCOUNT wins as well - pop the value in a variable, then
run SET ROWCOUNT @.NewLimit.

On the other hand, if each query needs another limit, TOP is more
efficient since you'd otherwise have to run a SET ROWCOUNT between all
your queries. And if you're trying to find the salesmen that are NOT
amongst the 10 best sellers, SET ROWCOUNT can't be used at all, whereas
TOP can.

Best, Hugo
--

(Remove _NO_ and _SPAM_ to get my e-mail address)|||OK, that's interesting. So, given a single query, do they both have the
server run through all records and then return the first say 10 rows or
does one or both have a way of short circuiting the process after it
found 10 matches?

See, I know they both help w/ network traffic but I didn't know if one
had the server do more/less work.

Thanks for your help.|||On 25 Jul 2005 12:29:36 -0700, wackyphill@.yahoo.com wrote:

>OK, that's interesting. So, given a single query, do they both have the
>server run through all records and then return the first say 10 rows or
>does one or both have a way of short circuiting the process after it
>found 10 matches?
>See, I know they both help w/ network traffic but I didn't know if one
>had the server do more/less work.
>Thanks for your help.

Hi wackyphill,

My *guess* is that they'll be executed the same.

If you want to *know*, then run both (for your queries, using your
tables on your hardware - as these factors might all influence the
result), and compare execution plans.

Best, Hugo
--

(Remove _NO_ and _SPAM_ to get my e-mail address)|||(wackyphill@.yahoo.com) writes:
> OK, that's interesting. So, given a single query, do they both have the
> server run through all records and then return the first say 10 rows or
> does one or both have a way of short circuiting the process after it
> found 10 matches?

That's more likely to happen with TOP. But it depends on the query.
If you say:

SELECT TOP 20 * FROM tbl

SQL Server will only read the first 20 rows it finds, and that's that.

But if you say

SELECT TOP 20 * FROM tbl ORDER BY non_indexed_col

SQL Server will have to read the entire table, sort it, and pick the
first 20 rows according to the ORDER BY.

The same applies to SET ROWCOUNT, but I'm not really sure that SQL Server
looks at the actual value for SET ROWCOUNT, but makes some standard
assumption. This standard assumption can be a low number, though, in which
case you are likely to the same query plan as TOP.

I had a horror story once, where one component in our system produced
SET ROWCOUNT 7899808, yeah that's right an 7-digit number. (The
component was written in C++, using the ODBC API, and there was an
ODBC call that for some reason produced this.) This caused one
particular query in an essential stored procedure to get a different
query plan - and a bad one. And this happened just a few days before
an important customer were to go live.

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||OK, thanks very much guys. I guess there's no reason I should sweat the
difference then except for the behavioral differences mentioned above.
I just wanted to be sure.

Thanks again for your time.

RowCount using Group BY and Having

Hi,
I have a query that uses Group By and Having to retrieve records.
The query is working fine and I want to get the Row Count of that Query.
How will I do that.
Thanks
Kiran
"Kiran" <Kiran@.nospam.net> wrote in message
news:eIhHM6EAFHA.3908@.TK2MSFTNGP12.phx.gbl...
> Hi,
> I have a query that uses Group By and Having to retrieve records.
> The query is working fine and I want to get the Row Count of that Query.
> How will I do that.
> Thanks
> Kiran
>
SELECT ... Group By Query
SELECT @.@.ROWCOUNT
You could also save the rowcount into a variable like this:
DECLARE @.MyCount int
SELECT ... Group By Query
SELECT @.MyCount = @.@.RowCount
HTH
Rick Sawtell
MCT, MCSD, MCDBA

RowCount using Group BY and Having

Hi,
I have a query that uses Group By and Having to retrieve records.
The query is working fine and I want to get the Row Count of that Query.
How will I do that.
Thanks
Kiran"Kiran" <Kiran@.nospam.net> wrote in message
news:eIhHM6EAFHA.3908@.TK2MSFTNGP12.phx.gbl...
> Hi,
> I have a query that uses Group By and Having to retrieve records.
> The query is working fine and I want to get the Row Count of that Query.
> How will I do that.
> Thanks
> Kiran
>
SELECT ... Group By Query
SELECT @.@.ROWCOUNT
You could also save the rowcount into a variable like this:
DECLARE @.MyCount int
SELECT ... Group By Query
SELECT @.MyCount = @.@.RowCount
HTH
Rick Sawtell
MCT, MCSD, MCDBA

RowCount using Group BY and Having

Hi,
I have a query that uses Group By and Having to retrieve records.
The query is working fine and I want to get the Row Count of that Query.
How will I do that.
Thanks
Kiran"Kiran" <Kiran@.nospam.net> wrote in message
news:eIhHM6EAFHA.3908@.TK2MSFTNGP12.phx.gbl...
> Hi,
> I have a query that uses Group By and Having to retrieve records.
> The query is working fine and I want to get the Row Count of that Query.
> How will I do that.
> Thanks
> Kiran
>
SELECT ... Group By Query
SELECT @.@.ROWCOUNT
You could also save the rowcount into a variable like this:
DECLARE @.MyCount int
SELECT ... Group By Query
SELECT @.MyCount = @.@.RowCount
HTH
Rick Sawtell
MCT, MCSD, MCDBA

Rowcount reporting incorrectly...

Why when I double click my table, does the "Rows"
field show 10 records, but when I do a SELECT COUNT(id)
it show me the right amount?
SQL 2000 Enterprise, Windows 2003
I've run DBCC CHECKALLOC, UPDATEUSAGE, DBREPAIR, SHOWCONTIG,
INDEXDEFRAG...etc.
I've never heard of this before.EM caches alot of information. Did you try refreshing the data? Exit
and restart EM and see if the problem still appears.|||DBCC UPDATEUSAGE may improve the accuracy of this number, but it would have
to be executed each time you want to look at the number. Read up on
statistics; how they are used and when they are updated.
"isideveloper" <isideveloper@.newsgroups.nospam> wrote in message
news:uwKyfr4RGHA.776@.TK2MSFTNGP09.phx.gbl...
> Why when I double click my table, does the "Rows"
> field show 10 records, but when I do a SELECT COUNT(id)
> it show me the right amount?
> SQL 2000 Enterprise, Windows 2003
> I've run DBCC CHECKALLOC, UPDATEUSAGE, DBREPAIR, SHOWCONTIG,
> INDEXDEFRAG...etc.
> I've never heard of this before.
>|||... and it has to be executed using the COUNT_ROWS option (which mean it wi
ll take a longer
time...).
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
"JT" <someone@.microsoft.com> wrote in message news:e6vBNy4RGHA.5036@.TK2MSFTNGP12.phx.gbl...

> DBCC UPDATEUSAGE may improve the accuracy of this number, but it would hav
e to be executed each
> time you want to look at the number. Read up on statistics; how they are u
sed and when they are
> updated.
>
> "isideveloper" <isideveloper@.newsgroups.nospam> wrote in message
> news:uwKyfr4RGHA.776@.TK2MSFTNGP09.phx.gbl...
>sql

RowCount or Equivalent

I have a query that returns a set of rows - sorted by part#. On the report I can hide the duplicates (part#). How can I test the part# so that whenever a new part# starts I can reverse image the whole l line. I have not defined any groups. Is this a must?

Sorry I am not understanding your question.

RowCount does not exist, use CountRows instead, then What does 'reversing the image' means.

If you are after counting rows returned by some reports parameters, something along these lines should help.

=iif(CountRows("SM") <= 0,"Your query returned no result.",(iif(CountRows("SM") >= 64500,"Report is too large to open in Excel. Please use CSV Export then use another database like Access. " & "Number of rows returned: " & CountRows("SM") , "Number of rows returned: " & CountRows("SM") )))

Philippe

Monday, March 26, 2012

RowCount or Equivalent

I have a query that returns a set of rows - sorted by part#. On the report I can hide the duplicates (part#). How can I test the part# so that whenever a new part# starts I can reverse image the whole l line. I have not defined any groups. Is this a must?

Sorry I am not understanding your question.

RowCount does not exist, use CountRows instead, then What does 'reversing the image' means.

If you are after counting rows returned by some reports parameters, something along these lines should help.

=iif(CountRows("SM") <= 0,"Your query returned no result.",(iif(CountRows("SM") >= 64500,"Report is too large to open in Excel. Please use CSV Export then use another database like Access. " & "Number of rows returned: " & CountRows("SM") , "Number of rows returned: " & CountRows("SM") )))

Philippe

Rowcount on reports

Is there a way to display a rowcount for a report?
If so what does the function look like?
Thanks in advance,
JohnWhat about RowNumber() ?
Jens Suessmeyer.
"John K" <JohnK@.discussions.microsoft.com> schrieb im Newsbeitrag
news:D83E5AAB-FEED-4396-88BD-75E682236E76@.microsoft.com...
> Is there a way to display a rowcount for a report?
> If so what does the function look like?
> Thanks in advance,
> John|||Thanks for the quick reply Jens.
I have added a header textbox called Rows (label),
and onother with a function of =rownumber().
I am getting a compilation error of:
report1.rdl The value expression for the textbox â'RowsTextboxâ' has an
incorrect number of parameters for the function â'rownumberâ'.
If I change the function to =rownumber("Report1") I get this:
report1.rdl The value expression for the textbox â'RowsTextboxâ' uses the
function RowNumber. RowNumber cannot be used in page headers or footers.
How can I use rownumber()?
Thanks.
John
"Jens Sü�meyer" wrote:
> What about RowNumber() ?
> Jens Suessmeyer.
> "John K" <JohnK@.discussions.microsoft.com> schrieb im Newsbeitrag
> news:D83E5AAB-FEED-4396-88BD-75E682236E76@.microsoft.com...
> > Is there a way to display a rowcount for a report?
> > If so what does the function look like?
> >
> > Thanks in advance,
> > John
>
>|||You can use =RowNumber(Nothing)
or =RowNumber("<name of report dataset>")
Look in Books Online for more information, as the function can be used with
a group name parameter and a data region name also instead of name of report
dataset. Note that the argument is case sensitive.
Charles Kangai, MCDBA, MCT
"John K" wrote:
> Thanks for the quick reply Jens.
> I have added a header textbox called Rows (label),
> and onother with a function of =rownumber().
> I am getting a compilation error of:
> report1.rdl The value expression for the textbox â'RowsTextboxâ' has an
> incorrect number of parameters for the function â'rownumberâ'.
> If I change the function to =rownumber("Report1") I get this:
> report1.rdl The value expression for the textbox â'RowsTextboxâ' uses the
> function RowNumber. RowNumber cannot be used in page headers or footers.
> How can I use rownumber()?
>
> Thanks.
> John
>
> "Jens Sü�meyer" wrote:
> > What about RowNumber() ?
> >
> > Jens Suessmeyer.
> >
> > "John K" <JohnK@.discussions.microsoft.com> schrieb im Newsbeitrag
> > news:D83E5AAB-FEED-4396-88BD-75E682236E76@.microsoft.com...
> > > Is there a way to display a rowcount for a report?
> > > If so what does the function look like?
> > >
> > > Thanks in advance,
> > > John
> >
> >
> >|||The is Rownumber, but you have to count something with it, perhaps Nothing,
so the whole expression would be =Rownumber(Nothing).
Try this.
HTH, Jens Suessmeyer.
--
http://www.sqlserver2005.de
--
"John K" <JohnK@.discussions.microsoft.com> schrieb im Newsbeitrag
news:085867DD-4240-43DA-A5E8-9A16BEB14F45@.microsoft.com...
> Thanks for the quick reply Jens.
> I have added a header textbox called Rows (label),
> and onother with a function of =rownumber().
> I am getting a compilation error of:
> report1.rdl The value expression for the textbox 'RowsTextbox' has an
> incorrect number of parameters for the function 'rownumber'.
> If I change the function to =rownumber("Report1") I get this:
> report1.rdl The value expression for the textbox 'RowsTextbox' uses the
> function RowNumber. RowNumber cannot be used in page headers or footers.
> How can I use rownumber()?
>
> Thanks.
> John
>
> "Jens Süßmeyer" wrote:
>> What about RowNumber() ?
>> Jens Suessmeyer.
>> "John K" <JohnK@.discussions.microsoft.com> schrieb im Newsbeitrag
>> news:D83E5AAB-FEED-4396-88BD-75E682236E76@.microsoft.com...
>> > Is there a way to display a rowcount for a report?
>> > If so what does the function look like?
>> >
>> > Thanks in advance,
>> > John
>>|||Thanks Jens,
Got it to work.
"Jens Sü�meyer" wrote:
> The is Rownumber, but you have to count something with it, perhaps Nothing,
> so the whole expression would be =Rownumber(Nothing).
> Try this.
> HTH, Jens Suessmeyer.
> --
> http://www.sqlserver2005.de
> --
> "John K" <JohnK@.discussions.microsoft.com> schrieb im Newsbeitrag
> news:085867DD-4240-43DA-A5E8-9A16BEB14F45@.microsoft.com...
> > Thanks for the quick reply Jens.
> >
> > I have added a header textbox called Rows (label),
> > and onother with a function of =rownumber().
> >
> > I am getting a compilation error of:
> >
> > report1.rdl The value expression for the textbox 'RowsTextbox' has an
> > incorrect number of parameters for the function 'rownumber'.
> >
> > If I change the function to =rownumber("Report1") I get this:
> >
> > report1.rdl The value expression for the textbox 'RowsTextbox' uses the
> > function RowNumber. RowNumber cannot be used in page headers or footers.
> >
> > How can I use rownumber()?
> >
> >
> > Thanks.
> > John
> >
> >
> > "Jens Sü�meyer" wrote:
> >
> >> What about RowNumber() ?
> >>
> >> Jens Suessmeyer.
> >>
> >> "John K" <JohnK@.discussions.microsoft.com> schrieb im Newsbeitrag
> >> news:D83E5AAB-FEED-4396-88BD-75E682236E76@.microsoft.com...
> >> > Is there a way to display a rowcount for a report?
> >> > If so what does the function look like?
> >> >
> >> > Thanks in advance,
> >> > John
> >>
> >>
> >>
>
>|||Thanks Charles,
Got it to work.
--
"Charles Kangai" wrote:
> You can use =RowNumber(Nothing)
> or =RowNumber("<name of report dataset>")
> Look in Books Online for more information, as the function can be used with
> a group name parameter and a data region name also instead of name of report
> dataset. Note that the argument is case sensitive.
> Charles Kangai, MCDBA, MCT
> "John K" wrote:
> > Thanks for the quick reply Jens.
> >
> > I have added a header textbox called Rows (label),
> > and onother with a function of =rownumber().
> >
> > I am getting a compilation error of:
> >
> > report1.rdl The value expression for the textbox â'RowsTextboxâ' has an
> > incorrect number of parameters for the function â'rownumberâ'.
> >
> > If I change the function to =rownumber("Report1") I get this:
> >
> > report1.rdl The value expression for the textbox â'RowsTextboxâ' uses the
> > function RowNumber. RowNumber cannot be used in page headers or footers.
> >
> > How can I use rownumber()?
> >
> >
> > Thanks.
> > John
> >
> >
> > "Jens Sü�meyer" wrote:
> >
> > > What about RowNumber() ?
> > >
> > > Jens Suessmeyer.
> > >
> > > "John K" <JohnK@.discussions.microsoft.com> schrieb im Newsbeitrag
> > > news:D83E5AAB-FEED-4396-88BD-75E682236E76@.microsoft.com...
> > > > Is there a way to display a rowcount for a report?
> > > > If so what does the function look like?
> > > >
> > > > Thanks in advance,
> > > > John
> > >
> > >
> > >

RowCount is returning null

i have 2 stored procedures: a delete and a select. the delete sp returns the rowcount properly. the select returns null. the code for both sp's is extremely simple and extremely similar. when i execute the select sp in server management studio the rowcount shows a 1 as expected. but the calling method gets null.

SP Code

ALTER

PROCEDURE [dbo].[RetrieveEmployeeKeyFromAssignmentTable]

@.assignmentPrimaryKey

int,

@.rowCount

intOUTPUT

AS

BEGIN

SETNOCOUNTON;SELECT employeePrimaryKeyFROM assignmentTableWHERE primaryKey= @.assignmentPrimaryKey;SET @.rowCount=@.@.RowCount;

END

c# code

SqlConnection

conn = GetOpenSqlConnection();if (conn ==null) returntrue;SqlDataReader reader =null;SqlParameter p1 =newSqlParameter(); SqlParameter p2 =newSqlParameter();try{SqlCommand command =newSqlCommand();

command.CommandText =

"RetrieveEmployeeKeyFromAssignmentTable";

command.CommandType =

CommandType.StoredProcedure;

command.Connection = conn;

p1.ParameterName =

"@.assignmentPrimaryKey";

p1.Value = assignmentPrimaryKey;

p2.ParameterName =

"@.rowCount";

p2.Direction =

ParameterDirection.Output;

p2.Value = 0;

command.Parameters.Add(p1); command.Parameters.Add(p2);

reader = command.ExecuteReader();

if (p2.Value ==null)//always true

any suggestions would be appreciated.

thanks. matt

also, reader.HasRows is true.

matt

|||

Hello,

first, I was suspicious of your code that you assigned the value of output parameter p2.value=0.

but it was O.K., and I was wrong , I tested with query analyzer.

I looked carefully in your code, find that you called with ExecuteReader ==> it is connected data object.

you have to close the Reader object before you try to get Output or else paremeter values.

verified with internet search...

|||

EXCELLENT.

thank you very much.

matt

Rowcount in tables

Can someone throw light on how to get the rowcount of a table that is stored in any system tables? I want to get tablename and rowcount for all user tables in a database in a query. Is there anyway other than count(*)?
Thanks
VinnieDBCC UPDATEUSAGE (0) WITH COUNT_ROWS (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/tsqlref/ts_dbcc_24rp.asp)

SELECT rows, Object_name(id)
FROM dbo.sysindexes
WHERE indid IN (0, 1)If you skip the DBCC, you'll get a SWAG guess, but none too accurate in a busy server.

-PatP|||sysindexes has a rowcount, see BOL for more details on this.

EDIT: sniped again!|||Thanks guys.|||Check for sp_spaceused. It may help you.|||Here's my little addtion to the pile: (built on MSSQL2k)

DECLARE @.MinSize dec(28,2), @.LikeName varchar(45), @.SizeSort bit, @.IncludeLogs bit
--DBCC UPDATEUSAGE(0) WITH COUNT_ROWS

SET @.MinSize = .00
SET @.LikeName = '' --Company%'
SET @.SizeSort = 1
SET @.IncludeLogs = 0

/*
** We need to create a temp table to do the calculation.
** reserved: sum(reserved) where indid in (0, 1, 255)
** data: sum(dpages) where indid < 2 + sum(used) where indid = 255 (text)

** indexp: sum(used) where indid in (0, 1, 255) - data
** unused: sum(reserved) - sum(used) where indid in (0, 1, 255)
*/
IF @.LikeName = '' SET @.LikeName = '%'

CREATE TABLE #space
(
name varchar(30),
id int,
type char(1),
rows int NULL,
reserved dec(28,2) NULL,
data dec(28,2) NULL,
datapages dec(28,2) NULL,
blob dec(28,2) NULL,
indexp dec(28,2) NULL,
unused dec(28,2) NULL,
rowsize dec(28,2) NULL
)

SET NOCOUNT ON

/************************************************** ***********
** Generate a list of all User and System tables.
** AND
** Now calculate the summary data.
** reserved: sum(reserved) where indid in (0, 1, 255)
*/
INSERT INTO #space (name, id, type, reserved)
SELECT LEFT(obj.name,30), obj.id, obj.type, SUM(reserved)
FROM sysindexes idx, sysobjects obj
WHERE idx.id = obj.id
AND idx.indid IN (0, 1, 255)
AND obj.type in ('S','U')
AND obj.name != 'syslogs'
AND obj.name LIKE @.LikeName
AND (@.IncludeLogs = 1 OR obj.name NOT LIKE '%Log')
GROUP BY obj.name, obj.id, obj.type

/************************************************** ***********
** Initialize these to zero.
*/
UPDATE #space
SET rows = 0, data = 0, blob = 0, indexp = 0, unused = 0

/************************************************** ***********
** data: sum(dpages) where indid < 2
** + sum(used) where indid = 255 (text)
*/
UPDATE #space
SET data = data + ISNULL((
SELECT SUM(idx.dpages)
FROM sysindexes idx
WHERE id = spc.id
AND idx.indid < 2), 0)
FROM #space spc

UPDATE #space
SET blob = blob + ISNULL((
SELECT SUM(idx.used)
FROM sysindexes idx
WHERE id = spc.id
AND idx.indid = 255), 0)
FROM #space spc

/************************************************** ***********
** index: sum(used) where indid in (0, 1, 255) - data space
*/
UPDATE #space
SET indexp = ISNULL((
SELECT SUM(idx.used)
FROM sysindexes idx
WHERE id = spc.id
AND idx.indid IN (0, 1, 255)), 0) - data - blob
FROM #space spc

/************************************************** ***********
** unused: sum(reserved) - sum(used) where indid in (0, 1, 255)
*/
UPDATE #space
SET unused = reserved - ISNULL((
SELECT SUM(idx.used)
FROM sysindexes idx
WHERE id = spc.id
AND idx.indid IN (0, 1, 255)), 0)
FROM #space spc

/************************************************** ***********
** rows: rows where indid < 2
*/
UPDATE #space
SET rows = idx.rows
FROM #space spc, sysindexes idx
WHERE spc.id = idx.id
AND idx.indid < 2

/************************************************** ***********
** Page Size: for Windows NT
*/
DECLARE @.PageSize int, @.UsablePage int
SELECT @.PageSize = low
FROM master.dbo.spt_values
WHERE number = 1 AND type = 'E'

set @.UsablePage = @.PageSize - 132

/************************************************** ***********
** Compute the results
*/
UPDATE #space SET
reserved = reserved * @.PageSize,
datapages = data,
data = data * @.PageSize,
blob = blob * @.PageSize,
indexp = indexp * @.PageSize,
unused = unused * @.PageSize

UPDATE #space SET
rowsize =
CASE
WHEN rows < 50 THEN -1
ELSE ((data) / rows)
END

UPDATE #space SET
reserved = reserved / 1024.0 / 1024.0,
data = data / 1024.0 / 1024.0,
blob = blob / 1024.0 / 1024.0,
indexp = indexp / 1024.0 / 1024.0,
unused = unused / 1024.0 / 1024.0

/************************************************** ***********
** Finally: output the report header

*/

PRINT GETDATE()
PRINT ''

IF @.MinSize != 0
PRINT 'Tables with a Total space used of ' + LTRIM(STR(@.MinSize, 8,1)) + ' MB or greater in the ' + DB_NAME() + ' database.'
ELSE
PRINT 'All tables in the ' + DB_NAME() + ' database.'

PRINT ''

/************************************************** ***********
** Finally: output the totals
*/

DECLARE @.DataTotal dec(28,2), @.BlobTotal dec(28,2), @.IndexTotal dec(28,2), @.Format varchar(15)

SELECT @.DataTotal = SUM(data),
@.BlobTotal = SUM(blob),
@.IndexTotal = SUM(indexp)
FROM #space

SET @.Format = CONVERT(varchar(15),convert(money,@.DataTotal+@.Blob Total+@.IndexTotal),1)
PRINT 'Space used : ' + REPLICATE(' ',15-DATALENGTH(@.Format)) + @.Format + ' MB'
SET @.Format = CONVERT(varchar(15),convert(money,@.DataTotal),1)
PRINT 'Space used by table data : ' + REPLICATE(' ',15-DATALENGTH(@.Format)) + @.Format + ' MB'
SET @.Format = CONVERT(varchar(15),convert(money,@.BlobTotal),1)
PRINT 'Space used by text/image data : ' + REPLICATE(' ',15-DATALENGTH(@.Format)) + @.Format + ' MB'
SET @.Format = CONVERT(varchar(15),convert(money,@.IndexTotal),1)
PRINT 'Space used by table indexes : ' + REPLICATE(' ',15-DATALENGTH(@.Format)) + @.Format + ' MB'
SET @.Format = CONVERT(varchar(15),@.PageSize)
PRINT 'Page size : ' + REPLICATE(' ',15-DATALENGTH(@.Format)) + @.Format + ' Bytes'
SET @.Format = CONVERT(varchar(15),@.UsablePage)
PRINT 'Usable Page size : ' + REPLICATE(' ',15-DATALENGTH(@.Format)) + @.Format + ' Bytes'
PRINT ''

/************************************************** ***********

** Finally: output the detail
*/

update #space
set rowsize = CASE
WHEN rowsize < 0 THEN 0
WHEN (data) < .1 THEN 0
ELSE rowsize
END

SELECT
TableName = name,
Rows = convert(varchar(11),CONVERT(varchar(15),convert(mo ney,rows),1)),
Total = convert(varchar(11),CONVERT(varchar(15),convert(mo ney,data+blob+indexp),1)),
Data = convert(varchar(11),CONVERT(varchar(15),convert(mo ney,data),1)),
Blob = convert(varchar(11),CONVERT(varchar(15),convert(mo ney,blob),1)),
Indexes = convert(varchar(11),CONVERT(varchar(15),convert(mo ney,indexp),1)),
RowBytes = convert(varchar(11),
CASE
WHEN rowsize = 0 THEN 'n/a'
ELSE CONVERT(varchar(15),convert(money,rowsize),1)
END),
RowsPage = convert(varchar(11),
CASE
WHEN rows = 0 THEN 'n/a'
ELSE CONVERT(varchar(15),convert(money,rows/datapages),1)
END),
Pages = convert(varchar(11),CONVERT(varchar(15),convert(mo ney,datapages),1)),
TotalSize = data+indexp+blob
INTO #report
FROM #space
WHERE data+indexp >= @.MinSize AND type = 'U' and name != 'dtproperties'

UPDATE #report
SET Rows = REPLACE(REPLACE(Rows,'.00',''),'.0',''),
Pages = REPLACE(REPLACE(Pages,'.00',''),'.0','')

UPDATE #report
SET Rows = REPLICATE(' ',11-DATALENGTH(Rows)) + Rows,
Total = REPLICATE(' ',11-DATALENGTH(Total)) + Total,
Data = REPLICATE(' ',11-DATALENGTH(Data)) + Data,
Blob = REPLICATE(' ',11-DATALENGTH(Blob)) + Blob,
Indexes = REPLICATE(' ',11-DATALENGTH(Indexes)) + Indexes,
RowsPage = REPLICATE(' ',11-DATALENGTH(RowsPage)) + RowsPage,
Pages = REPLICATE(' ',11-DATALENGTH(Pages)) + Pages,
RowBytes = REPLICATE(' ',11-DATALENGTH(RowBytes)) + RowBytes

PRINT ' --- Average --- ----- Table Space In MB -----'

IF @.SizeSort = 1
SELECT
TableName,
' Row Size' = RowBytes,
' Rows/Page' = RowsPage,
' Data Pages' = Pages,
' Rows' = Rows,
' Total' = Total,
' Data' = Data,
' Text/Img' = Blob,
' Index' = Indexes
FROM #report
ORDER BY TotalSize DESC
ELSE
SELECT
TableName,
' Row Size' = RowBytes,
' Rows/Page' = RowsPage,
' Data Pages' = Pages,
' Rows' = Rows,
' Total' = Total,
' Data' = Data,
' Text/Img' = Blob,
' Index' = Indexes
FROM #report
ORDER BY TableName

PRINT ''

DROP TABLE #space
DROP TABLE #report|||Here's my little addtion to the pile: (built on MSSQL2k)Great zot there, bubba! I'd consider that a pile all its own, not an addition to an existing pile! Whew, I can't wait to see a major contribution!

-PatP|||I got the following errors when I ran this in Query Analyzer:

Server: Msg 137, Level 15, State 2, Line 172
Must declare the variable '@.Blob'.
Server: Msg 170, Level 15, State 1, Line 201
Line 201: Incorrect syntax near 'ney'.|||i think you might have a simple wrapping issue...@.blob isnt a variable in this script but @.blobtotal is.

testing it...that is exactly what happened...

any tips on posting this without having the format chang on me?|||try the attachment...

for some reason pasting it FROM this forum adds some freaky yeaky spaces.

they dont appear as spaces in the forum window, but they sure as hell get added if you copy/paste it out of here...

...sorry...forum noooob issue.|||Cool that worked. Check this script out that I've been using.sql

rowcount in ''select into''

Is there a way to insert the rowcount in a 'select into' clause? Example:

select @.@.rowcount as id,* into mytable_with_rowcount from mytable

If mytable has 100 records then I want an id column in 'mytable_with_rowcount' and have the id column numbered 1 - 100. I know this can be done in a loop, but can it be done in the select w/out doing a loop?

Thanks,

Phil

if its sql server 2005 you can use Ranking Function to number the row and then insert to table. Read about Ranking Functions in BOL.

If its 2000, then you can create a table with ID as indentity column and then insert the rows to that table.

http://www.sqljunkies.com/Article/4E65FA2D-F1FE-4C29-BF4F-543AB384AFBB.scuk

http://www.sql-server-performance.com/ak_ranking_functions.asp

Madhu

|||Very nice. Thanks.

rowcount in header not printing

I have figured out that you really can't place a function like
CountRows directly in a report header. So I tried creating a textbox in
the header that points to a textbox in the body that does the
calculation. There expression for this new textbox looks like the
following:
ReportItems!tbRowCount.value
Since I don't want to display two row counts in a report... I have set
the textbox in the page body to Hidden = True.
Interestingly... the following is what happens:
- In VS.NET preview: header row count renders on the first page, but
none of the others.
- In IE 6: header row count renders on all pages like I was hoping.
Yay!
- When printing from IE 6: header row count renders on the first page,
but none of the others.
What matters the most to me is that the row count shows up in on all
pages in both IE and IE printing. BTW... I tried moving the calculation
into the body and setting its repeat with to the correct dataset. This
resulted in similar behavior: print 1st page... then not again for the
rest.
So has anyone figured this out? BTW I'm using RS 2003 and not the new
version.Hi Scott,
How did you link the TextBox in the header with the one in the body?
Bryan
"scott.d" wrote:
> I have figured out that you really can't place a function like
> CountRows directly in a report header. So I tried creating a textbox in
> the header that points to a textbox in the body that does the
> calculation. There expression for this new textbox looks like the
> following:
> ReportItems!tbRowCount.value
> Since I don't want to display two row counts in a report... I have set
> the textbox in the page body to Hidden = True.
> Interestingly... the following is what happens:
> - In VS.NET preview: header row count renders on the first page, but
> none of the others.
> - In IE 6: header row count renders on all pages like I was hoping.
> Yay!
> - When printing from IE 6: header row count renders on the first page,
> but none of the others.
> What matters the most to me is that the row count shows up in on all
> pages in both IE and IE printing. BTW... I tried moving the calculation
> into the body and setting its repeat with to the correct dataset. This
> resulted in similar behavior: print 1st page... then not again for the
> rest.
> So has anyone figured this out? BTW I'm using RS 2003 and not the new
> version.
>

rowcount help

i'm trying to get total rows found by query that uses top clause...
for example:
select top 10 myTable.* from myTable where myTable.number > 200
let's say there are 13 rows matching that condition, and by using
@.@.rowcount my result would be: 10.
is there any way to get total row count, without affecting the TOP
clause? i believe that the mysql equivalent would be
SQL_CALC_FOUND_ROWS().
tnx...> is there any way to get total row count, without affecting the TOP
> clause?
One method is with a subquery:
SELECT TOP 10
myTable.*,
(SELECT COUNT(*)
FROM myTable
WHERE myTable.number > 200) AS TotalRows
FROM myTable
WHERE myTable.number > 200
Hope this helps.
Dan Guzman
SQL Server MVP
"D.B." <dejan.bukovic@.gmail.com> wrote in message
news:1148128944.554703.296710@.38g2000cwa.googlegroups.com...
> i'm trying to get total rows found by query that uses top clause...
> for example:
> select top 10 myTable.* from myTable where myTable.number > 200
>
> let's say there are 13 rows matching that condition, and by using
> @.@.rowcount my result would be: 10.
>
> is there any way to get total row count, without affecting the TOP
> clause? i believe that the mysql equivalent would be
> SQL_CALC_FOUND_ROWS().
>
> tnx...
>|||well, it helped...
but i'm worried about the execution time when using full-text search...
anyway, thanx for your help...|||You could select the entire set into a temp table or table variable.
Then, get the count of the temp table, then select the number you want.
e.g.
declare @.tAllRows as table(...)
insert into @.tAllRows
select ... from myTable where myTable.number>200
declare @.iTotalCount int
set @.iTotalCount = @.@.rowcount
select top 10 myTable.*, @.@.rowcount from @.tAllRows
While I usually try to avoid temp tables and table variables,
_sometimes_ they help a lot with performance. Benchmarking would be a
good idea, though, as my approach could be a disaster.
Also, are you paging based on an identity field? If so, you might not
get the results you expect when the numbers are not continuous.|||err...
select top 10 myTable.*, @.iTotalCount from @.tAllRows
my bad...

rowcount help

i'm trying to get total rows found by query that uses top clause...
for example:
select top 10 myTable.* from myTable where myTable.number > 200
let's say there are 13 rows matching that condition, and by using
@.@.rowcount my result would be: 10.
is there any way to get total row count, without affecting the TOP
clause? i believe that the mysql equivalent would be
SQL_CALC_FOUND_ROWS().
tnx...> is there any way to get total row count, without affecting the TOP
> clause?
One method is with a subquery:
SELECT TOP 10
myTable.*,
(SELECT COUNT(*)
FROM myTable
WHERE myTable.number > 200) AS TotalRows
FROM myTable
WHERE myTable.number > 200
--
Hope this helps.
Dan Guzman
SQL Server MVP
"D.B." <dejan.bukovic@.gmail.com> wrote in message
news:1148128944.554703.296710@.38g2000cwa.googlegroups.com...
> i'm trying to get total rows found by query that uses top clause...
> for example:
> select top 10 myTable.* from myTable where myTable.number > 200
>
> let's say there are 13 rows matching that condition, and by using
> @.@.rowcount my result would be: 10.
>
> is there any way to get total row count, without affecting the TOP
> clause? i believe that the mysql equivalent would be
> SQL_CALC_FOUND_ROWS().
>
> tnx...
>|||well, it helped...
but i'm worried about the execution time when using full-text search...
anyway, thanx for your help...|||You could select the entire set into a temp table or table variable.
Then, get the count of the temp table, then select the number you want.
e.g.
declare @.tAllRows as table(...)
insert into @.tAllRows
select ... from myTable where myTable.number>200
declare @.iTotalCount int
set @.iTotalCount = @.@.rowcount
select top 10 myTable.*, @.@.rowcount from @.tAllRows
While I usually try to avoid temp tables and table variables,
_sometimes_ they help a lot with performance. Benchmarking would be a
good idea, though, as my approach could be a disaster.
Also, are you paging based on an identity field? If so, you might not
get the results you expect when the numbers are not continuous.|||err...
select top 10 myTable.*, @.iTotalCount from @.tAllRows
my bad...

rowcount help

i'm trying to get total rows found by query that uses top clause...

for example:
select top 10 myTable.* from myTable where myTable.number > 200

let's say there are 13 rows matching that condition, and by using
@.@.rowcount my result would be: 10.

is there any way to get total row count, without affecting the TOP
clause? i believe that the mysql equivalent would be
SQL_CALC_FOUND_ROWS().

tnx...I answered this question in microsoft.public.sqlserver.server.

It's bad etiquette to post the same question independently to multiple
groups because that causes unnecessary duplication of effort by persons
trying to help. If you have a question appropriate for multiple groups,
specify all groups in a single post so that all responses appear in all
groups.

--
Hope this helps.

Dan Guzman
SQL Server MVP

"D.B." <dejan.bukovic@.gmail.com> wrote in message
news:1148128056.678229.59640@.i39g2000cwa.googlegro ups.com...
> i'm trying to get total rows found by query that uses top clause...
> for example:
> select top 10 myTable.* from myTable where myTable.number > 200
>
> let's say there are 13 rows matching that condition, and by using
> @.@.rowcount my result would be: 10.
>
> is there any way to get total row count, without affecting the TOP
> clause? i believe that the mysql equivalent would be
> SQL_CALC_FOUND_ROWS().
>
> tnx...sql

rowcount from a bulk insert task in SSIS

I would like to get the rowcount from a bulk insert task to validate that all the data is being inserted correctly. So far the only way that I can see this being done is through a trigger on the target tables. I would like to have this information inside the DTS package. Can anyone help me?

Thanks

How about using two Exec SQL Tasks with SELECT COUN(*) FROM MyTable, to get the before and after counts. Depends on if you expect other people to be adding records around the same time, but then that would be an issue with triggers possibly. Not much of a bulk insert of you have triggers firing as you have to reduce the "load speed" to get them to fire.|||

DarrenSQLIS wrote:

How about using two Exec SQL Tasks with SELECT COUN(*) FROM MyTable, to get the before and after counts. Depends on if you expect other people to be adding records around the same time, but then that would be an issue with triggers possibly. Not much of a bulk insert of you have triggers firing as you have to reduce the "load speed" to get them to fire.

This is exactly how Joy Mundy proposed to do auditing in her " Ralph Kimball Group SSIS webcast" presentation listed on the front page of this thread. Finish your inserts and then in a separate task grab your counts.

Rowcount and SQLDataReader

Hi, from what I can find, there isn't a way to get the number of rows returned from a SQLDataReader command. Is this correct? If so, is there a way around this? My SQLDataReader command is as follows:

Dim commandIndAsNew System.Data.OleDb.OleDbDataAdapter(strQueryCombined, connInd)

Dim commandSQLAsNew SqlCommand("GetAssetList2", connStringSQL)

Dim resultDSAsNew Data.DataSet()

'// Fill the dataset with values

commandInd.Fill(resultDS)

'// Get the XML values of the dataset to send to SQL server and run a new query

Dim strXMLAsString = resultDS.GetXml()

Dim xmlFileListAs SqlParameter

Dim strContainsClauseAs SqlParameter

'// Create and execute the search against SQL Server

connStringSQL.Open()

commandSQL.CommandType = Data.CommandType.StoredProcedure

commandSQL.Parameters.Add("@.xmlFileList", Data.SqlDbType.VarChar, 1000).Value = strXML

commandSQL.Parameters.Add("@.strContainsClause", Data.SqlDbType.VarChar, 1000).Value = strContainsConstruct

Dim sqlReaderSourceAs SqlDataReader = commandSQL.ExecuteReader()

results.DataSource = sqlReaderSource

results.DataBind()

connStringSQL.Close()

And the stored procedure is such:

DROPPROC dbo.GetAssetList2;

GO

CREATEPROC dbo.GetAssetList2

(

@.xmlFileListvarchar(1000),

@.strContainsClausevarchar(1000)

)

AS

BEGIN

SETNOCOUNTON

DECLARE @.intDocHandleint

EXECsp_xml_preparedocument @.intDocHandleOUTPUT, @.xmlFileList

SELECTDISTINCT

AssetsMaster.AssetMasterUID,

SupportedFiles.AssetPath,

FROM

AssetsMaster,

OPENXML(@.intDocHandle,'/NewDataSet/Table',2)WITH(FILENAMEvarchar(256))AS x,

SupportedFiles

WHERE

AssetsMaster.AssetFileName= x.FILENAME

AND AssetsMaster.Extension= SupportedFiles.Extension

UNION

SELECTDISTINCT

AssetsMaster.AssetMasterUID,

SupportedFiles.AssetPath,

FROM

AssetsMaster,

OPENXML(@.intDocHandle,'/NewDataSet/Table',2)WITH(FILENAMEvarchar(256))AS x,

SupportedFiles

WHERE

AssetsMaster.AssetFileName<> x.FILENAME

ANDCONTAINS((Description, Keywords), @.strContainsClause)

AND AssetsMaster.Extension= SupportedFiles.Extension

ORDERBY AssetsMaster.DownloadsDESC

EXECsp_xml_removedocument @.intDocHandle

END

GO

How can I access the number of rows returned by this stored procedure?

Thanks,

James

I would suggest changing your datareader into a dataset. Then you can bind to the dataset, and also check how many rows are in it.|||

Thanks Motley. What is wrong with this? I am calling a stored SELECT procedure. It says there is a syntax error.

Dim connStringSQLAsNew SqlConnection("Data Source=*;Database=*;User ID=*;Password=*;Trusted_Connection=*")

'// Create the new OLEDB connection to Indexing Service

Dim commandSQLAsNew SqlCommand("GetAssetList2", connStringSQL)

Dim resultDSAsNew Data.DataSet()

Dim resultDAAsNew SqlDataAdapter()

'// Fill the dataset with values from the previous query

commandInd.Fill(resultDS)

'// Get the XML values of the dataset to send to SQL server and run a new query

Dim strXMLAsString = resultDS.GetXml()

Dim xmlFileListAs SqlParameter

Dim strContainsClauseAs SqlParameter

'// Create and execute the search against SQL Server

commandSQL.Parameters.Add("@.xmlFileList", Data.SqlDbType.VarChar, 1000).Value = strXML

commandSQL.Parameters.Add("@.strContainsClause", Data.SqlDbType.VarChar, 1000).Value = strContainsConstruct

resultDA.SelectCommand = commandSQL

resultDA.Fill(resultDS)

Dim sourceAsNew Data.DataView(resultDS.Tables(0))

resultCount.Text = source.Count.ToString

results.DataSource = source

results.DataBind()

|||

Never mind, I got it by added

commandSQL.CommandType = Data.CommandType.StoredProcedure

But now I get one extra row returned per query. It's empty. Any ideas?

rowcount

Hi,

I am using ssis to import .csv files into sql server tables.
How do I get the count of the records imported?
Thanks

SOLVED by using a rowcount component.

|||

Use the RowCount transform.

I dont know what you need, but look around to eventhandlers and global variables.

regards

RowCount

Hi,

want to get the number of rows i'm retrieving from a source. This count should be written as " No: of roes retrieved" + varname

I have used OleDbSource, RowCount,Script [ To write in a file ]. Rows is the package level variable name used in rowcount. when i do this way it always writes as 0 in the file.

[code in Script]

Dim sw As New StreamWriter("D:\Vijay1.txt")

s = Variables.Rows

sw.WriteLine(s.ToString)

sw.close

[/Code]

Can anyone help on this

you should store the row count in an ssis variable, then retreive the value from the script...|||

Hi,

I have done the same way. you can see in the code i have added. Rows is the package level variable I have used. In script I used Variables.Rows to access the value. when i write into a file it rights as 0

Thanks

|||

Can you try as follows:

Dim sw As New StreamWriter("D:\Vijay1.txt")

sw.WriteLine(Dts.Variables("Rows").Value.ToString())

sw.close()

Thanks,
Loonysan

|||

ManjuVijay wrote:

Hi,

I have done the same way. you can see in the code i have added. Rows is the package level variable I have used. In script I used Variables.Rows to access the value. when i write into a file it rights as 0

Thanks

the code should be:

s = Dts.Variables("Rows").Value

|||

Hi,

I am getting error saying DTS is not declared.

Thanks

|||

Hi,

I want to know whether i'm missing anyother thing.

I beleive I have to set only the variable name in RowCount. Any thing else I have to do?

|||

If i use script task it works properly

why i am not able to do so in script transform component

|||

The Script Task and Script Component are very different beasts. It is wrong to assume that because you can do something in one then you can also do the same in the other.

Its also true to say there are different ways of doing the same thing. For example, the syntax for accessing variables in the script component is different to that for accessig them in the script task.

What exactly are you unable to do?

-Jamie

|||> If i use script task it works properly

>why i am not able to do so in script transform component

The script component is used within a DataFlow task. The DataFlow task "snapshots" a variable value when it begins execution and cannot modify the variable until it has completed.

So, your row count = 0 at the beginning of execution. Your script component accesses the "snapshot" value and writes out 0.

The RowCount component only updates the row count variable, when execution of the data flow has completed. Your script task accesses the value after this and writes out the final rowcount.

Why does SSIS snapshot variable values? Well imagine a conditional split where the data is split on a variable value. If that could change during execution of a data flow, the behaviour of the split would be unpredictable - rows would be directed depending on whether they just happened to reach the split before or after the variable changed.

Donald

sql

Monday, March 12, 2012

Row Counts for every user table in a database?

Hello again, everyone!
I'm attempting to make a stored procedure that gets the rowcount for every
table in a given database. To do this, obviously, I need to use a cursor.
The problem I'm having is with passing the database name to the procedure,
and having it evaluate and run the expression. Here is my code thus far:
----
--
create procedure z_sp_CountTest
@.DatabaseName nvarchar(100)
as
-- Declare the Variables
Declare
@.SQL nvarchar(300),
@.DatabaseSysObjects nvarchar(100),
@.TableName sysname
-- Make a string for the database name and table to get all table names from
Set @.DatabaseSysObjects = @.DatabaseName + '.dbo.sysobjects'
-- Create a SQL string to get the user table names
Set @.SQL = 'Select name from ' + @.DatabaseSysObjects + ' where xtype = ''U''
order by name'
-- Declare the cursor to get the Table Names
Declare GetTableRowCounts Cursor
Local
For
exec master.dbo.sp_executesql @.SQL
Open GetTableRowCounts
Fetch next from GetTableRowCounts into @.TableName
While (@.@.FETCH_STATUS = 0)
Begin
[Do what I want with the rowcounts here.. Will require a statement similiar
to the above]
End
CLOSE GetTableRowCounts
DEALLOCATE GetTableRowCounts
----
--
However, whenever I do a syntax check, I always get:
Server: Msg 156, Level 15, State 1, Procedure z_sp_CountTest, Line 21
Incorrect syntax near the keyword 'exec'.
Can anyone give me a clue as to what it could possibly be?
I've tried almost every itteration of the exec line I could think of. This
includes leaving the master.dbo out, trying just exec, and many other
hair-brainned ideas.
Any help would be great!You'll probably have to dump the results from the @.SQL into a temp table and
run the cursor on the temp table.
-D
"Adam St. Pierre" <AdamStPierre@.discussions.microsoft.com> wrote in message
news:006956CB-2309-457C-BA49-FE08D5BB3894@.microsoft.com...
> Hello again, everyone!
> I'm attempting to make a stored procedure that gets the rowcount for every
> table in a given database. To do this, obviously, I need to use a cursor.
> The problem I'm having is with passing the database name to the procedure,
> and having it evaluate and run the expression. Here is my code thus far:
> ----
--
> create procedure z_sp_CountTest
> @.DatabaseName nvarchar(100)
> as
> -- Declare the Variables
> Declare
> @.SQL nvarchar(300),
> @.DatabaseSysObjects nvarchar(100),
> @.TableName sysname
> -- Make a string for the database name and table to get all table names
> from
> Set @.DatabaseSysObjects = @.DatabaseName + '.dbo.sysobjects'
> -- Create a SQL string to get the user table names
> Set @.SQL = 'Select name from ' + @.DatabaseSysObjects + ' where xtype =
> ''U''
> order by name'
>
> -- Declare the cursor to get the Table Names
> Declare GetTableRowCounts Cursor
> Local
> For
> exec master.dbo.sp_executesql @.SQL
> Open GetTableRowCounts
> Fetch next from GetTableRowCounts into @.TableName
> While (@.@.FETCH_STATUS = 0)
> Begin
> [Do what I want with the rowcounts here.. Will require a statement
> similiar
> to the above]
> End
> CLOSE GetTableRowCounts
> DEALLOCATE GetTableRowCounts
> ----
--
>
> However, whenever I do a syntax check, I always get:
> Server: Msg 156, Level 15, State 1, Procedure z_sp_CountTest, Line 21
> Incorrect syntax near the keyword 'exec'.
> Can anyone give me a clue as to what it could possibly be?
> I've tried almost every itteration of the exec line I could think of. This
> includes leaving the master.dbo out, trying just exec, and many other
> hair-brainned ideas.
>
> Any help would be great!
>|||Adam,
You can use a non-documented sp sp_msforeachtable (not recommended in
production code) or create a cursor to traverse information_schema.tables.
You can also pull that info from the system table sysindexes, but be sure to
first execute "dbcc updateusage (...) with count_rows".
use northwind
go
exec sp_msforeachtable 'select ''?'', count(*) from ?'
go
create table #t (
tname sysname,
rcnt int
)
declare @.tn sysname
declare @.sql nvarchar(4000)
declare my_cursor cursor local fast_forward
for
select
quotename(table_schema) + '.' + quotename(table_name)
from
information_schema.tables
where
objectproperty(object_id(quotename(table
_schema) + '.' +
quotename(table_name)), 'IsUserTable') = 1
and objectproperty(object_id(quotename(table
_schema) + '.' +
quotename(table_name)), 'IsMSShipped') = 0
open my_cursor
while 1 = 1
begin
fetch next from my_cursor into @.tn
if @.@.error != 0 or @.@.fetch_status != 0 break
set @.sql = N'select ''' + @.tn + N''', count(*) from ' + @.tn
insert into #t
exec sp_executesql @.sql
end
close my_cursor
deallocate my_cursor
select * from #t order by 1
drop table #t
go
dbcc updateusage (0) with count_rows
go
select object_name([id]) as table_name, rowcnt
from sysindexes
where indid in (0, 1) and objectproperty([id], 'IsUserTable') = 1
order by 1
go
AMB
"Adam St. Pierre" wrote:

> Hello again, everyone!
> I'm attempting to make a stored procedure that gets the rowcount for every
> table in a given database. To do this, obviously, I need to use a cursor.
> The problem I'm having is with passing the database name to the procedure,
> and having it evaluate and run the expression. Here is my code thus far:
> ----
--
> create procedure z_sp_CountTest
> @.DatabaseName nvarchar(100)
> as
> -- Declare the Variables
> Declare
> @.SQL nvarchar(300),
> @.DatabaseSysObjects nvarchar(100),
> @.TableName sysname
> -- Make a string for the database name and table to get all table names fr
om
> Set @.DatabaseSysObjects = @.DatabaseName + '.dbo.sysobjects'
> -- Create a SQL string to get the user table names
> Set @.SQL = 'Select name from ' + @.DatabaseSysObjects + ' where xtype = ''U
''
> order by name'
>
> -- Declare the cursor to get the Table Names
> Declare GetTableRowCounts Cursor
> Local
> For
> exec master.dbo.sp_executesql @.SQL
> Open GetTableRowCounts
> Fetch next from GetTableRowCounts into @.TableName
> While (@.@.FETCH_STATUS = 0)
> Begin
> [Do what I want with the rowcounts here.. Will require a statement simili
ar
> to the above]
> End
> CLOSE GetTableRowCounts
> DEALLOCATE GetTableRowCounts
> ----
--
>
> However, whenever I do a syntax check, I always get:
> Server: Msg 156, Level 15, State 1, Procedure z_sp_CountTest, Line 21
> Incorrect syntax near the keyword 'exec'.
> Can anyone give me a clue as to what it could possibly be?
> I've tried almost every itteration of the exec line I could think of. This
> includes leaving the master.dbo out, trying just exec, and many other
> hair-brainned ideas.
>
> Any help would be great!
>|||Adam,

> Declare GetTableRowCounts Cursor
> Local
> For
> exec master.dbo.sp_executesql @.SQL
When declaring a cursor, a select statement should go after "For". The
"exec" command is not allow here.
AMB
"Adam St. Pierre" wrote:

> Hello again, everyone!
> I'm attempting to make a stored procedure that gets the rowcount for every
> table in a given database. To do this, obviously, I need to use a cursor.
> The problem I'm having is with passing the database name to the procedure,
> and having it evaluate and run the expression. Here is my code thus far:
> ----
--
> create procedure z_sp_CountTest
> @.DatabaseName nvarchar(100)
> as
> -- Declare the Variables
> Declare
> @.SQL nvarchar(300),
> @.DatabaseSysObjects nvarchar(100),
> @.TableName sysname
> -- Make a string for the database name and table to get all table names fr
om
> Set @.DatabaseSysObjects = @.DatabaseName + '.dbo.sysobjects'
> -- Create a SQL string to get the user table names
> Set @.SQL = 'Select name from ' + @.DatabaseSysObjects + ' where xtype = ''U
''
> order by name'
>
> -- Declare the cursor to get the Table Names
> Declare GetTableRowCounts Cursor
> Local
> For
> exec master.dbo.sp_executesql @.SQL
> Open GetTableRowCounts
> Fetch next from GetTableRowCounts into @.TableName
> While (@.@.FETCH_STATUS = 0)
> Begin
> [Do what I want with the rowcounts here.. Will require a statement simili
ar
> to the above]
> End
> CLOSE GetTableRowCounts
> DEALLOCATE GetTableRowCounts
> ----
--
>
> However, whenever I do a syntax check, I always get:
> Server: Msg 156, Level 15, State 1, Procedure z_sp_CountTest, Line 21
> Incorrect syntax near the keyword 'exec'.
> Can anyone give me a clue as to what it could possibly be?
> I've tried almost every itteration of the exec line I could think of. This
> includes leaving the master.dbo out, trying just exec, and many other
> hair-brainned ideas.
>
> Any help would be great!
>|||> I've been told that sometimes this method isn't completely up to date, but I've come acro
ss a
> situation like that yet.
There are plenty such operations and situations, but it has been improved wi
th each version. But in
2005, it should be considered an exception of this isn't up to date. Below i
s a scrip to show this,
and note that even regular INSERTs can make the values go out of whack. On 2
005 the information is
up to date, though:
-- Pre stuff
SET NOCOUNT ON
USE Credit
IF OBJECT_ID('tempdb..#tmp') IS NOT NULL DROP TABLE #tmp
CREATE TABLE #tmp (seq int IDENTITY (1, 1), RowsInTable int, Comment varchar
(200), indid smallint,
dpages int, reserved int, used int, rowcnt int, statblob image )
GO
---
-- INSERT
---
IF OBJECT_ID('charge2') IS NOT NULL DROP TABLE charge2
SELECT * INTO charge2 FROM charge WHERE 1=0
CREATE CLUSTERED INDEX charge_member_link ON dbo.charge2(member_no)
CREATE INDEX charge_category_link ON dbo.charge2(category_no)
CREATE INDEX charge_charge_amt ON dbo.charge2(charge_amt)
INSERT #tmp SELECT (SELECT COUNT(*) FROM charge2), 'Table created with SELEC
T INTO, index created',
indid, dpages, reserved, used, rowcnt, statblob
FROM sysindexes WHERE id = OBJECT_ID('charge2') order by indid
GO
-- Regular INSERTs
DECLARE @.c INT SELECT @.c = 0
WHILE @.c < 5000
BEGIN
INSERT charge2(member_no, provider_no, category_no, charge_dt, charge_amt, s
tatement_no,
charge_code)
VALUES( 63, 482, 8, 'Sep 18 1997 10:43AM', 503.00, 20063, ' ')
SELECT @.c = @.c + 1
END
INSERT #tmp SELECT (SELECT COUNT(*) FROM charge2), 'After a bunch of regular
INSERTs', indid,
dpages, reserved, used, rowcnt, statblob
FROM sysindexes WHERE id = OBJECT_ID('charge2') order by indid
GO
-- UPDATE STATISTICS
UPDATE STATISTICS charge2
INSERT #tmp SELECT (SELECT COUNT(*) FROM charge2), 'After UPDATE STATISTICS'
, indid, dpages,
reserved, used, rowcnt, statblob
FROM sysindexes WHERE id = OBJECT_ID('charge2') order by indid
GO
---
-- DELETE
---
-- We have a table with 5000 rows, make sure columns in sysindexes are updat
ed
DBCC UPDATEUSAGE(credit, charge2) WITH COUNT_ROWS
--Regular DELETE
SET ROWCOUNT 4000 DELETE FROM charge2 SET ROWCOUNT 0
INSERT #tmp SELECT (SELECT COUNT(*) FROM charge2), 'After UPDATEUSAGE and DE
LETE of 4000 rows',
indid, dpages, reserved, used, rowcnt, statblob
FROM sysindexes WHERE id = OBJECT_ID('charge2') order by indid
GO
---
-- TRUNCATE TABLE
---
-- Make sure we have updated sysindexes for 5000 rows
IF OBJECT_ID('charge2') IS NOT NULL DROP TABLE charge2
SELECT * INTO charge2 FROM charge
CREATE CLUSTERED INDEX charge_member_link ON dbo.charge2(member_no)
CREATE INDEX charge_category_link ON dbo.charge2(category_no)
CREATE INDEX charge_charge_amt ON dbo.charge2(charge_amt)
DBCC UPDATEUSAGE(credit, charge2) WITH COUNT_ROWS
TRUNCATE TABLE charge2
INSERT #tmp SELECT (SELECT COUNT(*) FROM charge2), 'Had 5000 rows with corre
ct space usages, then
TRUNCATE TABLE', indid, dpages, reserved, used, rowcnt, statblob
FROM sysindexes WHERE id = OBJECT_ID('charge2') order by indid
GO
---
-- INSERT with subselect
---
-- Get a new fresh empty charge2 without identity
IF OBJECT_ID('charge2') IS NOT NULL DROP TABLE charge2
CREATE TABLE dbo.charge2
(charge_no int NOT NULL ,member_no int NOT NULL ,provider_no int NOT NULL, c
ategory_no int NOT
NULL,
charge_dt datetime NOT NULL , charge_amt money NOT NULL ,statement_no int NO
T NULL, charge_code
char(2) NOT NULL)
GO
CREATE CLUSTERED INDEX charge_member_link ON dbo.charge2(member_no)
CREATE INDEX charge_category_link ON dbo.charge2(category_no)
CREATE INDEX charge_charge_amt ON dbo.charge2(charge_amt)
SET ROWCOUNT 5000 INSERT charge2 SELECT * FROM charge SET ROWCOUNT 0
INSERT #tmp SELECT (SELECT COUNT(*) FROM charge2), 'After INSERT with SUBSEL
ECT', indid, dpages,
reserved, used, rowcnt, statblob
FROM sysindexes WHERE id = OBJECT_ID('charge2') order by indid
GO
---
-- SELECT INTO
---
IF OBJECT_ID('charge2') IS NOT NULL DROP TABLE charge2
SELECT * INTO charge2 FROM charge
INSERT #tmp SELECT (SELECT COUNT(*) FROM charge2), 'After SELECT INTO', indi
d, dpages, reserved,
used, rowcnt, statblob
FROM sysindexes WHERE id = OBJECT_ID('charge2') order by indid
GO
---
-- CREATE INDEX
---
IF OBJECT_ID('charge2') IS NOT NULL DROP TABLE charge2
SELECT * INTO charge2 FROM charge
CREATE CLUSTERED INDEX charge_member_link ON dbo.charge2(member_no)
CREATE INDEX charge_category_link ON dbo.charge2(category_no)
CREATE INDEX charge_charge_amt ON dbo.charge2(charge_amt)
INSERT #tmp SELECT (SELECT COUNT(*) FROM charge2), 'After CREATE INDEX', ind
id, dpages, reserved,
used, rowcnt, statblob
FROM sysindexes WHERE id = OBJECT_ID('charge2') order by indid
GO
-- Update the tables representation in sysindexes before creating the other
indexes
DROP INDEX charge2.charge_category_link
DROP INDEX charge2.charge_charge_amt
DROP INDEX charge2.charge_member_link
DBCC UPDATEUSAGE(credit, charge2) WITH COUNT_ROWS
CREATE CLUSTERED INDEX charge_member_link ON dbo.charge2(member_no)
CREATE INDEX charge_category_link ON dbo.charge2(category_no)
CREATE INDEX charge_charge_amt ON dbo.charge2(charge_amt)
INSERT #tmp SELECT (SELECT COUNT(*) FROM charge2), 'Dropped indexes, DBCC UP
DATEUSAGE and created
indexes', indid, dpages, reserved, used, rowcnt, statblob
FROM sysindexes WHERE id = OBJECT_ID('charge2') order by indid
GO
---
-- SLOW BCP
---
IF OBJECT_ID('charge2') IS NOT NULL DROP TABLE charge2
SELECT * INTO charge2 FROM charge
-- BCP out
EXEC master..xp_cmdshell 'bcp credit..charge2 out c:\charge.txt /t"[]" /r\n
/c /T', 'no_output'
-- Empty table with 3 indexes -> slow bcp
TRUNCATE TABLE charge2
CREATE CLUSTERED INDEX charge_member_link ON dbo.charge2(member_no)
CREATE INDEX charge_category_link ON dbo.charge2(category_no)
CREATE INDEX charge_charge_amt ON dbo.charge2(charge_amt)
DBCC UPDATEUSAGE(credit, charge2) WITH COUNT_ROWS
-- BCP in
EXEC master..xp_cmdshell 'bcp credit..charge2 in c:\charge.txt /t"[]" /r\n /
c /T', 'no_output'
INSERT #tmp SELECT (SELECT COUNT(*) FROM charge2), 'After slow BCP into empt
y table', indid, dpages,
reserved, used, rowcnt, statblob
FROM sysindexes WHERE id = OBJECT_ID('charge2') order by indid
GO
---
-- FAST BCP
---
IF OBJECT_ID('charge2') IS NOT NULL DROP TABLE charge2
SELECT * INTO charge2 FROM charge WHERE 1 = 0
-- BCP in
EXEC master..xp_cmdshell 'bcp credit..charge2 in c:\charge.txt /t"[]" /r\n /
c /T /h"TABLOCK"',
'no_output'
INSERT #tmp SELECT (SELECT COUNT(*) FROM charge2), 'After fast BCP into empt
y table', indid, dpages,
reserved, used, rowcnt, statblob
FROM sysindexes WHERE id = OBJECT_ID('charge2') order by indid
GO
SELECT * FROM #tmp WHERE indid IN(0,1) ORDER BY seq, indid
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
Blog: http://solidqualitylearning.com/blogs/tibor/
"Colin Dawson" <newsgroups@.cjdawson.com> wrote in message
news:xJyYf.47848$wl.40101@.text.news.blueyonder.co.uk...
> Who needs a cursor? How about using
> select
> so.name,
> si.rows
> from sysobjects so
> Join sysindexes si on si.id = so.id
> and si.indid in (0,1)
> where so.xtype = 'U'
>
> I've been told that sometimes this method isn't completely up to date, but
I've come across a
> situation like that yet. Mind you, I've not been looking.
>
> Colin.
>
> "Adam St. Pierre" <AdamStPierre@.discussions.microsoft.com> wrote in messag
e
> news:006956CB-2309-457C-BA49-FE08D5BB3894@.microsoft.com...
>|||<snip>
> There are plenty such operations and situations, but it has been improved
> with each version. But in 2005, it should be considered an exception of
> this isn't up to date. Below is a scrip to show this, and note that even
> regular INSERTs can make the values go out of whack. On 2005 the
> information is up to date, though:
</snip>
I suppose that I'm really lucky to be working soley with SQL2005 now :-)
Colin.