Showing posts with label number. Show all posts
Showing posts with label number. Show all posts

Friday, March 30, 2012

how to Diff vs Sum in Group By query?

Hello,
if area 'A' contains 2 numbers in 2 rows then
Select area, Sum(number) from tbl1 where area = 'A'
Group By area
gives me the sum of these 2 numbers in area 'A'
But how can I retrieve the difference of these 2 numbers
using T-Sql?
Thanks,
RonRon wrote:
> Hello,
> if area 'A' contains 2 numbers in 2 rows then
> Select area, Sum(number) from tbl1 where area = 'A'
> Group By area
> gives me the sum of these 2 numbers in area 'A'
> But how can I retrieve the difference of these 2 numbers
> using T-Sql?
> Thanks,
> Ron
Max(number) - Min(number)
Bob Barrows
--
Microsoft MVP -- ASP/ASP.NET
Please reply to the newsgroup. The email account listed in my From
header is my spam trap, so I don't check it very often. You will get a
quicker response by posting to the newsgroup.|||Thanks. That is pretty . I forgot to include a
twist in here. I also have a datefld. So num1 may be min
or num may be max. I have to show +num or -num.
select area, (First(num) - Last(num)) as num1 from tbl1
where datefld between '1/1/2005' and 1/2/2005' Group By
area having area = 'A'
I was able to use your trick to get my positive or
negative result using First and Last functions. Any
suggestions appreciated if this is incorrect usage.
Thanks again,
Ron

>--Original Message--
>Ron wrote:
>Max(number) - Min(number)
>Bob Barrows
>--
>Microsoft MVP -- ASP/ASP.NET
>Please reply to the newsgroup. The email account listed
in my From
>header is my spam trap, so I don't check it very often.
You will get a
>quicker response by posting to the newsgroup.
>
>.
>|||Ron wrote:
> Thanks. That is pretty . I forgot to include a
> twist in here. I also have a datefld. So num1 may be min
> or num may be max. I have to show +num or -num.
> select area, (First(num) - Last(num)) as num1 from tbl1
> where datefld between '1/1/2005' and 1/2/2005' Group By
> area having area = 'A'
> I was able to use your trick to get my positive or
> negative result using First and Last functions. Any
> suggestions appreciated if this is incorrect usage.
First? Last? You must be using Access ... This is a SQL Server group
Do you need a SQL Server (Transact-SQL) solution? Those fnctions do not
exist in T-SQL.
Bob Barrows
--
Microsoft MVP -- ASP/ASP.NET
Please reply to the newsgroup. The email account listed in my From
header is my spam trap, so I don't check it very often. You will get a
quicker response by posting to the newsgroup.|||On Fri, 25 Feb 2005 11:19:41 -0800, Ron wrote:

>Thanks. That is pretty . I forgot to include a
>twist in here. I also have a datefld. So num1 may be min
>or num may be max. I have to show +num or -num.
>select area, (First(num) - Last(num)) as num1 from tbl1
>where datefld between '1/1/2005' and 1/2/2005' Group By
>area having area = 'A'
>I was able to use your trick to get my positive or
>negative result using First and Last functions. Any
>suggestions appreciated if this is incorrect usage.
Hi Ron,
Try if this helps:
SELECT G.Area, F.num - L.num AS num1
FROM (SELECT area, MIN(datefld) AS FDate, MAX(datefld) AS LDate
FROM tbl1
WHERE datefld BETWEEN '20050101' AND '20050201'
GROUP BY area) AS G
INNER JOIN tbl1 AS F
ON F.area = G.area
AND F.datefld = G.FDate
INNER JOIN tbl1 AS L
ON L.area = G.area
AND L.datefld = G.LDate
WHERE G.area = 'A'
Best, Hugo
--
(Remove _NO_ and _SPAM_ to get my e-mail address)|||SELECT A.area, A.num-B.num
FROM Tbl1 AS A
JOIN Tbl1 AS B
ON A.datefld < B.datefld
AND A.area = 'A'
AND B.area = 'A'
David Portas
SQL Server MVP
--|||Yes, I figured that out. I was writing the sql in Access
and transferring in to Query Analyzer. Sorry bout that.
I did end up creating a udf for first and last.

>--Original Message--
>Ron wrote:
min
>First? Last? You must be using Access ... This is a SQL
Server group
>Do you need a SQL Server (Transact-SQL) solution? Those
fnctions do not
>exist in T-SQL.
>
>Bob Barrows
>--
>Microsoft MVP -- ASP/ASP.NET
>Please reply to the newsgroup. The email account listed
in my From
>header is my spam trap, so I don't check it very often.
You will get a
>quicker response by posting to the newsgroup.
>
>.
>|||Thanks. I will give that a try.

>--Original Message--
>On Fri, 25 Feb 2005 11:19:41 -0800, Ron wrote:
>
min
>Hi Ron,
>Try if this helps:
>SELECT G.Area, F.num - L.num AS num1
>FROM (SELECT area, MIN(datefld) AS FDate, MAX
(datefld) AS LDate
> FROM tbl1
> WHERE datefld BETWEEN '20050101'
AND '20050201'
> GROUP BY area) AS G
>INNER JOIN tbl1 AS F
> ON F.area = G.area
> AND F.datefld = G.FDate
>INNER JOIN tbl1 AS L
> ON L.area = G.area
> AND L.datefld = G.LDate
>WHERE G.area = 'A'
>
>Best, Hugo
>--
>(Remove _NO_ and _SPAM_ to get my e-mail address)
>.
>|||Thanks very much for your reply. I will give this a try.

>--Original Message--
>SELECT A.area, A.num-B.num
> FROM Tbl1 AS A
> JOIN Tbl1 AS B
> ON A.datefld < B.datefld
> AND A.area = 'A'
> AND B.area = 'A'
>--
>David Portas
>SQL Server MVP
>--
>.
>

Wednesday, March 28, 2012

How To Determine Total Number of Pages at Runtime?

It's no secret that the number of pages in a rendered report varies depending on the format. I have no problem getting the total number of pages for reports rendered in image formats from the web service, but I can't figure out how to get the number of pages for reports rendered in HTML.

I've always been under the impression that the Report Manager that ships with SSRS uses the same web service (reportservice.asmx) and IT can get the number of HTML pages, so it has to be possible.

Does anyone know how to do it?

Bump.|||

I now have a goofy workaround in place that I'll outline here, but I'd still like to know the "right" way to get the total number of pages from the web service.

In case someone is interested, my workaround is:

1. Add a textbox to the footer with the expression:

"***pages: " & Globals!TotalPages & "***"

2. Set the color of the textbox to match the background color (white, in this case).

3. Convert the byte array returned from the ReportingService.Render method to a string.

4. Pick out the number of pages with:

reportText.Substring(reportText.LastIndexOf("***pages: ")+10, reportText.LastIndexOf("***")-reportText.LastIndexOf("***pages: ")-10)

Like I said, goofy, but it will have to do for now.|||

If you would like to see an even goofier workaround, with somewhat more flexibility and potential, you may want to read this thread:

http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1807270&SiteID=1

>L<

How To Determine Total Number of Pages at Runtime?

It's no secret that the number of pages in a rendered report varies depending on the format. I have no problem getting the total number of pages for reports rendered in image formats from the web service, but I can't figure out how to get the number of pages for reports rendered in HTML.

I've always been under the impression that the Report Manager that ships with SSRS uses the same web service (reportservice.asmx) and IT can get the number of HTML pages, so it has to be possible.

Does anyone know how to do it?

Bump.|||

I now have a goofy workaround in place that I'll outline here, but I'd still like to know the "right" way to get the total number of pages from the web service.

In case someone is interested, my workaround is:

1. Add a textbox to the footer with the expression:

"***pages: " & Globals!TotalPages & "***"

2. Set the color of the textbox to match the background color (white, in this case).

