Showing posts with label rows. Show all posts
Showing posts with label rows. Show all posts

Friday, March 30, 2012

How to get the value of number of rows in groupfooter

I want to show how many records populated in the groupby clause, i want to show the number of rows value in the group footer.

Thank you very much.

If you put this in the group footer, you should see the count for each group.

=CountRows()

Hope this helps.

Jarret

sql

Monday, March 26, 2012

How to get the record created date?

How do I delete rows that are older than 180 days if the table does not
contain a column of timestamp? The following statement works fine if
parameter startdate is known:
DELETE From MyTable Where DATEDIFF (day, startdate, GETDATE()) > 180
Thanks in advance.
-tcYou don't. Unless you can join with another table that has a datetime
column. (Every table 'should' have such a column: RecordCreated datetime)
And 'timestamp' as the timestamp datatype has nothing to do with TIME.
Arnie Rowland
"To be successful, your heart must accompany your knowledge."
"tcw" <tcwangs@.msn.com> wrote in message
news:%23yZt9I4pGHA.4912@.TK2MSFTNGP05.phx.gbl...
> How do I delete rows that are older than 180 days if the table does not
> contain a column of timestamp? The following statement works fine if
> parameter startdate is known:
> DELETE From MyTable Where DATEDIFF (day, startdate, GETDATE()) > 180
> Thanks in advance.
> -tc
>|||SQL Server does not track this information, so you're going to have to add a
column like:
ALTER TABLE MyTable ADD CreatedDate SMALLDATETIME NOT NULL DEFAULT
CURRENT_TIMESTAMP;
Of course, you won't be able to take advantage of the values for this
specifc task until 6 more months have passed.
A
"tcw" <tcwangs@.msn.com> wrote in message
news:%23yZt9I4pGHA.4912@.TK2MSFTNGP05.phx.gbl...
> How do I delete rows that are older than 180 days if the table does not
> contain a column of timestamp? The following statement works fine if
> parameter startdate is known:
> DELETE From MyTable Where DATEDIFF (day, startdate, GETDATE()) > 180
> Thanks in advance.
> -tc
>|||> (Every table 'should' have such a column: RecordCreated datetime)
Whoa, that's a pretty broad generalization. Such a column is useful, but in
most applications it isn't necessary on every single table.
A|||Very True, but I prefer to drive home the point for the generalization, and
then once the idea has taken hold, start dealing with the exceptions. And of
course, not needed at all in some databases.
But for general business data ...
Arnie Rowland
"To be successful, your heart must accompany your knowledge."
"Aaron Bertrand [SQL Server MVP]" <ten.xoc@.dnartreb.noraa> wrote in mess
age
news:epyLdq4pGHA.4812@.TK2MSFTNGP04.phx.gbl...
> Whoa, that's a pretty broad generalization. Such a column is useful, but
> in most applications it isn't necessary on every single table.
> A
>|||It would be better to drive home the fact that each row should take up as
little space as possible and then deal with the exceptions. That way you
encourage efficiency.
Best regards
Mark Baldwin
"Arnie Rowland" <arnie@.1568.com> wrote in message
news:eiBkZz4pGHA.4912@.TK2MSFTNGP05.phx.gbl...
> Very True, but I prefer to drive home the point for the generalization,
> and then once the idea has taken hold, start dealing with the exceptions.
> And of course, not needed at all in some databases.
> But for general business data ...
> --
> Arnie Rowland
> "To be successful, your heart must accompany your knowledge."
>
> "Aaron Bertrand [SQL Server MVP]" <ten.xoc@.dnartreb.noraa> wrote in
> message news:epyLdq4pGHA.4812@.TK2MSFTNGP04.phx.gbl...
>|||I'm less concerned with saving 4 or 8 bytes than with having a 'robust' data
system -I keep hearing storage is inexpensive. Perhaps it's just the segment
of large corporation and government agencies that I work with, but for the
last several years, all projects I've worked with have either required or
benefited from having not only a date column (entered/changed) -but also a
column capturing 'who' was responsible. And updates/deletes from selected
tables may be shadowed to an archive table/server. I tend to work with
VLDB's that must meet requirements set out by Aegis (law enforcement),
SarBox (financial), and/or HIPPA (medical).
Personally, I think that business systems 'should' have date and person
columns on almost every table. They solve so many of the 'problems' that
come up over a project's lifecycle. -Such as the one posted by the OP.
Arnie Rowland
"To be successful, your heart must accompany your knowledge."
"Mark" <swozz_@.hotmail.com> wrote in message
news:OT$O7e$pGHA.5064@.TK2MSFTNGP05.phx.gbl...
> It would be better to drive home the fact that each row should take up as
> little space as possible and then deal with the exceptions. That way you
> encourage efficiency.
> --
> Best regards
> Mark Baldwin
>
> "Arnie Rowland" <arnie@.1568.com> wrote in message
> news:eiBkZz4pGHA.4912@.TK2MSFTNGP05.phx.gbl...
>|||> benefited from having not only a date column (entered/changed) -but also
> a column capturing 'who' was responsible.
That kind of data, imho, belongs in a separate auditing table.
Otherwise, you are forced to either have really wide tables or only track
the LAST person who changed it.

> Personally, I think that business systems 'should' have date and person
> columns on almost every table.
I think for higher level entities that's not a bad idea. For complex OLTP
systems with hundreds of tables, you're going to drown yourself in
information overload.
A|||Thank you very much, guys. I think I will add a timestamp column to my table
next time.
-tc
"Aaron Bertrand [SQL Server MVP]" <ten.xoc@.dnartreb.noraa> wrote in mess
age
news:eo6cup4pGHA.148@.TK2MSFTNGP04.phx.gbl...
> SQL Server does not track this information, so you're going to have to add
> a column like:
> ALTER TABLE MyTable ADD CreatedDate SMALLDATETIME NOT NULL DEFAULT
> CURRENT_TIMESTAMP;
> Of course, you won't be able to take advantage of the values for this
> specifc task until 6 more months have passed.
> A
>
> "tcw" <tcwangs@.msn.com> wrote in message
> news:%23yZt9I4pGHA.4912@.TK2MSFTNGP05.phx.gbl...
>|||"tcw" <tcwangs@.msn.com> wrote in message
news:egpsl9GqGHA.4932@.TK2MSFTNGP05.phx.gbl...
> Thank you very much, guys. I think I will add a timestamp column to my
table
> next time.
Note: To be perfectly clear, you wanta datetime (or smalldatetime) column.
Timestamp is a separate datatype which actually doesn't map to date or time.

> -tc
> "Aaron Bertrand [SQL Server MVP]" <ten.xoc@.dnartreb.noraa> wrote in
message
> news:eo6cup4pGHA.148@.TK2MSFTNGP04.phx.gbl...
add[vbcol=seagreen]
>

How to get the record created date?

How do I delete rows that are older than 180 days if the table does not
contain a column of timestamp? The following statement works fine if
parameter startdate is known:
DELETE From MyTable Where DATEDIFF (day, startdate, GETDATE()) > 180
Thanks in advance.
-tcYou don't. Unless you can join with another table that has a datetime
column. (Every table 'should' have such a column: RecordCreated datetime)
And 'timestamp' as the timestamp datatype has nothing to do with TIME.
--
Arnie Rowland
"To be successful, your heart must accompany your knowledge."
"tcw" <tcwangs@.msn.com> wrote in message
news:%23yZt9I4pGHA.4912@.TK2MSFTNGP05.phx.gbl...
> How do I delete rows that are older than 180 days if the table does not
> contain a column of timestamp? The following statement works fine if
> parameter startdate is known:
> DELETE From MyTable Where DATEDIFF (day, startdate, GETDATE()) > 180
> Thanks in advance.
> -tc
>|||SQL Server does not track this information, so you're going to have to add a
column like:
ALTER TABLE MyTable ADD CreatedDate SMALLDATETIME NOT NULL DEFAULT
CURRENT_TIMESTAMP;
Of course, you won't be able to take advantage of the values for this
specifc task until 6 more months have passed.
A
"tcw" <tcwangs@.msn.com> wrote in message
news:%23yZt9I4pGHA.4912@.TK2MSFTNGP05.phx.gbl...
> How do I delete rows that are older than 180 days if the table does not
> contain a column of timestamp? The following statement works fine if
> parameter startdate is known:
> DELETE From MyTable Where DATEDIFF (day, startdate, GETDATE()) > 180
> Thanks in advance.
> -tc
>|||> (Every table 'should' have such a column: RecordCreated datetime)
Whoa, that's a pretty broad generalization. Such a column is useful, but in
most applications it isn't necessary on every single table.
A|||Very True, but I prefer to drive home the point for the generalization, and
then once the idea has taken hold, start dealing with the exceptions. And of
course, not needed at all in some databases.
But for general business data ...
--
Arnie Rowland
"To be successful, your heart must accompany your knowledge."
"Aaron Bertrand [SQL Server MVP]" <ten.xoc@.dnartreb.noraa> wrote in message
news:epyLdq4pGHA.4812@.TK2MSFTNGP04.phx.gbl...
>> (Every table 'should' have such a column: RecordCreated datetime)
> Whoa, that's a pretty broad generalization. Such a column is useful, but
> in most applications it isn't necessary on every single table.
> A
>|||It would be better to drive home the fact that each row should take up as
little space as possible and then deal with the exceptions. That way you
encourage efficiency.
--
Best regards
Mark Baldwin
"Arnie Rowland" <arnie@.1568.com> wrote in message
news:eiBkZz4pGHA.4912@.TK2MSFTNGP05.phx.gbl...
> Very True, but I prefer to drive home the point for the generalization,
> and then once the idea has taken hold, start dealing with the exceptions.
> And of course, not needed at all in some databases.
> But for general business data ...
> --
> Arnie Rowland
> "To be successful, your heart must accompany your knowledge."
>
> "Aaron Bertrand [SQL Server MVP]" <ten.xoc@.dnartreb.noraa> wrote in
> message news:epyLdq4pGHA.4812@.TK2MSFTNGP04.phx.gbl...
>> (Every table 'should' have such a column: RecordCreated datetime)
>> Whoa, that's a pretty broad generalization. Such a column is useful, but
>> in most applications it isn't necessary on every single table.
>> A
>|||I'm less concerned with saving 4 or 8 bytes than with having a 'robust' data
system -I keep hearing storage is inexpensive. Perhaps it's just the segment
of large corporation and government agencies that I work with, but for the
last several years, all projects I've worked with have either required or
benefited from having not only a date column (entered/changed) -but also a
column capturing 'who' was responsible. And updates/deletes from selected
tables may be shadowed to an archive table/server. I tend to work with
VLDB's that must meet requirements set out by Aegis (law enforcement),
SarBox (financial), and/or HIPPA (medical).
Personally, I think that business systems 'should' have date and person
columns on almost every table. They solve so many of the 'problems' that
come up over a project's lifecycle. -Such as the one posted by the OP.
--
Arnie Rowland
"To be successful, your heart must accompany your knowledge."
"Mark" <swozz_@.hotmail.com> wrote in message
news:OT$O7e$pGHA.5064@.TK2MSFTNGP05.phx.gbl...
> It would be better to drive home the fact that each row should take up as
> little space as possible and then deal with the exceptions. That way you
> encourage efficiency.
> --
> Best regards
> Mark Baldwin
>
> "Arnie Rowland" <arnie@.1568.com> wrote in message
> news:eiBkZz4pGHA.4912@.TK2MSFTNGP05.phx.gbl...
>> Very True, but I prefer to drive home the point for the generalization,
>> and then once the idea has taken hold, start dealing with the exceptions.
>> And of course, not needed at all in some databases.
>> But for general business data ...
>> --
>> Arnie Rowland
>> "To be successful, your heart must accompany your knowledge."
>>
>> "Aaron Bertrand [SQL Server MVP]" <ten.xoc@.dnartreb.noraa> wrote in
>> message news:epyLdq4pGHA.4812@.TK2MSFTNGP04.phx.gbl...
>> (Every table 'should' have such a column: RecordCreated datetime)
>> Whoa, that's a pretty broad generalization. Such a column is useful,
>> but in most applications it isn't necessary on every single table.
>> A
>>
>|||> benefited from having not only a date column (entered/changed) -but also
> a column capturing 'who' was responsible.
That kind of data, imho, belongs in a separate auditing table.
Otherwise, you are forced to either have really wide tables or only track
the LAST person who changed it.
> Personally, I think that business systems 'should' have date and person
> columns on almost every table.
I think for higher level entities that's not a bad idea. For complex OLTP
systems with hundreds of tables, you're going to drown yourself in
information overload.
A|||Thank you very much, guys. I think I will add a timestamp column to my table
next time.
-tc
"Aaron Bertrand [SQL Server MVP]" <ten.xoc@.dnartreb.noraa> wrote in message
news:eo6cup4pGHA.148@.TK2MSFTNGP04.phx.gbl...
> SQL Server does not track this information, so you're going to have to add
> a column like:
> ALTER TABLE MyTable ADD CreatedDate SMALLDATETIME NOT NULL DEFAULT
> CURRENT_TIMESTAMP;
> Of course, you won't be able to take advantage of the values for this
> specifc task until 6 more months have passed.
> A
>
> "tcw" <tcwangs@.msn.com> wrote in message
> news:%23yZt9I4pGHA.4912@.TK2MSFTNGP05.phx.gbl...
>> How do I delete rows that are older than 180 days if the table does not
>> contain a column of timestamp? The following statement works fine if
>> parameter startdate is known:
>> DELETE From MyTable Where DATEDIFF (day, startdate, GETDATE()) > 180
>> Thanks in advance.
>> -tc
>|||"tcw" <tcwangs@.msn.com> wrote in message
news:egpsl9GqGHA.4932@.TK2MSFTNGP05.phx.gbl...
> Thank you very much, guys. I think I will add a timestamp column to my
table
> next time.
Note: To be perfectly clear, you wanta datetime (or smalldatetime) column.
Timestamp is a separate datatype which actually doesn't map to date or time.
> -tc
> "Aaron Bertrand [SQL Server MVP]" <ten.xoc@.dnartreb.noraa> wrote in
message
> news:eo6cup4pGHA.148@.TK2MSFTNGP04.phx.gbl...
> > SQL Server does not track this information, so you're going to have to
add
> > a column like:
> >
> > ALTER TABLE MyTable ADD CreatedDate SMALLDATETIME NOT NULL DEFAULT
> > CURRENT_TIMESTAMP;
> >
> > Of course, you won't be able to take advantage of the values for this
> > specifc task until 6 more months have passed.
> >
> > A
> >
> >
> > "tcw" <tcwangs@.msn.com> wrote in message
> > news:%23yZt9I4pGHA.4912@.TK2MSFTNGP05.phx.gbl...
> >> How do I delete rows that are older than 180 days if the table does not
> >> contain a column of timestamp? The following statement works fine if
> >> parameter startdate is known:
> >>
> >> DELETE From MyTable Where DATEDIFF (day, startdate, GETDATE()) > 180
> >>
> >> Thanks in advance.
> >>
> >> -tc
> >>
> >
> >
>sql

How to get the record created date?