3. Convert the byte array returned from the ReportingService.Render method to a string.

4. Pick out the number of pages with:

reportText.Substring(reportText.LastIndexOf("***pages: ")+10, reportText.LastIndexOf("***")-reportText.LastIndexOf("***pages: ")-10)

Like I said, goofy, but it will have to do for now.|||

If you would like to see an even goofier workaround, with somewhat more flexibility and potential, you may want to read this thread:

http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1807270&SiteID=1

>L<

sql

How To Determine Total Number of Pages at Runtime?

It's no secret that the number of pages in a rendered report varies depending on the format. I have no problem getting the total number of pages for reports rendered in image formats from the web service, but I can't figure out how to get the number of pages for reports rendered in HTML.

I've always been under the impression that the Report Manager that ships with SSRS uses the same web service (reportservice.asmx) and IT can get the number of HTML pages, so it has to be possible.

Does anyone know how to do it?

Bump.|||

I now have a goofy workaround in place that I'll outline here, but I'd still like to know the "right" way to get the total number of pages from the web service.

In case someone is interested, my workaround is:

1. Add a textbox to the footer with the expression:

"***pages: " & Globals!TotalPages & "***"

2. Set the color of the textbox to match the background color (white, in this case).

3. Convert the byte array returned from the ReportingService.Render method to a string.

4. Pick out the number of pages with:

reportText.Substring(reportText.LastIndexOf("***pages: ")+10, reportText.LastIndexOf("***")-reportText.LastIndexOf("***pages: ")-10)

Like I said, goofy, but it will have to do for now.|||

If you would like to see an even goofier workaround, with somewhat more flexibility and potential, you may want to read this thread:

http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1807270&SiteID=1

>L<

How to determine the number of cluster for the my clustering models?

Hi, all here,

Thank you very much for your kind attention.

Is there any good way to determine the number of clusters for the clustering models?

Really looking forward to hearing from you for your guidance.

Thanks a lot.

With best regards,

Yours sincerely,

If you set the CLUSTER_COUNT parameter to 0, then the algorithm will try to determine automatically the number of clusters.

Also, you could try to set CLUSTER_COUNT to a large value (say, 30). The algorithm will start looking for 30 clusters, then merge those that are really close, so the result will be less or equal to 30, and will give you an idea of how many actual clusters seem to exist in your data. You can also use the MINIMUM_SUPPORT parameter to add further restrictions to the clusters detected by the algorithm

|||

Hi, Bogdan, thank you very much for your guidance.

Best regards,

Monday, March 26, 2012

How to determine licensing mode and number of licenses in SQL 2005

I'm trying to find out how my SQL 2005 server's licensing is set up. I
don't see it in the properties of the server and when I query
serverproperties, it says licenseType returns disabled and NumLicenses
returns NULL. In SQL 2000, there was a Control Panel applet, but it's not
there for SQL 2005.
Thanks for your help!Hi
This was an old problem with SQL2000 prior to SP2
http://support.microsoft.com/?kbid=291332
If you are using SQL 2005 Developer edition then you may not have a license
type as these don't support standard licencing e.g.
SELECT
CAST( SERVERPROPERTY('productversion') AS varchar(15)) AS productversion,
CAST( SERVERPROPERTY ('productlevel') AS varchar(15)) AS productlevel,
CAST( SERVERPROPERTY ('edition') AS varchar(20)) AS edition,
CAST( SERVERPROPERTY ('licensetype') AS varchar(15)) AS licensetype,
CAST( SERVERPROPERTY ('numlicenses') AS varchar(15)) AS Numlicenses
productversion productlevel edition licensetype
Numlicenses
-- -- -- --
--
9.00.2047.00 SP1 Developer Edition DISABLED NULL
John
"Nieves" wrote:

> I'm trying to find out how my SQL 2005 server's licensing is set up. I
> don't see it in the properties of the server and when I query
> serverproperties, it says licenseType returns disabled and NumLicenses
> returns NULL. In SQL 2000, there was a Control Panel applet, but it's not
> there for SQL 2005.
> Thanks for your help!
>
>sql

How to determine licensing mode and number of licenses in SQL 2005

I'm trying to find out how my SQL 2005 server's licensing is set up. I
don't see it in the properties of the server and when I query
serverproperties, it says licenseType returns disabled and NumLicenses
returns NULL. In SQL 2000, there was a Control Panel applet, but it's not
there for SQL 2005.
Thanks for your help!Hi
This was an old problem with SQL2000 prior to SP2
http://support.microsoft.com/?kbid=291332
If you are using SQL 2005 Developer edition then you may not have a license
type as these don't support standard licencing e.g.
SELECT
CAST( SERVERPROPERTY('productversion') AS varchar(15)) AS productversion,
CAST( SERVERPROPERTY ('productlevel') AS varchar(15)) AS productlevel,
CAST( SERVERPROPERTY ('edition') AS varchar(20)) AS edition,
CAST( SERVERPROPERTY ('licensetype') AS varchar(15)) AS licensetype,
CAST( SERVERPROPERTY ('numlicenses') AS varchar(15)) AS Numlicenses
productversion productlevel edition licensetype
Numlicenses
-- -- -- --
--
9.00.2047.00 SP1 Developer Edition DISABLED NULL
John
"Nieves" wrote:
> I'm trying to find out how my SQL 2005 server's licensing is set up. I
> don't see it in the properties of the server and when I query
> serverproperties, it says licenseType returns disabled and NumLicenses
> returns NULL. In SQL 2000, there was a Control Panel applet, but it's not
> there for SQL 2005.
> Thanks for your help!
>
>

How to determine last "monthversary" date of an account?

I work on a project where advertisers on a classifieds Web site have the
possibility to place a certain number of ads per month.
The difficulty comes from the fact that a month period starts at each
"monthversary", meaning that if somebody created his account on June 15, I
would need to take into account the ads placed since the 15th of this
month...
I am simply trying to see how I can extract, in a very compact way, the last
"monthversary" date knowing the date the account was created and the current
date.
Right now I am using a method that works: I extract the day from the
creation date, prepend the current month and append the year, then:
1- if the "monthversary" is after today's date, go back one month
2- take care of the 30-day months issue and of of February as well (even
leap year)
3- take care of the year changes
And then I have a string that represents the last "monthversary" date, but I
am sure there is a simple, one-liner way to do this.
Thanks a lot!White,
Can you post the DDL and sample data? Sounds like the MAX function may work
here.
HTH
Jerry
"White Echo" <nospam_nicolas@.whiteecho.com_nospam> wrote in message
news:435922b5$0$3767$39cecf19@.news.twtelecom.net...
>I work on a project where advertisers on a classifieds Web site have the
>possibility to place a certain number of ads per month.
> The difficulty comes from the fact that a month period starts at each
> "monthversary", meaning that if somebody created his account on June 15, I
> would need to take into account the ads placed since the 15th of this
> month...
> I am simply trying to see how I can extract, in a very compact way, the
> last "monthversary" date knowing the date the account was created and the
> current date.
> Right now I am using a method that works: I extract the day from the
> creation date, prepend the current month and append the year, then:
> 1- if the "monthversary" is after today's date, go back one month
> 2- take care of the 30-day months issue and of of February as well (even
> leap year)
> 3- take care of the year changes
> And then I have a string that represents the last "monthversary" date, but
> I am sure there is a simple, one-liner way to do this.
> Thanks a lot!
>|||lookup datedd and datepart in BOL
select dateadd(m,-1,getdate())
http://sqlservercode.blogspot.com/
"White Echo" wrote:

> I work on a project where advertisers on a classifieds Web site have the
> possibility to place a certain number of ads per month.
> The difficulty comes from the fact that a month period starts at each
> "monthversary", meaning that if somebody created his account on June 15, I
> would need to take into account the ads placed since the 15th of this
> month...
> I am simply trying to see how I can extract, in a very compact way, the la
st
> "monthversary" date knowing the date the account was created and the curre
nt
> date.
> Right now I am using a method that works: I extract the day from the
> creation date, prepend the current month and append the year, then:
> 1- if the "monthversary" is after today's date, go back one month
> 2- take care of the 30-day months issue and of of February as well (even
> leap year)
> 3- take care of the year changes
> And then I have a string that represents the last "monthversary" date, but
I
> am sure there is a simple, one-liner way to do this.
> Thanks a lot!
>
>|||Sorry, different computer if you see what I mean.
But the function is something that I could also use at this computer.
Simply put:
If I opened my account on June 15 2005, what function would help me to
determine what would be the day of the beginning of the current account
period, knowing that an accounting period starts at each "monthversary"?
(By the way I was surprised to see that the expression "monthversary" is out
there).
"Jerry Spivey" <jspivey@.vestas-awt.com> wrote in message
news:%23zVNfTm1FHA.2076@.TK2MSFTNGP14.phx.gbl...
> White,
> Can you post the DDL and sample data? Sounds like the MAX function may
> work here.
> HTH
> Jerry
> "White Echo" <nospam_nicolas@.whiteecho.com_nospam> wrote in message
> news:435922b5$0$3767$39cecf19@.news.twtelecom.net...
>|||Nicolas,
Sometimes data works better than narratives. Could you post me some sample
data i.e, here is the date the account was opened, here is the monthversary,
and here is the date I want with x being the current date? Sample data -->
desired results?
Thanks
Jerry
"Nicolas Verhaeghe - White Echo" <nospam_nicolas@.whiteecho.com_nospam> wrote
in message news:435930ec$0$3759$39cecf19@.news.twtelecom.net...
> Sorry, different computer if you see what I mean.
> But the function is something that I could also use at this computer.
> Simply put:
> If I opened my account on June 15 2005, what function would help me to
> determine what would be the day of the beginning of the current account
> period, knowing that an accounting period starts at each "monthversary"?
> (By the way I was surprised to see that the expression "monthversary" is
> out there).
> "Jerry Spivey" <jspivey@.vestas-awt.com> wrote in message
> news:%23zVNfTm1FHA.2076@.TK2MSFTNGP14.phx.gbl...
>|||This only removes on month from Today's date... It does not help.
> lookup datedd and datepart in BOL
> select dateadd(m,-1,getdate())
> http://sqlservercode.blogspot.com/
> "White Echo" wrote:
>|||I thought I did this, I am sorry.
For instance:
Account created on June 15, 2005.
Today's date: October 21, 2005.
The result here would be: October 15, 2005
Account created on January 31, 2004.
Today's date: October 21, 2005.
The result here would be: September 30, 2005
If the account is created on June 15, 2005...
The first "month" started on July 15, 2004.
The second "month" on August 15, 2004
Etc...
But what I need to calculate is when the current "month" started for this
account.
The start day of a month is not the first day of a month, but rather what I
call the "monthversary": the same day number as that of the creation date.
"Jerry Spivey" <jspivey@.vestas-awt.com> wrote in message
news:elZhW9m1FHA.904@.tk2msftngp13.phx.gbl...
> Nicolas,
> Sometimes data works better than narratives. Could you post me some
> sample data i.e, here is the date the account was opened, here is the
> monthversary, and here is the date I want with x being the current date?
> Sample data --> desired results?
> Thanks
> Jerry
> "Nicolas Verhaeghe - White Echo" <nospam_nicolas@.whiteecho.com_nospam>
> wrote in message news:435930ec$0$3759$39cecf19@.news.twtelecom.net...
>|||On Fri, 21 Oct 2005 10:17:33 -0700, White Echo wrote:
(snip)
>Right now I am using a method that works: I extract the day from the
>creation date, prepend the current month and append the year, then:
>1- if the "monthversary" is after today's date, go back one month
>2- take care of the 30-day months issue and of of February as well (even
>leap year)
>3- take care of the year changes
>And then I have a string that represents the last "monthversary" date, but
I
>am sure there is a simple, one-liner way to do this.
Hi White Echo,
Not sure if it's simpler, but you could write it in one line (though I
prefer slightly more formatting - read this emssage with a fixed font
for best effect), and it has the definite advantage that it can be used
in a query to process all rows at once (though my example uses only a
variable):
DECLARE @.StartDate datetime
SET @.StartDate = '20050615'
SELECT DATEADD(month,
DATEDIFF(month,
@.StartDate,
CURRENT_TIMESTAMP)
- CASE WHEN DAY(@.StartDate) > DAY(CURRENT_TIMESTAMP)
THEN 1
ELSE 0
END,
@.StartDate)
Best, Hugo
--
(Remove _NO_ and _SPAM_ to get my e-mail address)|||Thank you very much, my friend!
"Hugo Kornelis" <hugo@.pe_NO_rFact.in_SPAM_fo> wrote in message
news:7mmil1t3gtgk6ktgcisgteocp120egtvlh@.
4ax.com...
> On Fri, 21 Oct 2005 10:17:33 -0700, White Echo wrote:
> (snip)
> Hi White Echo,
> Not sure if it's simpler, but you could write it in one line (though I
> prefer slightly more formatting - read this emssage with a fixed font
> for best effect), and it has the definite advantage that it can be used
> in a query to process all rows at once (though my example uses only a
> variable):
> DECLARE @.StartDate datetime
> SET @.StartDate = '20050615'
> SELECT DATEADD(month,
> DATEDIFF(month,
> @.StartDate,
> CURRENT_TIMESTAMP)
> - CASE WHEN DAY(@.StartDate) > DAY(CURRENT_TIMESTAMP)
> THEN 1
> ELSE 0
> END,
> @.StartDate)
>
> Best, Hugo
> --
> (Remove _NO_ and _SPAM_ to get my e-mail address)

Friday, March 23, 2012

How to determine Count of ties in MDX?

I need to determine the number of values in a set that are non-unique in the set.

In SQL, I would do the following:

select sum(value_count) as Ties

from (select value, count(*) as value_count

from source

group by value

having count(*) >1

)

In MDX, I have a set defined in a query that is passed into several custom statistical functions. I would like to be able to accomplish this without writing another external function, as it seems the sort of thing that should be easy...

Here is the query I'm trying to plug this into. Suggestions welcome.

with

set [data] as ( nonempty({

[Sample Date].[Time].[Day] }) *{ [Measures].[Parm Value] } )