How do I delete rows that are older than 180 days if the table does not
contain a column of timestamp? The following statement works fine if
parameter startdate is known:
DELETE From MyTable Where DATEDIFF (day, startdate, GETDATE()) > 180
Thanks in advance.
-tcYou don't. Unless you can join with another table that has a datetime
column. (Every table 'should' have such a column: RecordCreated datetime)
And 'timestamp' as the timestamp datatype has nothing to do with TIME.
--
Arnie Rowland
"To be successful, your heart must accompany your knowledge."
"tcw" <tcwangs@.msn.com> wrote in message
news:%23yZt9I4pGHA.4912@.TK2MSFTNGP05.phx.gbl...
> How do I delete rows that are older than 180 days if the table does not
> contain a column of timestamp? The following statement works fine if
> parameter startdate is known:
> DELETE From MyTable Where DATEDIFF (day, startdate, GETDATE()) > 180
> Thanks in advance.
> -tc
>|||SQL Server does not track this information, so you're going to have to add a
column like:
ALTER TABLE MyTable ADD CreatedDate SMALLDATETIME NOT NULL DEFAULT
CURRENT_TIMESTAMP;
Of course, you won't be able to take advantage of the values for this
specifc task until 6 more months have passed.
A
"tcw" <tcwangs@.msn.com> wrote in message
news:%23yZt9I4pGHA.4912@.TK2MSFTNGP05.phx.gbl...
> How do I delete rows that are older than 180 days if the table does not
> contain a column of timestamp? The following statement works fine if
> parameter startdate is known:
> DELETE From MyTable Where DATEDIFF (day, startdate, GETDATE()) > 180
> Thanks in advance.
> -tc
>|||> (Every table 'should' have such a column: RecordCreated datetime)
Whoa, that's a pretty broad generalization. Such a column is useful, but in
most applications it isn't necessary on every single table.
A|||Very True, but I prefer to drive home the point for the generalization, and
then once the idea has taken hold, start dealing with the exceptions. And of
course, not needed at all in some databases.
But for general business data ...
--
Arnie Rowland
"To be successful, your heart must accompany your knowledge."
"Aaron Bertrand [SQL Server MVP]" <ten.xoc@.dnartreb.noraa> wrote in message
news:epyLdq4pGHA.4812@.TK2MSFTNGP04.phx.gbl...
>> (Every table 'should' have such a column: RecordCreated datetime)
> Whoa, that's a pretty broad generalization. Such a column is useful, but
> in most applications it isn't necessary on every single table.
> A
>|||It would be better to drive home the fact that each row should take up as
little space as possible and then deal with the exceptions. That way you
encourage efficiency.
--
Best regards
Mark Baldwin
"Arnie Rowland" <arnie@.1568.com> wrote in message
news:eiBkZz4pGHA.4912@.TK2MSFTNGP05.phx.gbl...
> Very True, but I prefer to drive home the point for the generalization,
> and then once the idea has taken hold, start dealing with the exceptions.
> And of course, not needed at all in some databases.
> But for general business data ...
> --
> Arnie Rowland
> "To be successful, your heart must accompany your knowledge."
>
> "Aaron Bertrand [SQL Server MVP]" <ten.xoc@.dnartreb.noraa> wrote in
> message news:epyLdq4pGHA.4812@.TK2MSFTNGP04.phx.gbl...
>> (Every table 'should' have such a column: RecordCreated datetime)
>> Whoa, that's a pretty broad generalization. Such a column is useful, but
>> in most applications it isn't necessary on every single table.
>> A
>|||I'm less concerned with saving 4 or 8 bytes than with having a 'robust' data
system -I keep hearing storage is inexpensive. Perhaps it's just the segment
of large corporation and government agencies that I work with, but for the
last several years, all projects I've worked with have either required or
benefited from having not only a date column (entered/changed) -but also a
column capturing 'who' was responsible. And updates/deletes from selected
tables may be shadowed to an archive table/server. I tend to work with
VLDB's that must meet requirements set out by Aegis (law enforcement),
SarBox (financial), and/or HIPPA (medical).
Personally, I think that business systems 'should' have date and person
columns on almost every table. They solve so many of the 'problems' that
come up over a project's lifecycle. -Such as the one posted by the OP.
--
Arnie Rowland
"To be successful, your heart must accompany your knowledge."
"Mark" <swozz_@.hotmail.com> wrote in message
news:OT$O7e$pGHA.5064@.TK2MSFTNGP05.phx.gbl...
> It would be better to drive home the fact that each row should take up as
> little space as possible and then deal with the exceptions. That way you
> encourage efficiency.
> --
> Best regards
> Mark Baldwin
>
> "Arnie Rowland" <arnie@.1568.com> wrote in message
> news:eiBkZz4pGHA.4912@.TK2MSFTNGP05.phx.gbl...
>> Very True, but I prefer to drive home the point for the generalization,
>> and then once the idea has taken hold, start dealing with the exceptions.
>> And of course, not needed at all in some databases.
>> But for general business data ...
>> --
>> Arnie Rowland
>> "To be successful, your heart must accompany your knowledge."
>>
>> "Aaron Bertrand [SQL Server MVP]" <ten.xoc@.dnartreb.noraa> wrote in
>> message news:epyLdq4pGHA.4812@.TK2MSFTNGP04.phx.gbl...
>> (Every table 'should' have such a column: RecordCreated datetime)
>> Whoa, that's a pretty broad generalization. Such a column is useful,
>> but in most applications it isn't necessary on every single table.
>> A
>>
>|||> benefited from having not only a date column (entered/changed) -but also
> a column capturing 'who' was responsible.
That kind of data, imho, belongs in a separate auditing table.
Otherwise, you are forced to either have really wide tables or only track
the LAST person who changed it.
> Personally, I think that business systems 'should' have date and person
> columns on almost every table.
I think for higher level entities that's not a bad idea. For complex OLTP
systems with hundreds of tables, you're going to drown yourself in
information overload.
A|||Thank you very much, guys. I think I will add a timestamp column to my table
next time.
-tc
"Aaron Bertrand [SQL Server MVP]" <ten.xoc@.dnartreb.noraa> wrote in message
news:eo6cup4pGHA.148@.TK2MSFTNGP04.phx.gbl...
> SQL Server does not track this information, so you're going to have to add
> a column like:
> ALTER TABLE MyTable ADD CreatedDate SMALLDATETIME NOT NULL DEFAULT
> CURRENT_TIMESTAMP;
> Of course, you won't be able to take advantage of the values for this
> specifc task until 6 more months have passed.
> A
>
> "tcw" <tcwangs@.msn.com> wrote in message
> news:%23yZt9I4pGHA.4912@.TK2MSFTNGP05.phx.gbl...
>> How do I delete rows that are older than 180 days if the table does not
>> contain a column of timestamp? The following statement works fine if
>> parameter startdate is known:
>> DELETE From MyTable Where DATEDIFF (day, startdate, GETDATE()) > 180
>> Thanks in advance.
>> -tc
>|||"tcw" <tcwangs@.msn.com> wrote in message
news:egpsl9GqGHA.4932@.TK2MSFTNGP05.phx.gbl...
> Thank you very much, guys. I think I will add a timestamp column to my
table
> next time.
Note: To be perfectly clear, you wanta datetime (or smalldatetime) column.
Timestamp is a separate datatype which actually doesn't map to date or time.
> -tc
> "Aaron Bertrand [SQL Server MVP]" <ten.xoc@.dnartreb.noraa> wrote in
message
> news:eo6cup4pGHA.148@.TK2MSFTNGP04.phx.gbl...
> > SQL Server does not track this information, so you're going to have to
add
> > a column like:
> >
> > ALTER TABLE MyTable ADD CreatedDate SMALLDATETIME NOT NULL DEFAULT
> > CURRENT_TIMESTAMP;
> >
> > Of course, you won't be able to take advantage of the values for this
> > specifc task until 6 more months have passed.
> >
> > A
> >
> >
> > "tcw" <tcwangs@.msn.com> wrote in message
> > news:%23yZt9I4pGHA.4912@.TK2MSFTNGP05.phx.gbl...
> >> How do I delete rows that are older than 180 days if the table does not
> >> contain a column of timestamp? The following statement works fine if
> >> parameter startdate is known:
> >>
> >> DELETE From MyTable Where DATEDIFF (day, startdate, GETDATE()) > 180
> >>
> >> Thanks in advance.
> >>
> >> -tc
> >>
> >
> >
>

How to get the numbers of row in a table using function. Simple but there is a problem i have

Here is the code. Trying to get the number of the rows in a table. If it is greater than 0 return false else return true. Later i changed this code with if else but i am wondering why it is giving this error?

Code Snippet

CREATE FUNCTION [dbo].[Ready]

(

-- Add the parameters for the function here

@.ProductPrm uniqueidentifier

)

RETURNS bit

AS

BEGIN

-- Declare the return variable here

DECLARE @.ProductNum int;

DECLARE @.Status bit;

-- Add the T-SQL statements to compute the return value here

SELECT @.ProductNum =COUNT(*)

FROM tblProduct

WHERE ProductID = @.ProductPrm

-- Return the result of the function

CASE WHEN @.ProductNum >= 1 THEN @.Status = 'False' ELSE @.Status = 'True' END

RETURN @.Status

END

Code Snippet

Msg 156, Level 15, State 1, Procedure RestoranHazirMi, Line 25

Incorrect syntax near the keyword 'CASE'.

Msg 102, Level 15, State 1, Procedure RestoranHazirMi, Line 29

Incorrect syntax near 'END'.

CASE WHEN is a statement level construction, not flow control

You could use

Code Snippet

CREATE FUNCTION [dbo].[Ready]

(

-- Add the parameters for the function here

@.ProductPrm uniqueidentifier

)

RETURNS bit

AS

BEGIN

-- Declare the return variable here

DECLARE @.ProductNum int;

DECLARE @.Status bit;

-- Add the T-SQL statements to compute the return value here

SELECT @.Status = CASE WHEN COUNT(*)>=1 THEN 'False' ELSE 'True' END

FROM tblProduct

WHERE ProductID = @.ProductPrm

RETURN @.Status

END

OR (IF/ELSE for flow control):

Code Snippet

CREATE FUNCTION [dbo].[Ready]

(

-- Add the parameters for the function here

@.ProductPrm uniqueidentifier

)

RETURNS bit

AS

BEGIN

-- Declare the return variable here

DECLARE @.ProductNum int;

DECLARE @.Status bit;

-- Add the T-SQL statements to compute the return value here

SELECT @.ProductNum =COUNT(*)

FROM tblProduct

WHERE ProductID = @.ProductPrm

-- Return the result of the function

IF (@.ProductNum >= 1)

SET @.Status = 'False'

ELSE

SET @.Status = 'True'

RETURN @.Status

END

|||thanks dude. I've learned it now.sql

Friday, March 23, 2012

How to get the last occurence of rows containing disticnt value in one column

I have a table that tracks GPS records broadly speaking as follows

tsDATETIME
usernameVARCHAR(16)
...
GPS data
...

I want to select the most recent GPS data for each distinct user.
That is, the table will have may records for a given username, but I
only want the most recent for each one.

For a single user I know I can do

SELECT TOP 1 * from <table> order by ts desc

But I want a set of results that effectively does this for
all users, and I can't work out the necessary query/subquery I
should be using.

I'm sure I'm missing something fairly obvious, so usual newbie
disclaimers apply.

--
HTML-to-text and markup removal with Detagger
http://www.jafsoft.com/detagger/What is the primary key? I'll assume the key consists of (ts,
username), in which case the folllowing should do what you want:

SELECT ts, username, ... /* other columns */
FROM YourTable AS T
WHERE ts =
(SELECT MAX(ts)
FROM YourTable
WHERE username = T.username)

It really helps if you include DDL with questions like this (basically
a CREATE TABLE statement, including keys and constraints). The exact
table structure may make a big difference to the possible solutions.
The usual recommendation that you shouldn't use SELECT * in production
code also applies.

--
David Portas
SQL Server MVP
--|||Please post DDL, so that people do not have to guess what the keys,
constraints, Declarative Referential Integrity, datatypes, etc. in your
schema are. Sample data is also a good idea, along with clear
specifications. Even pseudo-DDL is better than narratives. Is this
what you meant?

CREATE TABLE Foobar
(event_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
user_name VARCHAR(16) NOT NULL,
stuff_1 INTEGER NOT NULL,
stuff_2 INTEGER NOT NULL,
..
stuff_n INTEGER NOT NULL,
PRIMARY KEY (user_name, event_time));

SELECT F1.*
FROM Foobar AS F1
WHERE F1.event_time
= (SELECT MAX(f2.event_time)
FROM Foobar AS F2
WHERE F1.user_name = F2.user_name);
-- use column names in production code, not SELECT *.|||"David Portas" <REMOVE_BEFORE_REPLYING_dportas@.acm.org> wrote:

>What is the primary key? I'll assume the key consists of (ts,
>username), in which case the folllowing should do what you want:
>SELECT ts, username, ... /* other columns */
> FROM YourTable AS T
> WHERE ts =
> (SELECT MAX(ts)
> FROM YourTable
> WHERE username = T.username)

Thanks

>It really helps if you include DDL with questions like this (basically
>a CREATE TABLE statement, including keys and constraints). The exact
>table structure may make a big difference to the possible solutions.

Point noted.

>The usual recommendation that you shouldn't use SELECT * in production
>code also applies.

I realise this. That was just me being lazy (although for some of my
selects I do want the entire row).

--
HTML-to-text and markup removal with Detagger
http://www.jafsoft.com/detagger/|||"--CELKO--" <jcelko212@.earthlink.net> wrote:

>Please post DDL, so that people do not have to guess what the keys,
>constraints, Declarative Referential Integrity, datatypes, etc. in your
>schema are. Sample data is also a good idea, along with clear
>specifications. Even pseudo-DDL is better than narratives. Is this
>what you meant?

Sorry. Will do in future.

Thanks for the solution.
--
HTML-to-text and markup removal with Detagger
http://www.jafsoft.com/detagger/sql

how to get the highest row from the bunch of rows

hi...i just want to retrieve the highest row from the collection of
rows like...my table is:
name year
a 2008
a 2006
b 2007
b 2006
b 2005
c 2007
c 2004
I just need the latest year for all the names like:
name year
a 2008
b 2007
c 2007
THANKS..."sql_learner" <mailfrd@.gmail.com> wrote in message
news:eafce7c0-7c49-415e-b410-336593650ce2@.s8g2000prg.googlegroups.com...
> hi...i just want to retrieve the highest row from the collection of
> rows like...my table is:
> name year
> a 2008
> a 2006
> b 2007
> b 2006
> b 2005
> c 2007
> c 2004
> I just need the latest year for all the names like:
> name year
> a 2008
> b 2007
> c 2007
> THANKS...
SELECT name, MAX(year) year
FROM tbl
GROUP BY name;
--
David Portas|||sql_learner wrote:
> hi...i just want to retrieve the highest row from the collection of
> rows like...my table is:
> name year
> a 2008
> a 2006
> b 2007
> b 2006
> b 2005
> c 2007
> c 2004
> I just need the latest year for all the names like:
> name year
> a 2008
> b 2007
> c 2007
> THANKS...
SELECT name,MAX(year)
FROM tablename
GROUP BY name
... p
--
Posted via a free Usenet account from http://www.teranews.com

Monday, March 19, 2012

How to get Specific rows from Table

hi

i m using row count in order to get first 16 rows from a specific table...now i want to get rows from row no. 16 to 32 (or any no which i want)...can any one tell meee how can i query it using sql server 200

HI,

do it as

for n to n1 records do as

select top n1-n * from

(

select top n1 * from

)

order by key desc

|||

If your total result set is small enough (> 1000 records) you could insert into a table variable with an identity column and then select back out referencing the identity column in the where clause. For example:

DECLARE @.tblTable TABLE

(

TableID INT IDENTITY(1,1)

,OtherID INT

,Value VARCHAR(50)

)

INSERT @.tblTable (OtherID, Value) VALUES (1, 'One')

INSERT @.tblTable (OtherID, Value) VALUES (2, 'Two')

INSERT @.tblTable (OtherID, Value) VALUES (3, 'Three')

INSERT @.tblTable (OtherID, Value) VALUES (4, 'Four')

INSERT @.tblTable (OtherID, Value) VALUES (5, 'Five')

DECLARE @.Start INT, @.End INT

SELECT @.Start = 1, @.End = 3

SELECT *

FROM @.tblTable

WHERE TableID BETWEEN @.Start AND @.End

|||

It seems that you are trying to do pagination in database.

Below is the code snippet for a stored procedure. This takes page number and numbers of records in a Page.

CREATE PROCEDURE Pagination
@.Page int,
@.Size int
AS

DECLARE @.Start int, @.End int
BEGIN TRANSACTION GetDataSet
SET @.Start = (((@.Page - 1) * @.Size) + 1)
IF @.@.ERROR <> 0
GOTO ErrorHandler
SET @.End = (@.Start + @.Size - 1)
IF @.@.ERROR <> 0
GOTO ErrorHandler
CREATE TABLE #TemporaryTable
(
Row int IDENTITY(1,1) PRIMARY KEY,
Project varchar(100),
Buyer int,
Bidder int,
AverageBid money
)
IF @.@.ERROR <> 0
GOTO ErrorHandler
INSERT INTO #TemporaryTable
SELECT ...
-- Any kind of select statement is possible with however many joins
-- as long as the data selected can fit into the temporary table.
IF @.@.ERROR <> 0
GOTO ErrorHandler
SELECT Project, Buyer, Bidder, AverageBid
FROM #TemporaryTable
WHERE (Row >= @.Start) AND (Row <= @.End)
IF @.@.ERROR <> 0
GOTO ErrorHandler
DROP TABLE #TemporaryTable
COMMIT TRANSACTION GetDataSet
RETURN 0
ErrorHandler:
ROLLBACK TRANSACTION GetDataSet
RETURN @.@.ERROR

Regards

Sachin

How to get specific number of rows from each group

I need a SQL query to get 2 items from each catergory.
And if possible, 2 items with price < $100 and 1 item with price >= $100
from each caterogy.
Table: tblItems
Fields: ItemID, CategoryID, ItemName, ItemPrice
A stored procedure with multiple queries also works.
Thanks,
--
GeeviSelect * From Table
Where PK In
(Select Top 2 PK From Table
Where Price < 100
And Category = T.Category
Order By Price
Union
Select Top 1 PK From Table
Where Price >- 100
And Category = T.Category
Order By Price Desc)
"Geevi" wrote:

> I need a SQL query to get 2 items from each catergory.
> And if possible, 2 items with price < $100 and 1 item with price >= $100
> from each caterogy.
> Table: tblItems
> Fields: ItemID, CategoryID, ItemName, ItemPrice
> A stored procedure with multiple queries also works.
> Thanks,
> --
> Geevi
>|||Sorry, Union won't work because you can;t use Order by in parts of a Union..
.
So you have to use separate In Predicate conditions...
Select * From Table
Where PK In
(Select Top 2 PK From Table
Where Price < 100
And Category = T.Category
Order By Price)
Or PK In
(Select Top 1 PK From Table
Where Price >= 100
And Category = T.Category
Order By Price Desc)
"Geevi" wrote:

> I need a SQL query to get 2 items from each catergory.
> And if possible, 2 items with price < $100 and 1 item with price >= $100
> from each caterogy.
> Table: tblItems
> Fields: ItemID, CategoryID, ItemName, ItemPrice
> A stored procedure with multiple queries also works.
> Thanks,
> --
> Geevi
>|||aaaghhh!! Forgot to alias the first Table...
Select * From Table As T -- Left off the "As T" Before
Where PK In
(Select Top 2 PK From Table
Where Price < 100
And Category = T.Category
Order By Price)
Or PK In
(Select Top 1 PK From Table
Where Price >= 100
And Category = T.Category
Order By Price Desc)
"Geevi" wrote:

> I need a SQL query to get 2 items from each catergory.
> And if possible, 2 items with price < $100 and 1 item with price >= $100
> from each caterogy.
> Table: tblItems
> Fields: ItemID, CategoryID, ItemName, ItemPrice
> A stored procedure with multiple queries also works.
> Thanks,
> --
> Geevi
>|||Burying the TOP .. ORDER BY should work:
Select * From Table as T
Where PK In (
select PK from (
Select Top 2 PK From Tbl
Where Price < 100
And Category = T.Category
Order By Price
) PartA
union
select PK from (
Select Top 1 PK From Tbl
Where Price >= 100
And Category = T.Category
Order By Price Desc
) PartB
)
-- I don't know how to get 2 items, of which 2 have prices < $100
-- and one has price >= $100.
Steve Kass
Drew University
CBretana wrote:
> Sorry, Union won't work because you can;t use Order by in parts of a Union
..
> So you have to use separate In Predicate conditions...
>
> Select * From Table
> Where PK In
> (Select Top 2 PK From Table
> Where Price < 100
> And Category = T.Category
> Order By Price)
> Or PK In
> (Select Top 1 PK From Table
> Where Price >= 100
> And Category = T.Category
> Order By Price Desc)
>
> "Geevi" wrote:
>|||Great! It works!
I could not use the Order By "Price" as "ORDER BY items must appear in the
select list if the statement contains a UNION operator."
But this is a big time saver for me.
Thanks CBretana, for the solution!
"CBretana" wrote:
> Select * From Table
> Where PK In
> (Select Top 2 PK From Table
> Where Price < 100
> And Category = T.Category
> Order By Price
> Union
> Select Top 1 PK From Table
> Where Price >- 100
> And Category = T.Category
> Order By Price Desc)
>
>
>
> "Geevi" wrote:
>

How to get scrollbar for a subreport

Hi,

Can anyone tell me how to get a scrollbar inside a subreport.I'm using SQL Server 2005 Business Int. Solution.I'm having more than 1000 rows for a subreport.I want to fix the width and hieght of the subreport so that i can get a scrollbar in the subreport.Please, help me regarding this.

Thanks,

Saradhi

This is easy to do with a report viewer using Visual Studio 2005. I'm not sure how to do this using SQL Server 2005 BIS.

|||

Hi,

Yes.It can be done in Visual Studio 2005 using reportviewer control.But i don't know with SQL Server 2005 BIS. Anyway, thanks for the reply.

Thanks,

Saradhi

Monday, March 12, 2012

How to get rows user defined range?

Hello,
I need a keywork like LIMIT(in oracle) which let me to get rows, I defined.
For exaple I want to show records from 100. record to 200. record!
In oracle I could do like this
Select * from Customer limit 100, 100
I could do a complex query so it let me to get what I want, but I don't
think it has a performance.
Is there a key word like LIMIT in Sql Server?http://www.aspfaq.com/show.asp?id=2120
Adam Machanic
SQL Server MVP
http://www.datamanipulation.net
--
"s" <ss@.hotmail.com> wrote in message
news:OUYvbqM0FHA.3408@.TK2MSFTNGP09.phx.gbl...
> Hello,
> I need a keywork like LIMIT(in oracle) which let me to get rows, I
> defined. For exaple I want to show records from 100. record to 200.
> record!
> In oracle I could do like this
> Select * from Customer limit 100, 100
> I could do a complex query so it let me to get what I want, but I don't
> think it has a performance.
> Is there a key word like LIMIT in Sql Server?
>|||Generate a quota query with a ranking value. You can do all sorts of range
related tricks with such a value. Search the archives of this newsgroup for
some examples.
Anith|||Is LIMIT X,Y part of ANSI-SQL ?
I had a look, but I could only find it as a keyword, not actually defined
what it was for, syntax etc.
"s" <ss@.hotmail.com> wrote in message
news:OUYvbqM0FHA.3408@.TK2MSFTNGP09.phx.gbl...
> Hello,
> I need a keywork like LIMIT(in oracle) which let me to get rows, I
defined.
> For exaple I want to show records from 100. record to 200. record!
> In oracle I could do like this
> Select * from Customer limit 100, 100
> I could do a complex query so it let me to get what I want, but I don't
> think it has a performance.
> Is there a key word like LIMIT in Sql Server?
>|||>> Is LIMIT X,Y part of ANSI-SQL ?
No, I think it is a MySQL dialect. Most prominent SQL variants have some
syntax that partially support quota queries.
Anith

How to get row size

using sql 2k, what's the fastest and easiest way to get the row size of a
row. I hava a number of rows I need to look at.
Thanks.
moondaddy@.noemail.noemailHello,
If you need to estimate the size of a table, you can use the following
Excel file:
http://www.microsoft.com/downloads/...&displaylang=en
The size of each row can be variable (if there are variable-length
columns in the table). If you want to see the min/max/avg row size in
an existing table, you can use:
DBCC SHOWCONTIG ('table name') WITH TABLERESULTS
AFAIK, there is no direct method to get the row size for a particular
row in an existing table. If you need this information, copy that row
in an empty table with the same structure and use DBCC SHOWCONTIG, as
shown above.
Razvan|||this will give you the min size and max size of the rows in you table, then
make an educated guess..
This is the easiest way
select minlen,xmaxlen from sysindexes where indid in (1,0) and id =
object_id('tbl_name')|||Thanks for the reply.
What I'm trying to determin is how close a table is to the max rowsize of
8060. I dont see what part of this is going to help me with that.
I used DBCC SHOWCONTIG ('table name') WITH TABLERESULTS
and got the result below. Should I be able to guestimate the total rowsize
from this?
tbLeaseDt
898102240
PK_tbLeaseDt
1
0
45
1325
120
1431
263.83100000000002
0
7
6
268.73300170898437
96.679847717285156
85.714285714285708
6
7
0.0
14.285714149475098
moondaddy@.noemail.noemail
"Razvan Socol" <rsocol@.gmail.com> wrote in message
news:1146811248.235424.294000@.e56g2000cwe.googlegroups.com...
> Hello,
> If you need to estimate the size of a table, you can use the following
> Excel file:
> http://www.microsoft.com/downloads/...&displaylang=en
> The size of each row can be variable (if there are variable-length
> columns in the table). If you want to see the min/max/avg row size in
> an existing table, you can use:
> DBCC SHOWCONTIG ('table name') WITH TABLERESULTS
> AFAIK, there is no direct method to get the row size for a particular
> row in an existing table. If you need this information, copy that row
> in an empty table with the same structure and use DBCC SHOWCONTIG, as
> shown above.
> Razvan
>|||Thanks. can you please explain how I would guess the approximate total row
size using the min size and max size in the table? I may have a number
varchar columns of large size along with many other columns. even though
none of the current data in the columns is more then a length of 50.
Therefore, wouldn't the max rowsize be superficially low?
moondaddy@.noemail.noemail
"Omnibuzz" <Omnibuzz@.discussions.microsoft.com> wrote in message
news:017A12EC-48E1-409B-9A03-190E9630B9C2@.microsoft.com...
> this will give you the min size and max size of the rows in you table,
> then
> make an educated guess..
> This is the easiest way
> select minlen,xmaxlen from sysindexes where indid in (1,0) and id =
> object_id('tbl_name')
>|||>From these results, you can see that the row size for the smallest row
is 120, the row size for the biggest row is 1431 and the average row
size is 263.83100000000002. These informations are referring to the
rows that exist in the table at this time.
If you want the row size of largest row that can be inserted in the
table, you can compute this size based on the definitions of your
columns (that can be found in the syscolumns table), using the
informations presented in the Books Online topic "estimating table
size":
http://msdn.microsoft.com/library/e...des_02_92k3.asp
Razvan|||Hello,
You could use DATALENGTH() for a quick measure of row size.
Please see "Estimating the Size of a Table" in BOL for some related
infrmation.
Best Regards,
Peter Yang
MCSE2000/2003, MCSA, MCDBA
Microsoft Online Partner Support
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
========================================
=============
This posting is provided "AS IS" with no warranties, and confers no rights.