MEMBER [Sen's Slope] as 'Statistics.Sen_Slope({[data]})'

MEMBER [Kendall's Tau] as 'Statistics.KENDALLS_TAU({[data]})'

MEMBER [Significant] as 'Statistics.Significance({[data]})'

MEMBER [MK_Z] as 'Statistics.Mann_Kendall_Z({[data]})'

member [measures].[Samples] as [data].count

member [measures].[Average] as avg([data])

member [measures].[Median] as Median([data])

member [measures].[Last Sample] as tail([data],1).item(0)

MEMBER [Ties] as '0'

select {[Samples],[Average],[Median],[Last Sample], [Kendall's Tau], [Sen's Slope], [MK_Z], [Significant], [Ties] } on 0

FROM ( SELECT ( [Sample Date].[Time].[2002 Q4]:[Sample Date].[Time].[2006 Q3] ) on 0,

{([Site Hierarchy].[Site Hierarchy].[Site ID].[0829SD6001] ,

[Analysis Parameter].[Analysis Parameter].[Acidity (ACD)])} ON 1

FROM [Sample Data])

;

Hi Clayton,

This sample from Adventure Works, where value is [Reseller Order Quantity], seems to work:

SQL query:

>>

select sum(order_count) as Ties
from
(select OrderQuantity, count(*) as order_count
from
(select ProductKey, sum(OrderQuantity) as OrderQuantity
from dbo.FactResellerSales
group by ProductKey) ps
group by OrderQuantity
having count(*) > 1) oc

87

>>

MDX query:

>>

With

Member [Measures].[PrdTies] as

Count(Filter(Order(NonEmpty(

[Product].[Product].[Product].Members,

{[Measures].[Reseller Order Quantity]}),

[Measures].[Reseller Order Quantity], BDESC) as OrdPrds,

(OrdPrds.CurrentOrdinal < OrdPrds.Count

And [Measures].[Reseller Order Quantity] =

([Measures].[Reseller Order Quantity],

OrdPrds.Item(OrdPrds.CurrentOrdinal)))

OR (OrdPrds.CurrentOrdinal > 1

And [Measures].[Reseller Order Quantity] =

([Measures].[Reseller Order Quantity],

OrdPrds.Item(OrdPrds.CurrentOrdinal-2)))))

select {[Measures].[PrdTies]} on 0

from [Adventure Works]

PrdTies
87

>>

|||

Deepak,

Thanks for the thourough response. I've done some testing, comparing results from the MDX you wrote to the ADOMD CLR proc I wrote, and I was getting different results. I've traced through the CLR version and manually counted the values in the set, and the CLR proc was correct. I've clipped out the relevant code in case you want to compare results. It may be the differences in how I'm calling the CLR functions by passing in a set versus the Measure method, which is working over the complete set of data from the subcube query.

Here is your test MDX query, with a measure added for the CLR function. In this case, both methods return the same count, as expected. I'm just curious as to what might be causing me to get dfferent counts between the two methods when used in my cube...

With

set [data] as ( NonEmpty([Product].[Product].[Product].Members)

*([Measures].[Reseller Order Quantity]) )

member [CountOfTies] as 'Statistics.CountOfTies({[data]})'

Member [Measures].[PrdTies] as

Count(Filter(Order(NonEmpty(

[Product].[Product].[Product].Members,

{[Measures].[Reseller Order Quantity]}),

[Measures].[Reseller Order Quantity], BDESC) as OrdPrds,

(OrdPrds.CurrentOrdinal < OrdPrds.Count

And [Measures].[Reseller Order Quantity] =

([Measures].[Reseller Order Quantity],

OrdPrds.Item(OrdPrds.CurrentOrdinal)))

OR (OrdPrds.CurrentOrdinal > 1

And [Measures].[Reseller Order Quantity] =

([Measures].[Reseller Order Quantity],

OrdPrds.Item(OrdPrds.CurrentOrdinal-2)))))

select {[Measures].[PrdTies], [CountOfTies]} on 0

from [Adventure Works];

Assembly code:

using System;

using System.Collections;

using Microsoft.AnalysisServices;

using Microsoft.AnalysisServices.AdomdServer;

namespace Statistics

{

public sealed class Statistics

{

private Statistics()

{

}

[CLSCompliant(false)]

// function to return a sum of the counts for tied values

public static Object CountOfTies(Set data1)

{

try

{

//number of Tuples in the set

Int32 v = data1.Tuples.Count;

if (v > 1)

{

//dimension a new array to hold values for passing into GetCountOfTies()

Double[] ValueArray;

ValueArray = new Double[v];

MDXValue mdxval;

Int32 i = 0;

// convert tuple set into an array

foreach (Tuple t in data1.Tuples)

{

mdxval = t;

ValueArray[i++] = mdxval.ToDouble();

}

// get array of any ties

Int32[] ResultArray = GetCountOfTies(ValueArray);

//sum counts to get results to return

i = 0;

foreach (Int32 j in ResultArray)

{i = i + j;}

return i;

}

else {return 0;}

}

catch (Exception e)

{

Console.WriteLine(e);

return "ERROR";

}

}

private static Int32[] GetCountOfTies(double[] doubleArray)

{

//create an array of counts of unique values, where there are ties in values.

//the resulting array will contain one element for each value with ties.

Array.Sort(doubleArray);

ArrayList numbers = new ArrayList();

double? lastVal = null;

int currentCount = 0;

foreach (double val in doubleArray)

{

if (lastVal != null && lastVal != val)

{

if (currentCount > 1)

numbers.Add(currentCount);

currentCount = 1;

}

else

{currentCount++;}

lastVal = val;

}

return (Int32[])numbers.ToArray(typeof(Int32));

}

}

}

Monday, March 19, 2012

How to design SP with variable number of params?

I have a form that allows a user to update contact info. For example:
First name
Last name
PO Box
City
State
There are actually more fields (up to 50) but I have only used five for
simplicity. Sometimes a user will submit an update for all fields.
However, for a web service, some one may only send the First Name or any
other one field. In that case, is it better to design an SP for each case?
I see that having scaling issues.
Another approach is to design one SP with many conditionals (50). Both
approaches are inefficient. What is a better way?
Thanks,
BrettSpecify default values for your parameters. I.e.,
CREATE PROCEDURE sample
@.paramLast VARCHAR(30) = NULL, -- NULL default value
@.paramFirst VARCHAR(30) = NULL, -- NULL default value
@.paramPoBox VARCHAR(30) = NULL,
@.paramCity VARCHAR(30) = '', -- Empty string default value
@.paramState CHAR(2) = 'NY' -- 'NY' default value
It will be a little tedious for 50 fields, but will allow you to not specify
parameters on calling.
"Brett" <no@.spam.net> wrote in message
news:OkwoMaUGFHA.2676@.TK2MSFTNGP12.phx.gbl...
>I have a form that allows a user to update contact info. For example:
> First name
> Last name
> PO Box
> City
> State
> There are actually more fields (up to 50) but I have only used five for
> simplicity. Sometimes a user will submit an update for all fields.
> However, for a web service, some one may only send the First Name or any
> other one field. In that case, is it better to design an SP for each
> case? I see that having scaling issues.
> Another approach is to design one SP with many conditionals (50). Both
> approaches are inefficient. What is a better way?
> Thanks,
> Brett
>|||Michael C# wrote:
> Specify default values for your parameters. I.e.,
> CREATE PROCEDURE sample
> @.paramLast VARCHAR(30) = NULL, -- NULL default value
> @.paramFirst VARCHAR(30) = NULL, -- NULL default value
> @.paramPoBox VARCHAR(30) = NULL,
> @.paramCity VARCHAR(30) = '', -- Empty string default
> value @.paramState CHAR(2) = 'NY' -- 'NY' default
> value
> It will be a little tedious for 50 fields, but will allow you to not
> specify parameters on calling.
>
I'm not sure that will work for the OP for updating.
Specify all updatable values in the parameter list. 50 is a lot, and I
might question the number of attributes on the underlying table. Unless
you're dealing with more than one table and could break up the updates
in a meaningful way.
David Gugick
Imceda Software
www.imceda.com|||Commonly we would just update all data on an update in the stored procedure
unless there is a great reason not to. You could do something like:
CREATE PROCEDURE TABLE_UPDATE
@.LastName VARCHAR(30) = NULL,
@.FirstName VARCHAR(30) = NULL,
as
update table
set lastName = coalesce(@.lastName, lastName),
firstName = coalesce(@.firstName, firstName)
go
Then if you call it with table_update @.firstName ='Bob'
The current value of lastName will be used, and the new value for
@.firstName.
----
Louis Davidson - drsql@.hotmail.com
SQL Server MVP
Compass Technology Management - www.compass.net
Pro SQL Server 2000 Database Design -
http://www.apress.com/book/bookDisplay.html?bID=266
Blog - http://spaces.msn.com/members/drsql/
Note: Please reply to the newsgroups only unless you are interested in
consulting services. All other replies may be ignored :)
"Brett" <no@.spam.net> wrote in message
news:OkwoMaUGFHA.2676@.TK2MSFTNGP12.phx.gbl...
>I have a form that allows a user to update contact info. For example:
> First name
> Last name
> PO Box
> City
> State
> There are actually more fields (up to 50) but I have only used five for
> simplicity. Sometimes a user will submit an update for all fields.
> However, for a web service, some one may only send the First Name or any
> other one field. In that case, is it better to design an SP for each
> case? I see that having scaling issues.
> Another approach is to design one SP with many conditionals (50). Both
> approaches are inefficient. What is a better way?
> Thanks,
> Brett
>|||there is one thing that bothers me with this approach (regardles of number
of fields). the thing is that on update, event if the value for the column
is unchanged, the constraints are being checked all the same. eg, if there
is a foreign key constraint, updating a fk column (with the same value, thus
in fact not updating at all) will cause a lookup in the referenced table,
which is absolutely unnecessary, imho. but the alternatives - dynamically
constructing the update statement, or creating a separate statement for
every combination of params - make even less sense.
any thoughts?
dean
"Louis Davidson" <dr_dontspamme_sql@.hotmail.com> wrote in message
news:%23sEA5TWGFHA.4088@.TK2MSFTNGP09.phx.gbl...
> Commonly we would just update all data on an update in the stored
procedure
> unless there is a great reason not to. You could do something like:
> CREATE PROCEDURE TABLE_UPDATE
> @.LastName VARCHAR(30) = NULL,
> @.FirstName VARCHAR(30) = NULL,
> as
> update table
> set lastName = coalesce(@.lastName, lastName),
> firstName = coalesce(@.firstName, firstName)
> go
> Then if you call it with table_update @.firstName ='Bob'
> The current value of lastName will be used, and the new value for
> @.firstName.
>
> --
> ----
--
> Louis Davidson - drsql@.hotmail.com
> SQL Server MVP
> Compass Technology Management - www.compass.net
> Pro SQL Server 2000 Database Design -
> http://www.apress.com/book/bookDisplay.html?bID=266
> Blog - http://spaces.msn.com/members/drsql/
> Note: Please reply to the newsgroups only unless you are interested in
> consulting services. All other replies may be ignored :)
> "Brett" <no@.spam.net> wrote in message
> news:OkwoMaUGFHA.2676@.TK2MSFTNGP12.phx.gbl...
>|||This seems to be the best approach of the posts here. I see there probably
isn't a way to get around conditionals for NULL checks. coalesce is a type
of conditional but probably better than using multiple IF statements
correct?
Thanks,
Brett
"Louis Davidson" <dr_dontspamme_sql@.hotmail.com> wrote in message
news:%23sEA5TWGFHA.4088@.TK2MSFTNGP09.phx.gbl...
> Commonly we would just update all data on an update in the stored
> procedure unless there is a great reason not to. You could do something
> like:
> CREATE PROCEDURE TABLE_UPDATE
> @.LastName VARCHAR(30) = NULL,
> @.FirstName VARCHAR(30) = NULL,
> as
> update table
> set lastName = coalesce(@.lastName, lastName),
> firstName = coalesce(@.firstName, firstName)
> go
> Then if you call it with table_update @.firstName ='Bob'
> The current value of lastName will be used, and the new value for
> @.firstName.
>
> --
> ----
--
> Louis Davidson - drsql@.hotmail.com
> SQL Server MVP
> Compass Technology Management - www.compass.net
> Pro SQL Server 2000 Database Design -
> http://www.apress.com/book/bookDisplay.html?bID=266
> Blog - http://spaces.msn.com/members/drsql/
> Note: Please reply to the newsgroups only unless you are interested in
> consulting services. All other replies may be ignored :)
> "Brett" <no@.spam.net> wrote in message
> news:OkwoMaUGFHA.2676@.TK2MSFTNGP12.phx.gbl...
>|||"David Gugick" <davidg-nospam@.imceda.com> wrote in message
news:%2359VcIWGFHA.524@.TK2MSFTNGP14.phx.gbl...
> Michael C# wrote:
> I'm not sure that will work for the OP for updating.
>
Why not? Here's an example of a stored procedure, with a variable number of
params, that updates a table.
--Create Table and Primary Key
CREATE TABLE [dbo].[Table1] (
[IDNum] [int] NOT NULL ,
[LastName] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[FirstName] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[Table1] WITH NOCHECK ADD
CONSTRAINT [PK_Table1] PRIMARY KEY CLUSTERED
(
[IDNum]
) ON [PRIMARY]
GO
--Populate table
INSERT INTO Table1 (IDNum, LastName, FirstName) VALUES (0, 'Jetson',
'George')
INSERT INTO Table1 (IDNum, LastName, FirstName) VALUES (1, 'Flintstone',
'Fred')
INSERT INTO Table1 (IDNum, LastName, FirstName) VALUES (2, 'Rubble',
'Barney')
GO
--Create stored procedure with variable number of parameters
CREATE PROCEDURE usp_UpdateRecord
@.paramID INT,
@.paramLast VARCHAR(50) = NULL,
@.paramFirst VARCHAR(50) = NULL
AS
UPDATE Table1 SET LastName = @.paramLast
WHERE IDNum = @.paramID
AND @.paramLast IS NOT NULL
UPDATE Table1 SET FirstName = @.paramFirst
WHERE IDNum = @.paramID
AND @.paramFirst IS NOT NULL
GO
--Now call the stored procedure with a variable
--number of parameters each time
EXEC usp_UpdateRecord @.paramID = 0, @.paramLast = 'Johnson'
EXEC usp_UpdateRecord @.paramID = 1, @.paramFirst = 'Wilma'
EXEC usp_UpdateRecord @.paramID = 2, @.paramLast = 'Public', @.paramFirst =
'John'
GO

> Specify all updatable values in the parameter list. 50 is a lot, and I
> might question the number of attributes on the underlying table. Unless
> you're dealing with more than one table and could break up the updates in
> a meaningful way.
>
> --
> David Gugick
> Imceda Software
> www.imceda.com|||I personally would not recommend you design a procedure to perform up to
50 distinct updates to update a single row in the table. Seems more work
and overhead than a single update to me.
David G.|||Are you talking about the overhead incurred when typing in the code once, or
the overhead incurred each time you UPDATE 50 fields in order to change one?
Michael C.
"David Gugick" <davidg-nospam@.imceda.com> wrote in message
news:eunWozbGFHA.3112@.tk2msftngp13.phx.gbl...
>I personally would not recommend you design a procedure to perform up to 50
>distinct updates to update a single row in the table. Seems more work and
>overhead than a single update to me.
> --
> David G.
>|||Michael C# wrote:
> Are you talking about the overhead incurred when typing in the code
> once, or the overhead incurred each time you UPDATE 50 fields in
> order to change one?
> Michael C.
I just mean the possibly running up to 50 individual updates to satisfy
what a single update can do. Plus, the implementation does not allow you
to return a column value to NULL, if needed.
My only real point here is issuing a single update and supplying all
parameters is generally the easiest, most maintainable, and safest
implementation. If the OP has a component in ASP.net or his/her
fat-client app that automates the execution of the update, then he only
has to write it once.
David G.

Wednesday, March 7, 2012

How to delete large number of record without matter with transaction log?

Hello,
It happens to me that I have control over a MSSQL 2000 server that was
looked after by another staff today. And than there is a call from the
server's owner company that the server's harddisk is running out of space.
As background information, the SQL server's running on a 5GB HDD
partition with the Win2k system dir on it. And after some inspection, I
found the "msdb" database occupies about 1.13GB and it's transaction log
occupies 2MB.
So I opened Enterprise Manager and looked into the tables one by one.
And found the 'sysdtssteplog' table has almost 7 million rows. So I run
"delete from sysdtssteplog" to delete it. After 15-20 minutes, the "Query
Analyzer"(I've explicitly called it to run the SQL statement) tell me it
cannot finish the task because the disk is running out of space and no room
for transaction log. And when I see the file size, the transaction log file
of msdb has grown to over 200MB. Oops.
At least, I managed to found an unoccupied machine to install a temp SQL
server, copy the database file to, trancate, and put back to the origional
server. And the story is over. But what should I do if I experienced that
next time? There's management change in both my company and that company so
replacement of harddisk may not be feasible in a short time. And I'd like to
know if there's anything wrong in my procedure of handling the issue. This
is my first time to handle a SQL server, and I have tough time on this. I
used to be a programmer only.
Looking forward for any advice. Thanks a lot.
Regards,
Lau Lei Cheong
Vyas's example shows how to divide a "big" transaction into a small ones
SET ROWCOUNT 1000
WHILE 1 = 1
BEGIN
/*
DELETION here and Don't forget WHERE condition
*/
IF @.@.ROWCOUNT = 0
BEGIN
BREAK
END
ELSE
BEGIN
CHECKPOINT --Or doing BACKUP LOG File
END
END
SET ROWCOUNT 0
"Lau Lei Cheong" <leu_lc@.yehoo.com.hk> wrote in message
news:eSbLvFQjFHA.1464@.TK2MSFTNGP14.phx.gbl...
> Hello,
> It happens to me that I have control over a MSSQL 2000 server that was
> looked after by another staff today. And than there is a call from the
> server's owner company that the server's harddisk is running out of space.
> As background information, the SQL server's running on a 5GB HDD
> partition with the Win2k system dir on it. And after some inspection, I
> found the "msdb" database occupies about 1.13GB and it's transaction log
> occupies 2MB.
> So I opened Enterprise Manager and looked into the tables one by one.
> And found the 'sysdtssteplog' table has almost 7 million rows. So I run
> "delete from sysdtssteplog" to delete it. After 15-20 minutes, the "Query
> Analyzer"(I've explicitly called it to run the SQL statement) tell me it
> cannot finish the task because the disk is running out of space and no
room
> for transaction log. And when I see the file size, the transaction log
file
> of msdb has grown to over 200MB. Oops.
> At least, I managed to found an unoccupied machine to install a temp
SQL
> server, copy the database file to, trancate, and put back to the origional
> server. And the story is over. But what should I do if I experienced that
> next time? There's management change in both my company and that company
so
> replacement of harddisk may not be feasible in a short time. And I'd like
to
> know if there's anything wrong in my procedure of handling the issue. This
> is my first time to handle a SQL server, and I have tough time on this. I
> used to be a programmer only.
> Looking forward for any advice. Thanks a lot.
> Regards,
> Lau Lei Cheong
>
>
|||Hello Uri,
Thanks for your response.
One further question, why does the code use "WHILE 1 = 1" instead of
anything like "WHILE (TRUE)"? Is there any reason behind?
Regards,
Lau Lei Cheong
"Uri Dimant" <urid@.iscar.co.il> glsD:%23LDM8MQjFHA.3012@.TK2MSFTNGP12.phx .gbl...
> Vyas's example shows how to divide a "big" transaction into a small ones
> SET ROWCOUNT 1000
> WHILE 1 = 1
> BEGIN
> /*
> DELETION here and Don't forget WHERE condition
> */
> IF @.@.ROWCOUNT = 0
> BEGIN
> BREAK
> END
> ELSE
> BEGIN
> CHECKPOINT --Or doing BACKUP LOG File
> END
> END
> SET ROWCOUNT 0
> "Lau Lei Cheong" <leu_lc@.yehoo.com.hk> wrote in message
> news:eSbLvFQjFHA.1464@.TK2MSFTNGP14.phx.gbl...
> room
> file
> SQL
> so
> to
>
|||1=1 is TRUE condition but if @.@.rowcount=0 we exit from the loop.
You can build your own logic to fetch the rows
"Lau Lei Cheong" <leu_lc@.yehoo.com.hk> wrote in message
news:e8UVyiQjFHA.2852@.TK2MSFTNGP15.phx.gbl...
> Hello Uri,
> Thanks for your response.
> One further question, why does the code use "WHILE 1 = 1" instead of
> anything like "WHILE (TRUE)"? Is there any reason behind?
> Regards,
> Lau Lei Cheong
> "Uri Dimant" <urid@.iscar.co.il>
glsD:%23LDM8MQjFHA.3012@.TK2MSFTNGP12.phx .gbl...[vbcol=seagreen]
log[vbcol=seagreen]
one.[vbcol=seagreen]
"Query[vbcol=seagreen]
it[vbcol=seagreen]
temp[vbcol=seagreen]
that[vbcol=seagreen]
company[vbcol=seagreen]
like[vbcol=seagreen]
I
>

How to delete large number of record without matter with transaction log?

Hello,
It happens to me that I have control over a MSSQL 2000 server that was
looked after by another staff today. And than there is a call from the
server's owner company that the server's harddisk is running out of space.
As background information, the SQL server's running on a 5GB HDD
partition with the Win2k system dir on it. And after some inspection, I
found the "msdb" database occupies about 1.13GB and it's transaction log
occupies 2MB.
So I opened Enterprise Manager and looked into the tables one by one.
And found the 'sysdtssteplog' table has almost 7 million rows. So I run
"delete from sysdtssteplog" to delete it. After 15-20 minutes, the "Query
Analyzer"(I've explicitly called it to run the SQL statement) tell me it
cannot finish the task because the disk is running out of space and no room
for transaction log. And when I see the file size, the transaction log file
of msdb has grown to over 200MB. Oops.
At least, I managed to found an unoccupied machine to install a temp SQL
server, copy the database file to, trancate, and put back to the origional
server. And the story is over. But what should I do if I experienced that
next time? There's management change in both my company and that company so
replacement of harddisk may not be feasible in a short time. And I'd like to
know if there's anything wrong in my procedure of handling the issue. This
is my first time to handle a SQL server, and I have tough time on this. I
used to be a programmer only.
Looking forward for any advice. Thanks a lot.
Regards,
Lau Lei CheongVyas's example shows how to divide a "big" transaction into a small ones
SET ROWCOUNT 1000
WHILE 1 = 1
BEGIN
/*
DELETION here and Don't forget WHERE condition
*/
IF @.@.ROWCOUNT = 0
BEGIN
BREAK
END
ELSE
BEGIN
CHECKPOINT --Or doing BACKUP LOG File
END
END
SET ROWCOUNT 0
"Lau Lei Cheong" <leu_lc@.yehoo.com.hk> wrote in message
news:eSbLvFQjFHA.1464@.TK2MSFTNGP14.phx.gbl...
> Hello,
> It happens to me that I have control over a MSSQL 2000 server that was
> looked after by another staff today. And than there is a call from the
> server's owner company that the server's harddisk is running out of space.
> As background information, the SQL server's running on a 5GB HDD
> partition with the Win2k system dir on it. And after some inspection, I
> found the "msdb" database occupies about 1.13GB and it's transaction log
> occupies 2MB.
> So I opened Enterprise Manager and looked into the tables one by one.
> And found the 'sysdtssteplog' table has almost 7 million rows. So I run
> "delete from sysdtssteplog" to delete it. After 15-20 minutes, the "Query
> Analyzer"(I've explicitly called it to run the SQL statement) tell me it
> cannot finish the task because the disk is running out of space and no
room
> for transaction log. And when I see the file size, the transaction log
file
> of msdb has grown to over 200MB. Oops.
> At least, I managed to found an unoccupied machine to install a temp
SQL
> server, copy the database file to, trancate, and put back to the origional
> server. And the story is over. But what should I do if I experienced that
> next time? There's management change in both my company and that company
so
> replacement of harddisk may not be feasible in a short time. And I'd like
to
> know if there's anything wrong in my procedure of handling the issue. This
> is my first time to handle a SQL server, and I have tough time on this. I
> used to be a programmer only.
> Looking forward for any advice. Thanks a lot.
> Regards,
> Lau Lei Cheong
>
>|||Hello Uri,
Thanks for your response.
One further question, why does the code use "WHILE 1 = 1" instead of
anything like "WHILE (TRUE)"? Is there any reason behind?
Regards,
Lau Lei Cheong
"Uri Dimant" <urid@.iscar.co.il> glsD:%23LDM8MQjFHA.3012@.TK2MSFTNGP12.phx.gbl...[vb
col=seagreen]
> Vyas's example shows how to divide a "big" transaction into a small ones
> SET ROWCOUNT 1000
> WHILE 1 = 1
> BEGIN
> /*
> DELETION here and Don't forget WHERE condition
> */
> IF @.@.ROWCOUNT = 0
> BEGIN
> BREAK
> END
> ELSE
> BEGIN
> CHECKPOINT --Or doing BACKUP LOG File
> END
> END
> SET ROWCOUNT 0
> "Lau Lei Cheong" <leu_lc@.yehoo.com.hk> wrote in message
> news:eSbLvFQjFHA.1464@.TK2MSFTNGP14.phx.gbl...
> room
> file
> SQL
> so
> to
>[/vbcol]|||1=1 is TRUE condition but if @.@.rowcount=0 we exit from the loop.
You can build your own logic to fetch the rows
"Lau Lei Cheong" <leu_lc@.yehoo.com.hk> wrote in message
news:e8UVyiQjFHA.2852@.TK2MSFTNGP15.phx.gbl...
> Hello Uri,
> Thanks for your response.
> One further question, why does the code use "WHILE 1 = 1" instead of
> anything like "WHILE (TRUE)"? Is there any reason behind?
> Regards,
> Lau Lei Cheong
> "Uri Dimant" <urid@.iscar.co.il>
glsD:%23LDM8MQjFHA.3012@.TK2MSFTNGP12.phx.gbl...
log[vbcol=seagreen]
one.[vbcol=seagreen]
"Query[vbcol=seagreen]
it[vbcol=seagreen]
temp[vbcol=seagreen]
that[vbcol=seagreen]
company[vbcol=seagreen]
like[vbcol=seagreen]
I[vbcol=seagreen]
>

How to delete large number of record without matter with transaction log?

Hello,
It happens to me that I have control over a MSSQL 2000 server that was
looked after by another staff today. And than there is a call from the
server's owner company that the server's harddisk is running out of space.
As background information, the SQL server's running on a 5GB HDD
partition with the Win2k system dir on it. And after some inspection, I
found the "msdb" database occupies about 1.13GB and it's transaction log
occupies 2MB.
So I opened Enterprise Manager and looked into the tables one by one.
And found the 'sysdtssteplog' table has almost 7 million rows. So I run
"delete from sysdtssteplog" to delete it. After 15-20 minutes, the "Query
Analyzer"(I've explicitly called it to run the SQL statement) tell me it
cannot finish the task because the disk is running out of space and no room
for transaction log. And when I see the file size, the transaction log file
of msdb has grown to over 200MB. Oops.
At least, I managed to found an unoccupied machine to install a temp SQL
server, copy the database file to, trancate, and put back to the origional
server. And the story is over. But what should I do if I experienced that
next time? There's management change in both my company and that company so
replacement of harddisk may not be feasible in a short time. And I'd like to
know if there's anything wrong in my procedure of handling the issue. This
is my first time to handle a SQL server, and I have tough time on this. I
used to be a programmer only.
Looking forward for any advice. Thanks a lot.
Regards,
Lau Lei CheongVyas's example shows how to divide a "big" transaction into a small ones
SET ROWCOUNT 1000
WHILE 1 = 1
BEGIN
/*
DELETION here and Don't forget WHERE condition
*/
IF @.@.ROWCOUNT = 0
BEGIN
BREAK
END
ELSE
BEGIN
CHECKPOINT --Or doing BACKUP LOG File
END
END
SET ROWCOUNT 0
"Lau Lei Cheong" <leu_lc@.yehoo.com.hk> wrote in message
news:eSbLvFQjFHA.1464@.TK2MSFTNGP14.phx.gbl...
> Hello,
> It happens to me that I have control over a MSSQL 2000 server that was
> looked after by another staff today. And than there is a call from the
> server's owner company that the server's harddisk is running out of space.
> As background information, the SQL server's running on a 5GB HDD
> partition with the Win2k system dir on it. And after some inspection, I
> found the "msdb" database occupies about 1.13GB and it's transaction log
> occupies 2MB.
> So I opened Enterprise Manager and looked into the tables one by one.
> And found the 'sysdtssteplog' table has almost 7 million rows. So I run
> "delete from sysdtssteplog" to delete it. After 15-20 minutes, the "Query
> Analyzer"(I've explicitly called it to run the SQL statement) tell me it
> cannot finish the task because the disk is running out of space and no
room
> for transaction log. And when I see the file size, the transaction log
file
> of msdb has grown to over 200MB. Oops.
> At least, I managed to found an unoccupied machine to install a temp
SQL
> server, copy the database file to, trancate, and put back to the origional
> server. And the story is over. But what should I do if I experienced that
> next time? There's management change in both my company and that company
so
> replacement of harddisk may not be feasible in a short time. And I'd like
to
> know if there's anything wrong in my procedure of handling the issue. This
> is my first time to handle a SQL server, and I have tough time on this. I
> used to be a programmer only.
> Looking forward for any advice. Thanks a lot.
> Regards,
> Lau Lei Cheong
>
>|||Hello Uri,
Thanks for your response.
One further question, why does the code use "WHILE 1 = 1" instead of
anything like "WHILE (TRUE)"? Is there any reason behind?
Regards,
Lau Lei Cheong
"Uri Dimant" <urid@.iscar.co.il> ¼¶¼g©ó¶l¥ó·s»D:%23LDM8MQjFHA.3012@.TK2MSFTNGP12.phx.gbl...
> Vyas's example shows how to divide a "big" transaction into a small ones
> SET ROWCOUNT 1000
> WHILE 1 = 1
> BEGIN
> /*
> DELETION here and Don't forget WHERE condition
> */
> IF @.@.ROWCOUNT = 0
> BEGIN
> BREAK
> END
> ELSE
> BEGIN
> CHECKPOINT --Or doing BACKUP LOG File
> END
> END
> SET ROWCOUNT 0
> "Lau Lei Cheong" <leu_lc@.yehoo.com.hk> wrote in message
> news:eSbLvFQjFHA.1464@.TK2MSFTNGP14.phx.gbl...
>> Hello,
>> It happens to me that I have control over a MSSQL 2000 server that
>> was
>> looked after by another staff today. And than there is a call from the
>> server's owner company that the server's harddisk is running out of
>> space.
>> As background information, the SQL server's running on a 5GB HDD
>> partition with the Win2k system dir on it. And after some inspection, I
>> found the "msdb" database occupies about 1.13GB and it's transaction log
>> occupies 2MB.
>> So I opened Enterprise Manager and looked into the tables one by one.
>> And found the 'sysdtssteplog' table has almost 7 million rows. So I run
>> "delete from sysdtssteplog" to delete it. After 15-20 minutes, the "Query
>> Analyzer"(I've explicitly called it to run the SQL statement) tell me it
>> cannot finish the task because the disk is running out of space and no
> room
>> for transaction log. And when I see the file size, the transaction log
> file
>> of msdb has grown to over 200MB. Oops.
>> At least, I managed to found an unoccupied machine to install a temp
> SQL
>> server, copy the database file to, trancate, and put back to the
>> origional
>> server. And the story is over. But what should I do if I experienced that
>> next time? There's management change in both my company and that company
> so
>> replacement of harddisk may not be feasible in a short time. And I'd like
> to
>> know if there's anything wrong in my procedure of handling the issue.
>> This
>> is my first time to handle a SQL server, and I have tough time on this. I
>> used to be a programmer only.
>> Looking forward for any advice. Thanks a lot.
>> Regards,
>> Lau Lei Cheong
>>
>|||1=1 is TRUE condition but if @.@.rowcount=0 we exit from the loop.
You can build your own logic to fetch the rows
"Lau Lei Cheong" <leu_lc@.yehoo.com.hk> wrote in message
news:e8UVyiQjFHA.2852@.TK2MSFTNGP15.phx.gbl...
> Hello Uri,
> Thanks for your response.
> One further question, why does the code use "WHILE 1 = 1" instead of
> anything like "WHILE (TRUE)"? Is there any reason behind?
> Regards,
> Lau Lei Cheong
> "Uri Dimant" <urid@.iscar.co.il>
¼¶¼g©ó¶l¥ó·s»D:%23LDM8MQjFHA.3012@.TK2MSFTNGP12.phx.gbl...
> > Vyas's example shows how to divide a "big" transaction into a small ones
> >
> > SET ROWCOUNT 1000
> > WHILE 1 = 1
> > BEGIN
> > /*
> > DELETION here and Don't forget WHERE condition
> > */
> >
> > IF @.@.ROWCOUNT = 0
> > BEGIN
> > BREAK
> > END
> > ELSE
> > BEGIN
> > CHECKPOINT --Or doing BACKUP LOG File
> > END
> > END
> >
> > SET ROWCOUNT 0
> > "Lau Lei Cheong" <leu_lc@.yehoo.com.hk> wrote in message
> > news:eSbLvFQjFHA.1464@.TK2MSFTNGP14.phx.gbl...
> >> Hello,
> >>
> >> It happens to me that I have control over a MSSQL 2000 server that
> >> was
> >> looked after by another staff today. And than there is a call from the
> >> server's owner company that the server's harddisk is running out of
> >> space.
> >>
> >> As background information, the SQL server's running on a 5GB HDD
> >> partition with the Win2k system dir on it. And after some inspection, I
> >> found the "msdb" database occupies about 1.13GB and it's transaction
log
> >> occupies 2MB.
> >>
> >> So I opened Enterprise Manager and looked into the tables one by
one.
> >> And found the 'sysdtssteplog' table has almost 7 million rows. So I run
> >> "delete from sysdtssteplog" to delete it. After 15-20 minutes, the
"Query
> >> Analyzer"(I've explicitly called it to run the SQL statement) tell me
it
> >> cannot finish the task because the disk is running out of space and no
> > room
> >> for transaction log. And when I see the file size, the transaction log
> > file
> >> of msdb has grown to over 200MB. Oops.
> >>
> >> At least, I managed to found an unoccupied machine to install a
temp
> > SQL
> >> server, copy the database file to, trancate, and put back to the
> >> origional
> >> server. And the story is over. But what should I do if I experienced
that
> >> next time? There's management change in both my company and that
company
> > so
> >> replacement of harddisk may not be feasible in a short time. And I'd
like
> > to
> >> know if there's anything wrong in my procedure of handling the issue.
> >> This
> >> is my first time to handle a SQL server, and I have tough time on this.
I
> >> used to be a programmer only.
> >>
> >> Looking forward for any advice. Thanks a lot.
> >>
> >> Regards,
> >> Lau Lei Cheong
> >>
> >>
> >>
> >
> >
>

Friday, February 24, 2012

How to delete Duplicate records from table

i have table and in that i have number of records which are duplicated.
i want to delete the duplicate records from this table.
pls help me.CREATE TABLE #Demo (
idNo int identity(1,1),
colA int,
colB int
)
INSERT INTO #Demo(colA,colB) VALUES (1,6)
INSERT INTO #Demo(colA,colB) VALUES (1,6)
INSERT INTO #Demo(colA,colB) VALUES (2,4)
INSERT INTO #Demo(colA,colB) VALUES (3,3)
INSERT INTO #Demo(colA,colB) VALUES (4,2)
INSERT INTO #Demo(colA,colB) VALUES (3,3)
INSERT INTO #Demo(colA,colB) VALUES (5,1)
INSERT INTO #Demo(colA,colB) VALUES (8,1)
PRINT 'Table'
SELECT * FROM #Demo
PRINT 'Duplicates in Table'
SELECT * FROM #Demo
WHERE idNo IN
(SELECT B.idNo
FROM #Demo A JOIN #Demo B
ON A.idNo <> B.idNo
AND A.colA = B.colA
AND A.colB = B.colB)
PRINT 'Duplicates to Delete'
SELECT * FROM #Demo
WHERE idNo IN
(SELECT B.idNo
FROM #Demo A JOIN #Demo B
ON A.idNo < B.idNo -- < this time, not <>
AND A.colA = B.colA
AND A.colB = B.colB)
DELETE FROM #Demo
WHERE idNo IN
(SELECT B.idNo
FROM #Demo A JOIN #Demo B
ON A.idNo < B.idNo -- < this time, not <>
AND A.colA = B.colA
AND A.colB = B.colB)
PRINT 'Cleaned-up Table'
SELECT * FROM #Demo
DROP TABLE #Demo
"shiva" <bany.shanker@.gmail.com> wrote in message
news:1133445445.278560.128440@.g14g2000cwa.googlegroups.com...
>i have table and in that i have number of records which are duplicated.
> i want to delete the duplicate records from this table.
> pls help me.
>|||Unfrotunately, I have not found a clean way to do this. Uri's method will
work great, but technically, his table doesn't have duplicate records (as th
e
identity column prevents that).
It you have true duplicates, here's what I do:
1) Create a table containing all the table's fields plus a count field.
CREATE TABLE #xxx
(
Field1 int,
Field2 int,
NumToDelete int
)
2) Select the records which are duplicate:
INSERT INTO #xxx
SELECT *, COUNT(*) - 1
FROM dupedtable
GROUP BY Field1, Field2
HAVING COUNT(*) > 1
3) Either loop or generate a cursor and go through each record in #xxx
perfoming the following (note, if you loop, you'll need an identity column i
n
#xxx)
SET ROWCOUNT @.NumToDelete
DELETE FROM dupedtable
WHERE Field1 = @.Field1 AND Field2 = @.Field2
That's about it.
Marc
"shiva" wrote:

> i have table and in that i have number of records which are duplicated.
> i want to delete the duplicate records from this table.
> pls help me.
>|||Marc L. Allen wrote:
> Unfrotunately, I have not found a clean way to do this. Uri's method will
> work great, but technically, his table doesn't have duplicate records (as
the
> identity column prevents that).
> It you have true duplicates, here's what I do:
> 1) Create a table containing all the table's fields plus a count field.
> CREATE TABLE #xxx
> (
> Field1 int,
> Field2 int,
> NumToDelete int
> )
> 2) Select the records which are duplicate:
> INSERT INTO #xxx
> SELECT *, COUNT(*) - 1
> FROM dupedtable
> GROUP BY Field1, Field2
> HAVING COUNT(*) > 1
> 3) Either loop or generate a cursor and go through each record in #xxx
> perfoming the following (note, if you loop, you'll need an identity column
in
> #xxx)
> SET ROWCOUNT @.NumToDelete
> DELETE FROM dupedtable
> WHERE Field1 = @.Field1 AND Field2 = @.Field2
> That's about it.
> Marc
>
> "shiva" wrote:
>
delete #demo from #demo inner join #Demo d on #demo.idno < d.idno and
#demo.cola = d.cola and #demo.colb = d.colb
Regards|||Here is the process to delete the duplicate records posted some days back by
some body.
1. SELECT * INTO #Temp1 FROM [Table1]
2. TRUNCATE TABLE [Table1]
3. CREATE UNIQUE INDEX [Index1] ON [Table1] (Unique Column Names) WITH
IGNORE_DUP_KEY
4. INSERT INTO [Table1] (Column Names) SELECT (Column Names) FROM [Table1]
5. DROP INDEX [Table1].[Index1]
Note: In 4 th step,it will take the first row in list of duplicates ,rest of
them will be ignored
Thanks
Kumar
"shiva" wrote:

> i have table and in that i have number of records which are duplicated.
> i want to delete the duplicate records from this table.
> pls help me.
>