How to get row count ?

To all gurus,
I am developing an application in which i want to show the number
of rows returned by the query.
e.g.
Select Categories.CategoryName, Products.ProductName,
Sum(([Order Details].UnitPrice*[Quantity]*(1-[Discount])/100)*100) AS
ProductSales
FROM
((([Order Details] INNER JOIN Orders ON [Order Details].OrderID =
Orders.OrderID)
INNER JOIN Products ON [Order Details].ProductID = Products.ProductID)
INNER JOIN Categories ON Products.CategoryID = Categories.CategoryID)
WHERE
(Orders.ShippedDate) BETWEEN '1/1/1997' AND '12/31/1997'
GROUP BY
Categories.CategoryName, Products.ProductName

I want the number of rows returned by this query.
How can i get the number of rows?

Please help me..
waiting for your replies..

Prem
(premratan@.hotmail.com)Select count (*) as "row count" from (select <any query here>) as t

For some reason, the final table alias "as t" is required.

Goetz Graefe

"Prem" <premratan@.hotmail.com> wrote in message
news:2f7d06ff.0311111515.2a2a040c@.posting.google.c om...
> To all gurus,
> I am developing an application in which i want to show the number
> of rows returned by the query.
> e.g.
> Select Categories.CategoryName, Products.ProductName,
> Sum(([Order Details].UnitPrice*[Quantity]*(1-[Discount])/100)*100) AS
> ProductSales
> FROM
> ((([Order Details] INNER JOIN Orders ON [Order Details].OrderID =
> Orders.OrderID)
> INNER JOIN Products ON [Order Details].ProductID = Products.ProductID)
> INNER JOIN Categories ON Products.CategoryID = Categories.CategoryID)
> WHERE
> (Orders.ShippedDate) BETWEEN '1/1/1997' AND '12/31/1997'
> GROUP BY
> Categories.CategoryName, Products.ProductName
> I want the number of rows returned by this query.
> How can i get the number of rows?
> Please help me..
> waiting for your replies..
> Prem
> (premratan@.hotmail.com)|||Refer to @.@.ROWCOUNT in SQL Server Books Online. If you are using ADO in your
application, then you can use the recordset's RecordCount property to get
the value at the client side.

--
-- Anith
( Please reply to newsgroups only )|||premratan@.hotmail.com (Prem) wrote in message news:<2f7d06ff.0311111515.2a2a040c@.posting.google.com>...
> To all gurus,
> I am developing an application in which i want to show the number
> of rows returned by the query.
> e.g.
> Select Categories.CategoryName, Products.ProductName,
> Sum(([Order Details].UnitPrice*[Quantity]*(1-[Discount])/100)*100) AS
> ProductSales
> FROM
> ((([Order Details] INNER JOIN Orders ON [Order Details].OrderID =
> Orders.OrderID)
> INNER JOIN Products ON [Order Details].ProductID = Products.ProductID)
> INNER JOIN Categories ON Products.CategoryID = Categories.CategoryID)
> WHERE
> (Orders.ShippedDate) BETWEEN '1/1/1997' AND '12/31/1997'
> GROUP BY
> Categories.CategoryName, Products.ProductName
> I want the number of rows returned by this query.
> How can i get the number of rows?
> Please help me..
> waiting for your replies..
> Prem
> (premratan@.hotmail.com)

After running the query, you can do this:

select @.@.rowcount

If you need to use the value later, you can put it in a variable:

set @.rows = @.@.rowcount

Simon

how to get RID of rows

thanks

Why exactly do you need the RID?

WesleyB

Visit my SQL Server weblog @. http://dis4ea.blogspot.com

|||

HI WesleyB

I have no concret need now.

Just want to know where it store?

I use dbcc page command to oversee the structure of the data page.

I can see many data row .... but can't see the RID....

|||The RID is not stored. It is calculated from the PageId and the SlotId on the page, i.e. Slot 17 on Page 1:29 has RID 1:29:17.

Thanks,

How to get rid of Ghost Pages

For those of you who may not have heard of ghost pages, when SQL Server
deletes all the rows in a data page, it doesn't re-use it untill a seperate
process cleans up such pages. These pages are called ghost pages.
I have a SQL7 production database where the process to clean up the ghost
pages is not waking up. I just read some where that there is a trace that ca
n
be turned on in order to stop this process from waking up. Can someone pleas
e
tell me what the trace number is that I can turn off?
Here are some more details... I have a table in production that is used as
"scratch pad" and therefore encounters a lot of inserts/deletes. The table a
t
any given time will have a couple of rows to may be a couple of hundred rows
.
Over time, the number of ghost pages increase and the SQLs doing joins
against this table treat it as if it has a lot of rows and as a result, the
underlying query plan changes and causes the SQLs to run for a long time.
Here is the interesting part... I noticed at one point there were only a
couple of rows in the table and the number of data pages showing up in DBCC
SHOWCONTIG output where in hundreds and the extent fragmentation was very
high. Also, in some cases, every data page was in a different extent even
though the table only had a couple of rows. When I created a clustered index
and droped the index, the ghost pages disappeared and made a day and night
difference in performance. When I left the clustered index on the table, the
ghost pages eventually appeared again. From that point onwards, when I
dropped and re-created the clustered index, the ghost pages disappeared one
more time and the underlying SQLs started running much faster again.
Does anyone know of a permenant fix to this?
Thanks.
AdamCan you post the list of trace flags that you have on?
Paul Randal
Lead Program Manager, Microsoft SQL Server Storage Engine
http://blogs.msdn.com/sqlserverstor...ne/default.aspx
This posting is provided "AS IS" with no warranties, and confers no rights.
"Adam" <Adam@.discussions.microsoft.com> wrote in message
news:6DB63A27-CBE7-49E3-9AD7-B61C1BD49C53@.microsoft.com...
> For those of you who may not have heard of ghost pages, when SQL Server
> deletes all the rows in a data page, it doesn't re-use it untill a
> seperate
> process cleans up such pages. These pages are called ghost pages.
> I have a SQL7 production database where the process to clean up the ghost
> pages is not waking up. I just read some where that there is a trace that
> can
> be turned on in order to stop this process from waking up. Can someone
> please
> tell me what the trace number is that I can turn off?
> Here are some more details... I have a table in production that is used
> as
> "scratch pad" and therefore encounters a lot of inserts/deletes. The table
> at
> any given time will have a couple of rows to may be a couple of hundred
> rows.
> Over time, the number of ghost pages increase and the SQLs doing joins
> against this table treat it as if it has a lot of rows and as a result,
> the
> underlying query plan changes and causes the SQLs to run for a long time.
> Here is the interesting part... I noticed at one point there were only a
> couple of rows in the table and the number of data pages showing up in
> DBCC
> SHOWCONTIG output where in hundreds and the extent fragmentation was very
> high. Also, in some cases, every data page was in a different extent even
> though the table only had a couple of rows. When I created a clustered
> index
> and droped the index, the ghost pages disappeared and made a day and night
> difference in performance. When I left the clustered index on the table,
> the
> ghost pages eventually appeared again. From that point onwards, when I
> dropped and re-created the clustered index, the ghost pages disappeared
> one
> more time and the underlying SQLs started running much faster again.
> Does anyone know of a permenant fix to this?
> Thanks.
> Adam

How to get rid of Ghost Pages

For those of you who may not have heard of ghost pages, when SQL Server
deletes all the rows in a data page, it doesn't re-use it untill a seperate
process cleans up such pages. These pages are called ghost pages.
I have a SQL7 production database where the process to clean up the ghost
pages is not waking up. I just read some where that there is a trace that can
be turned on in order to stop this process from waking up. Can someone please
tell me what the trace number is that I can turn off?
Here are some more details... I have a table in production that is used as
"scratch pad" and therefore encounters a lot of inserts/deletes. The table at
any given time will have a couple of rows to may be a couple of hundred rows.
Over time, the number of ghost pages increase and the SQLs doing joins
against this table treat it as if it has a lot of rows and as a result, the
underlying query plan changes and causes the SQLs to run for a long time.
Here is the interesting part... I noticed at one point there were only a
couple of rows in the table and the number of data pages showing up in DBCC
SHOWCONTIG output where in hundreds and the extent fragmentation was very
high. Also, in some cases, every data page was in a different extent even
though the table only had a couple of rows. When I created a clustered index
and droped the index, the ghost pages disappeared and made a day and night
difference in performance. When I left the clustered index on the table, the
ghost pages eventually appeared again. From that point onwards, when I
dropped and re-created the clustered index, the ghost pages disappeared one
more time and the underlying SQLs started running much faster again.
Does anyone know of a permenant fix to this?
Thanks.
Adam
Can you post the list of trace flags that you have on?
Paul Randal
Lead Program Manager, Microsoft SQL Server Storage Engine
http://blogs.msdn.com/sqlserverstorageengine/default.aspx
This posting is provided "AS IS" with no warranties, and confers no rights.
"Adam" <Adam@.discussions.microsoft.com> wrote in message
news:6DB63A27-CBE7-49E3-9AD7-B61C1BD49C53@.microsoft.com...
> For those of you who may not have heard of ghost pages, when SQL Server
> deletes all the rows in a data page, it doesn't re-use it untill a
> seperate
> process cleans up such pages. These pages are called ghost pages.
> I have a SQL7 production database where the process to clean up the ghost
> pages is not waking up. I just read some where that there is a trace that
> can
> be turned on in order to stop this process from waking up. Can someone
> please
> tell me what the trace number is that I can turn off?
> Here are some more details... I have a table in production that is used
> as
> "scratch pad" and therefore encounters a lot of inserts/deletes. The table
> at
> any given time will have a couple of rows to may be a couple of hundred
> rows.
> Over time, the number of ghost pages increase and the SQLs doing joins
> against this table treat it as if it has a lot of rows and as a result,
> the
> underlying query plan changes and causes the SQLs to run for a long time.
> Here is the interesting part... I noticed at one point there were only a
> couple of rows in the table and the number of data pages showing up in
> DBCC
> SHOWCONTIG output where in hundreds and the extent fragmentation was very
> high. Also, in some cases, every data page was in a different extent even
> though the table only had a couple of rows. When I created a clustered
> index
> and droped the index, the ghost pages disappeared and made a day and night
> difference in performance. When I left the clustered index on the table,
> the
> ghost pages eventually appeared again. From that point onwards, when I
> dropped and re-created the clustered index, the ghost pages disappeared
> one
> more time and the underlying SQLs started running much faster again.
> Does anyone know of a permenant fix to this?
> Thanks.
> Adam

How to get return value for the number of rows affected by update command

Hi,

i read from help files that "For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. " Anyone know how to get the return value from the query below?

Below is the normal way i did in vb.net, but how to check for the return value. Please help.

========
Public Sub CreateMySqlCommand(myExecuteQuery As String, myConnection As SqlConnection)
Dim myCommand As New SqlCommand(myExecuteQuery, myConnection)
myCommand.Connection.Open()
myCommand.ExecuteNonQuery()
myConnection.Close()
End Sub 'CreateMySqlCommand
========

Thank you.you can add either of these statements to the SQL being called
[BOL} @.@.rowcount
[BOL] Rowcount_big

the difference is in the datatypes rowcount _big returns a bigint
and @.@.rowcount returns int

if you have over 2 billion rows user rowcount_big|||Hi Ruprect, thanks for your reply. My sql statement is a very simple insert query without using any parameters just like the one below:

sql = "INSERT INTO [Subscriber] ([SubID], [SubName], [SubEmail], [Status], [MailID], [SubscribeDate]) VALUES (SubID, SubName, SubEmail, 'Pending', MailID ,getDate())"

I'm unsure of how to include the " [BOL} @.@.rowcount ". Do you mean that i should add a parameter to return @.@.rowcount or there is other way to do it? I'm new to this, would you please give me an example.

Thanks for your time.|||@.@.Rowcount stored the number of records affected by the immediately prior statement. The value is lost as soon as another statement is executed, so you must either use it immediately or store it in a procedure variable:

declare @.RecordsAffected Int
.
.
.
.
.
Update/Select/Delete some records from somewhere...
set @.RecordsAffected = @.@.RowCount

Look up @.@.Rowcount in Books Online for more details.|||thanks BLIND MAN
i didnt getthis until late
[BOL] stands for Books Online it's the sql server help file
i was giving you the article title

and since blindman got it exactly i've no need to reiterate
good luck.|||see if there is something like mycommand.rowsaffected property.|||Thanks Blindman and Thanks Ruprect. I'll study BOL ;) for details of @.@.rowcount.|||You should also follow ms_sql_dba's suggestion to see if there is a method to return the value via VB.

It might be more appropriate if you are going to use the value in your VB code.|||Hi ms_sql_dba, there isn't any rowsaffected property, however there is this UpdatedRowSource and others ..

Thanks for your suggestion, although i'm unsure of their usage, i'll look into it and see if i can find something which stores the value of number of rows affected!|||Sure Blindman, i'll study both ways and see which one is more applicable for my situation. You have a great day.|||Hi Everyone,

I managed to find another solution to my question. Just simply assign the value like this line:-

rowsAffected = myCommand.ExecuteNonQuery()|||see, it was simple!|||Yea. Lesson learned! Cheers!!!

Wednesday, March 7, 2012

How to get missing rows?

Hello,
I've got a table in SQL Server 2005 that contains a column of unique id's
that range between something like 1123454 and 2985763. What I need to do is
order by this column (easy to do) and then find the quickest way to loop
through each column and get just the missing numbers. Such as after ordering
my uniqueid the first column would look like:
1345874
1345879
1345883
and so on...
Assuming that this table has about 2 million rows populated out of a
possible 10 million sequential unique id's (but not sequentially populated),
my program needs to check if a number exists and if so, do nothing. If the
number doesn't exist, use that missing number to process code and insert a
row with the missing unique id and data.
I can do all of this, but I'm just wondering what might be the best
(fastest) way to loop through this table and find the missing unique id's. I
t
is a remote database and my program runs locally.
Thanks for any suggestions.First suggestion is to rethink your logic. What do you plan to do with the
"missing" numbers?
Plus, this is a trivial exercise, which makes me question the design again.
loop while @.curr_id < @.max_id
begin
Select @.curr_id = min(id) where id > @.last_id...
if @.curr_id > @.last_id + 1
...
set @.last_id = @.curr_id
etc
"John Riddle" <JohnRiddle@.discussions.microsoft.com> wrote in message
news:432D5D43-43E0-4760-AEDD-531D32921F57@.microsoft.com...
> Hello,
> I've got a table in SQL Server 2005 that contains a column of unique id's
> that range between something like 1123454 and 2985763. What I need to do
> is
> order by this column (easy to do) and then find the quickest way to loop
> through each column and get just the missing numbers. Such as after
> ordering
> my uniqueid the first column would look like:
> 1345874
> 1345879
> 1345883
> and so on...
> Assuming that this table has about 2 million rows populated out of a
> possible 10 million sequential unique id's (but not sequentially
> populated),
> my program needs to check if a number exists and if so, do nothing. If the
> number doesn't exist, use that missing number to process code and insert a
> row with the missing unique id and data.
> I can do all of this, but I'm just wondering what might be the best
> (fastest) way to loop through this table and find the missing unique id's.
> It
> is a remote database and my program runs locally.
> Thanks for any suggestions.|||Here's a sample. You can modify it to your table. The #Numbers table
population SELECT ... INTO statement is courtesy of Steve Kalis:
SELECT TOP 1000000 Num = IDENTITY(INT, 1, 1) INTO #Numbers
FROM sysobjects s1
CROSS JOIN sysobjects s2
CREATE TABLE #TempA (IDCol INT PRIMARY KEY NOT NULL)
INSERT INTO #TempA (IDCol)
SELECT 1
UNION SELECT 2
UNION SELECT 3
UNION SELECT 20
UNION SELECT 18
UNION SELECT 11
SELECT *
FROM #TempA ta
RIGHT JOIN #Numbers n
ON ta.IDCol = n.Num
WHERE ta.IDCol IS NULL
DROP TABLE #TempA
DROP TABLE #Numbers
"John Riddle" <JohnRiddle@.discussions.microsoft.com> wrote in message
news:432D5D43-43E0-4760-AEDD-531D32921F57@.microsoft.com...
> Hello,
> I've got a table in SQL Server 2005 that contains a column of unique id's
> that range between something like 1123454 and 2985763. What I need to do
> is
> order by this column (easy to do) and then find the quickest way to loop
> through each column and get just the missing numbers. Such as after
> ordering
> my uniqueid the first column would look like:
> 1345874
> 1345879
> 1345883
> and so on...
> Assuming that this table has about 2 million rows populated out of a
> possible 10 million sequential unique id's (but not sequentially
> populated),
> my program needs to check if a number exists and if so, do nothing. If the
> number doesn't exist, use that missing number to process code and insert a
> row with the missing unique id and data.
> I can do all of this, but I'm just wondering what might be the best
> (fastest) way to loop through this table and find the missing unique id's.
> It
> is a remote database and my program runs locally.
> Thanks for any suggestions.|||google up
"Islands and Gaps in Sequential Numbers"
by Alexander Kozak|||Yes, I can think of several ways to do it as well. First being a cursor
movement. However, I was curious as to what you database guys thought would
be the FASTEST method.
To let you know, my program uses the unique id field to check a website
which uses the field in the url. I have been manually incrementing the id in
my program and building the url. About half of the urls work (actually have
a
page associated with them). The others will be used at some unkown time in
the future until all are used up. I have no way of knowing after I've alread
y
travelled through a million or so id's which ones have since been used for m
e
to travel back through.
Since the utility takes time to set a get request to the webserver and wait
for a response to find out if there is new content, going through the same
million rows again is very time consuming just to find the new id's that now
have content. I wanted to skip straight through those id's already processed
by the utility and just check the unused id's. This would speed up the
re-checking of a block of id's considerably. Make sense?
I had initially thought of using a cursor to compare the table id against a
int variable that is incremented by one each time and processing if the
cursor id <> int. However, a friend had said that cursor operations on
millions of rows are slow. I thought there might be some sql method to
restrict by unused id's and simply loop straight trhough a set of
known-to-unused id's.
Thought I'd post it to the group for general ideas. I can easily implement
the concept of one of you guys knows that such and such method would be the
fastest.
Thanks.
"Jeff Dillon" wrote:

> First suggestion is to rethink your logic. What do you plan to do with the
> "missing" numbers?
> Plus, this is a trivial exercise, which makes me question the design again
.
> loop while @.curr_id < @.max_id
> begin
> Select @.curr_id = min(id) where id > @.last_id...
> if @.curr_id > @.last_id + 1
> ...
> set @.last_id = @.curr_id
> etc
>
> "John Riddle" <JohnRiddle@.discussions.microsoft.com> wrote in message
> news:432D5D43-43E0-4760-AEDD-531D32921F57@.microsoft.com...
>
>|||That's not the problem. I could think of at least two ways of doing. But
since this will be performed on millions of number, I was just looking for
suggestions as to what would be the highest performing approach, not a code
sample.
However, Mike's response was very good and I think I'll be using that
approach.
Thanks.
"Alexander Kuznetsov" wrote:

> google up
> "Islands and Gaps in Sequential Numbers"
> by Alexander Kozak
>|||You have a separate web page for each id? Wow. Have you considered a single
page with appropriate logic? Primary keys should never be used like this.
What are you trying to do? And why try to "fill in the gaps". Just use the
next one?
Options:
* Use a GUID
* Use an Identity column
* Use a table that stores the last number..then use Select @.NewID =
Max(LastID) + 1
"John Riddle" <JohnRiddle@.discussions.microsoft.com> wrote in message
news:229308E3-4EDF-4BB2-AD39-20CFC472AB45@.microsoft.com...
> Yes, I can think of several ways to do it as well. First being a cursor
> movement. However, I was curious as to what you database guys thought
> would
> be the FASTEST method.
> To let you know, my program uses the unique id field to check a website
> which uses the field in the url. I have been manually incrementing the id
> in
> my program and building the url. About half of the urls work (actually
> have a
> page associated with them). The others will be used at some unkown time in
> the future until all are used up. I have no way of knowing after I've
> already
> travelled through a million or so id's which ones have since been used for
> me
> to travel back through.
> Since the utility takes time to set a get request to the webserver and
> wait
> for a response to find out if there is new content, going through the same
> million rows again is very time consuming just to find the new id's that
> now
> have content. I wanted to skip straight through those id's already
> processed
> by the utility and just check the unused id's. This would speed up the
> re-checking of a block of id's considerably. Make sense?
> I had initially thought of using a cursor to compare the table id against
> a
> int variable that is incremented by one each time and processing if the
> cursor id <> int. However, a friend had said that cursor operations on
> millions of rows are slow. I thought there might be some sql method to
> restrict by unused id's and simply loop straight trhough a set of
> known-to-unused id's.
> Thought I'd post it to the group for general ideas. I can easily
> implement
> the concept of one of you guys knows that such and such method would be
> the
> fastest.
> Thanks.
> "Jeff Dillon" wrote:
>|||Its not my web page. Its an outside web page that I'm populating my data bas
e
with data from. I'm parsing the page and populating the database.
As I described before, my utility navigates to the page. In the url of the
page is an "id". The website that I'm getting the data from does "just fill
in the gaps" from time to time and hence I need to re-traverse all the
possible id's to find out which ones are now being used and populating my
database with the additional info recently posted.
Since I don't want to re-traverse id's that I've already got data for, I
need a fast way to only go to the id's that I don't yet have data for. So I
need to "restrict" my table by id's that are <not> in the table yet. I want
my utility to re-traverse a set of id's about 10million long and fill in the
gaps of missing data with id's that were not yet used at the time of the
first traversal but are now being used by the site and have data associated
with them. About 80% are used in my database, but nearly 100% are now being
used in that same id block on the remote site (that I have no control over).
Now do you understand? Its not a design issue. I can only get information as
it becomes available and associated with a certain id. The outside website
seems to have no rhyme nor reason in how they assign id's to results tables,
so I'm left with having to constantly re-check urls that had no data in them
at the last traversal.
"Jeff Dillon" wrote:

> You have a separate web page for each id? Wow. Have you considered a singl
e
> page with appropriate logic? Primary keys should never be used like this.
> What are you trying to do? And why try to "fill in the gaps". Just use the
> next one?
> Options:
> * Use a GUID
> * Use an Identity column
> * Use a table that stores the last number..then use Select @.NewID =
> Max(LastID) + 1
>
> "John Riddle" <JohnRiddle@.discussions.microsoft.com> wrote in message
> news:229308E3-4EDF-4BB2-AD39-20CFC472AB45@.microsoft.com...
>
>|||
This message is for Alexander Kozak. I am trying to reach Alexey
Ostrovsky, who I believe you know. Alexey has been out of contact for
over a month and I am worried about him. If you are the correct
Alexander Kozak, please contact me at bobemail1s-alexey@.yahoo.com
(displosable email in case of spam).
My apologies for posting to the group off subject. But I do not have
Alexander's direct email.
Thanks,
Bob Flanagan
*** Sent via Developersdex http://www.examnotes.net ***|||Bob,
Alex Kozak has recently published an article "Powerful, Flexible
Text-Formatting Solutions in SQL Server " on devx.com. There is an
"E-Mail the author" button on page 3.

Friday, February 24, 2012

How to get INSERT-SQL for rows?

Hi

I'm using the SQL Server 2005 Express edition.
I've manually created some rows in a table "Books".

If I right-click on "dbo.Books" and choose "Script Table As --> Create To --> New Query Editor Window", I get the SQL for creating that table.

But how do I get the INSERT-SQL for the rows already inserted?

Kind Regards

hi,

there's no support for that task, you have to do it your self..

or you can have a look at a free prj of mine, amInsert, available at http://www.asql.biz/en/Download2005.aspx

regards

|||

Hi Andrea

Thanks for your ImInsert!
It worked perfectly!

Kind Regards