Showing posts with label complex. Show all posts
Showing posts with label complex. Show all posts

Wednesday, March 21, 2012

Is it possible to create reports in SSRS 2005 by mining data in SQL Server 2000

All,

I have found a lot of comments on the net but nowhere was I able to have a direct answer to this question:
My client has a complex database deployed on SQL Server 2000. He wishes to create reports based on this data using SSRS. Another division of the same company just implemented SQL Server 2005 and SSRS 2005.
I wish to know if SSRS 2005 is able to create reports based on data from SQL Server 2000?

Thank you.
S
Sure. You'll have no problems reporting against 2005 and 2000 together...

Friday, March 9, 2012

Is it customary to reindex every night?

I've been doing this DBA thing for a while. I'm having to deal with
more production issues as I'm working in more complex businesses now.
One of the systems that we recently put into production is being
maintained by a non-DBA type whom I had a recent chat with. He told me
that they've found that the performance of the system seems to degrade
over a week as queries seem to take longer to execute as the week goes
on. So to combat the performance loss, he scheduled nightly reindexing
of the database.
Nightly reindexing of a database seems okay when you have the luxury
of not being a 24x7 business use application. However, I wouldn't have
ordinarily expected such harsh degredation over a weeks time period
(40 sec delays per query issued in some cases). This is a database
that is relatively more insert/update than select/report. I'm just
curious as to what your experiences have been? Have you found cases
where you've run indexing every night? If so why? If not, do you have
any opinions on what I should take a look at to investigate the
performance decrease?
Thanks in advance,
Osolage
Hi
"Osolage" wrote:

> I've been doing this DBA thing for a while. I'm having to deal with
> more production issues as I'm working in more complex businesses now.
> One of the systems that we recently put into production is being
> maintained by a non-DBA type whom I had a recent chat with. He told me
> that they've found that the performance of the system seems to degrade
> over a week as queries seem to take longer to execute as the week goes
> on. So to combat the performance loss, he scheduled nightly reindexing
> of the database.
> Nightly reindexing of a database seems okay when you have the luxury
> of not being a 24x7 business use application. However, I wouldn't have
> ordinarily expected such harsh degredation over a weeks time period
> (40 sec delays per query issued in some cases). This is a database
> that is relatively more insert/update than select/report. I'm just
> curious as to what your experiences have been? Have you found cases
> where you've run indexing every night? If so why? If not, do you have
> any opinions on what I should take a look at to investigate the
> performance decrease?
> Thanks in advance,
> Osolage
>
The amount of degredation is depending on the amount of change that the data
undergoes, therefore if there are a high number of transaction on the
database you may need to re-index more often. This can be made worse by
having poorly thought out fill factors or possibly even poor programming or
datatype selection.
Look at outputing what DBCC SHOWCONTIG gives before you re-index. You may
want to try and follow something similar to the example on the DBCC
SHOWCONTIG topic in books online which will only re-index when the
fragmentation gets above a certain level.
Also watch out for database shrinking (either auto or manual) which can also
cause fragmentation.
John
|||Yes, I've seen this.
Generally, there was some sloppy code and design, such that the
database ran well as long as it was squeezed into available RAM, but
with even a little fragmentation the missing indexes and bad plans
caused an exponential degradation in performance.
There was initially a lot of inserting to tables with (nonsequential)
GUID clustered PKs, after that was changed to simple identity int's
much of the problem went away.
So, it was split between some sloppy code, and some scalability issues
that called for specific redesigns.
Some of these problems can be a real pain to diagnose, when they only
occur on the production box, with full-scale data, and different
critical points because of a different processor count and different
RAM layout than any dev environments.
J.
On 29 Jan 2007 22:15:25 -0800, "Osolage" <osolage@.gmail.com> wrote:

>I've been doing this DBA thing for a while. I'm having to deal with
>more production issues as I'm working in more complex businesses now.
>One of the systems that we recently put into production is being
>maintained by a non-DBA type whom I had a recent chat with. He told me
>that they've found that the performance of the system seems to degrade
>over a week as queries seem to take longer to execute as the week goes
>on. So to combat the performance loss, he scheduled nightly reindexing
>of the database.
>Nightly reindexing of a database seems okay when you have the luxury
>of not being a 24x7 business use application. However, I wouldn't have
>ordinarily expected such harsh degredation over a weeks time period
>(40 sec delays per query issued in some cases). This is a database
>that is relatively more insert/update than select/report. I'm just
>curious as to what your experiences have been? Have you found cases
>where you've run indexing every night? If so why? If not, do you have
>any opinions on what I should take a look at to investigate the
>performance decrease?
>Thanks in advance,
>Osolage
|||Osolage wrote:
> I've been doing this DBA thing for a while. I'm having to deal with
> more production issues as I'm working in more complex businesses now.
> One of the systems that we recently put into production is being
> maintained by a non-DBA type whom I had a recent chat with. He told me
> that they've found that the performance of the system seems to degrade
> over a week as queries seem to take longer to execute as the week goes
> on. So to combat the performance loss, he scheduled nightly reindexing
> of the database.
> Nightly reindexing of a database seems okay when you have the luxury
> of not being a 24x7 business use application. However, I wouldn't have
> ordinarily expected such harsh degredation over a weeks time period
> (40 sec delays per query issued in some cases). This is a database
> that is relatively more insert/update than select/report. I'm just
> curious as to what your experiences have been? Have you found cases
> where you've run indexing every night? If so why? If not, do you have
> any opinions on what I should take a look at to investigate the
> performance decrease?
> Thanks in advance,
> Osolage
>
Depends on how the indexes are defined, how many inserts/updates across
index keys are occurring, etc. Also, as John mentioned, make sure
you're not shrinking the database - that will effectively "undo" any
reindexing that you've done.
Rather than rebuild EVERY index, consider rebuilding only those that are
fragmented. Here's a script to get you started. It needs a couple of
tweaks that I haven't gotten around to making, in particular it needs to
exclude index ID = 255, but it should get you started.
Tracy McKibben
MCDBA
http://www.realsqlguy.com
|||You can look at Reorganize indexes and Reindex only highly fragmented
indexes.
BOL has good Example for it.
On Jan 30, 3:43 pm, JXStern <JXSternChange...@.gte.net> wrote:
> Yes, I've seen this.
> Generally, there was some sloppy code and design, such that the
> database ran well as long as it was squeezed into available RAM, but
> with even a little fragmentation the missing indexes and bad plans
> caused an exponential degradation in performance.
> There was initially a lot of inserting to tables with (nonsequential)
> GUID clustered PKs, after that was changed to simple identity int's
> much of the problem went away.
> So, it was split between some sloppy code, and some scalability issues
> that called for specific redesigns.
> Some of these problems can be a real pain to diagnose, when they only
> occur on the production box, with full-scale data, and different
> critical points because of a different processor count and different
> RAM layout than any dev environments.
> J.
> On 29 Jan 2007 22:15:25 -0800, "Osolage" <osol...@.gmail.com> wrote:
>
>
>
> - Show quoted text -
|||Hi, everyone,
I thank you for your comments so far. They validate my suspicions.
The procedures for checking index fragmentation and what-not can be
very tedious. This is something I've traditionally avoided except in
serious cases, because of the tedium. I'd be more inclined to dive in
if there are tools that help speed up the discovery of problem spots.
Have any of you used any tools to help speed up the research or to
even automate the discovery of problemmatic indexes? Please share or
link to your experiences if you are willing to share. I would love to
learn from you as it will make my job easier.
Sincere thanks,
Osoalge
|||On Feb 5, 4:38 pm, "Osolage" <osol...@.gmail.com> wrote:
> Hi, everyone,
> I thank you for your comments so far. They validate my suspicions.
> The procedures for checking index fragmentation and what-not can be
> very tedious. This is something I've traditionally avoided except in
> serious cases, because of the tedium. I'd be more inclined to dive in
> if there are tools that help speed up the discovery of problem spots.
> Have any of you used any tools to help speed up the research or to
> even automate the discovery of problemmatic indexes? Please share or
> link to your experiences if you are willing to share. I would love to
> learn from you as it will make my job easier.
> Sincere thanks,
> Osoalge
http://www.realsqlguy.com/bin/view/RealSQLGuy/DefraggingIndexes

Is it customary to reindex every night?

I've been doing this DBA thing for a while. I'm having to deal with
more production issues as I'm working in more complex businesses now.
One of the systems that we recently put into production is being
maintained by a non-DBA type whom I had a recent chat with. He told me
that they've found that the performance of the system seems to degrade
over a week as queries seem to take longer to execute as the week goes
on. So to combat the performance loss, he scheduled nightly reindexing
of the database.
Nightly reindexing of a database seems okay when you have the luxury
of not being a 24x7 business use application. However, I wouldn't have
ordinarily expected such harsh degredation over a weeks time period
(40 sec delays per query issued in some cases). This is a database
that is relatively more insert/update than select/report. I'm just
curious as to what your experiences have been? Have you found cases
where you've run indexing every night? If so why? If not, do you have
any opinions on what I should take a look at to investigate the
performance decrease?
Thanks in advance,
OsolageHi
"Osolage" wrote:

> I've been doing this DBA thing for a while. I'm having to deal with
> more production issues as I'm working in more complex businesses now.
> One of the systems that we recently put into production is being
> maintained by a non-DBA type whom I had a recent chat with. He told me
> that they've found that the performance of the system seems to degrade
> over a week as queries seem to take longer to execute as the week goes
> on. So to combat the performance loss, he scheduled nightly reindexing
> of the database.
> Nightly reindexing of a database seems okay when you have the luxury
> of not being a 24x7 business use application. However, I wouldn't have
> ordinarily expected such harsh degredation over a weeks time period
> (40 sec delays per query issued in some cases). This is a database
> that is relatively more insert/update than select/report. I'm just
> curious as to what your experiences have been? Have you found cases
> where you've run indexing every night? If so why? If not, do you have
> any opinions on what I should take a look at to investigate the
> performance decrease?
> Thanks in advance,
> Osolage
>
The amount of degredation is depending on the amount of change that the data
undergoes, therefore if there are a high number of transaction on the
database you may need to re-index more often. This can be made worse by
having poorly thought out fill factors or possibly even poor programming or
datatype selection.
Look at outputing what DBCC SHOWCONTIG gives before you re-index. You may
want to try and follow something similar to the example on the DBCC
SHOWCONTIG topic in books online which will only re-index when the
fragmentation gets above a certain level.
Also watch out for database shrinking (either auto or manual) which can also
cause fragmentation.
John|||Yes, I've seen this.
Generally, there was some sloppy code and design, such that the
database ran well as long as it was squeezed into available RAM, but
with even a little fragmentation the missing indexes and bad plans
caused an exponential degradation in performance.
There was initially a lot of inserting to tables with (nonsequential)
GUID clustered PKs, after that was changed to simple identity int's
much of the problem went away.
So, it was split between some sloppy code, and some scalability issues
that called for specific redesigns.
Some of these problems can be a real pain to diagnose, when they only
occur on the production box, with full-scale data, and different
critical points because of a different processor count and different
RAM layout than any dev environments.
J.
On 29 Jan 2007 22:15:25 -0800, "Osolage" <osolage@.gmail.com> wrote:

>I've been doing this DBA thing for a while. I'm having to deal with
>more production issues as I'm working in more complex businesses now.
>One of the systems that we recently put into production is being
>maintained by a non-DBA type whom I had a recent chat with. He told me
>that they've found that the performance of the system seems to degrade
>over a week as queries seem to take longer to execute as the week goes
>on. So to combat the performance loss, he scheduled nightly reindexing
>of the database.
>Nightly reindexing of a database seems okay when you have the luxury
>of not being a 24x7 business use application. However, I wouldn't have
>ordinarily expected such harsh degredation over a weeks time period
>(40 sec delays per query issued in some cases). This is a database
>that is relatively more insert/update than select/report. I'm just
>curious as to what your experiences have been? Have you found cases
>where you've run indexing every night? If so why? If not, do you have
>any opinions on what I should take a look at to investigate the
>performance decrease?
>Thanks in advance,
>Osolage|||Osolage wrote:
> I've been doing this DBA thing for a while. I'm having to deal with
> more production issues as I'm working in more complex businesses now.
> One of the systems that we recently put into production is being
> maintained by a non-DBA type whom I had a recent chat with. He told me
> that they've found that the performance of the system seems to degrade
> over a week as queries seem to take longer to execute as the week goes
> on. So to combat the performance loss, he scheduled nightly reindexing
> of the database.
> Nightly reindexing of a database seems okay when you have the luxury
> of not being a 24x7 business use application. However, I wouldn't have
> ordinarily expected such harsh degredation over a weeks time period
> (40 sec delays per query issued in some cases). This is a database
> that is relatively more insert/update than select/report. I'm just
> curious as to what your experiences have been? Have you found cases
> where you've run indexing every night? If so why? If not, do you have
> any opinions on what I should take a look at to investigate the
> performance decrease?
> Thanks in advance,
> Osolage
>
Depends on how the indexes are defined, how many inserts/updates across
index keys are occurring, etc. Also, as John mentioned, make sure
you're not shrinking the database - that will effectively "undo" any
reindexing that you've done.
Rather than rebuild EVERY index, consider rebuilding only those that are
fragmented. Here's a script to get you started. It needs a couple of
tweaks that I haven't gotten around to making, in particular it needs to
exclude index ID = 255, but it should get you started.
Tracy McKibben
MCDBA
http://www.realsqlguy.com|||You can look at Reorganize indexes and Reindex only highly fragmented
indexes.
BOL has good Example for it.
On Jan 30, 3:43 pm, JXStern <JXSternChange...@.gte.net> wrote:
> Yes, I've seen this.
> Generally, there was some sloppy code and design, such that the
> database ran well as long as it was squeezed into available RAM, but
> with even a little fragmentation the missing indexes and bad plans
> caused an exponential degradation in performance.
> There was initially a lot of inserting to tables with (nonsequential)
> GUID clustered PKs, after that was changed to simple identity int's
> much of the problem went away.
> So, it was split between some sloppy code, and some scalability issues
> that called for specific redesigns.
> Some of these problems can be a real pain to diagnose, when they only
> occur on the production box, with full-scale data, and different
> critical points because of a different processor count and different
> RAM layout than any dev environments.
> J.
> On 29 Jan 2007 22:15:25 -0800, "Osolage" <osol...@.gmail.com> wrote:
>
>
>
>
> - Show quoted text -|||Hi, everyone,
I thank you for your comments so far. They validate my suspicions.
The procedures for checking index fragmentation and what-not can be
very tedious. This is something I've traditionally avoided except in
serious cases, because of the tedium. I'd be more inclined to dive in
if there are tools that help speed up the discovery of problem spots.
Have any of you used any tools to help speed up the research or to
even automate the discovery of problemmatic indexes? Please share or
link to your experiences if you are willing to share. I would love to
learn from you as it will make my job easier.
Sincere thanks,
Osoalge|||On Feb 5, 4:38 pm, "Osolage" <osol...@.gmail.com> wrote:
> Hi, everyone,
> I thank you for your comments so far. They validate my suspicions.
> The procedures for checking index fragmentation and what-not can be
> very tedious. This is something I've traditionally avoided except in
> serious cases, because of the tedium. I'd be more inclined to dive in
> if there are tools that help speed up the discovery of problem spots.
> Have any of you used any tools to help speed up the research or to
> even automate the discovery of problemmatic indexes? Please share or
> link to your experiences if you are willing to share. I would love to
> learn from you as it will make my job easier.
> Sincere thanks,
> Osoalge
http://www.realsqlguy.com/bin/view/...fraggingIndexes

Is it customary to reindex every night?

I've been doing this DBA thing for a while. I'm having to deal with
more production issues as I'm working in more complex businesses now.
One of the systems that we recently put into production is being
maintained by a non-DBA type whom I had a recent chat with. He told me
that they've found that the performance of the system seems to degrade
over a week as queries seem to take longer to execute as the week goes
on. So to combat the performance loss, he scheduled nightly reindexing
of the database.
Nightly reindexing of a database seems okay when you have the luxury
of not being a 24x7 business use application. However, I wouldn't have
ordinarily expected such harsh degredation over a weeks time period
(40 sec delays per query issued in some cases). This is a database
that is relatively more insert/update than select/report. I'm just
curious as to what your experiences have been? Have you found cases
where you've run indexing every night? If so why? If not, do you have
any opinions on what I should take a look at to investigate the
performance decrease?
Thanks in advance,
OsolageHi
"Osolage" wrote:
> I've been doing this DBA thing for a while. I'm having to deal with
> more production issues as I'm working in more complex businesses now.
> One of the systems that we recently put into production is being
> maintained by a non-DBA type whom I had a recent chat with. He told me
> that they've found that the performance of the system seems to degrade
> over a week as queries seem to take longer to execute as the week goes
> on. So to combat the performance loss, he scheduled nightly reindexing
> of the database.
> Nightly reindexing of a database seems okay when you have the luxury
> of not being a 24x7 business use application. However, I wouldn't have
> ordinarily expected such harsh degredation over a weeks time period
> (40 sec delays per query issued in some cases). This is a database
> that is relatively more insert/update than select/report. I'm just
> curious as to what your experiences have been? Have you found cases
> where you've run indexing every night? If so why? If not, do you have
> any opinions on what I should take a look at to investigate the
> performance decrease?
> Thanks in advance,
> Osolage
>
The amount of degredation is depending on the amount of change that the data
undergoes, therefore if there are a high number of transaction on the
database you may need to re-index more often. This can be made worse by
having poorly thought out fill factors or possibly even poor programming or
datatype selection.
Look at outputing what DBCC SHOWCONTIG gives before you re-index. You may
want to try and follow something similar to the example on the DBCC
SHOWCONTIG topic in books online which will only re-index when the
fragmentation gets above a certain level.
Also watch out for database shrinking (either auto or manual) which can also
cause fragmentation.
John|||Yes, I've seen this.
Generally, there was some sloppy code and design, such that the
database ran well as long as it was squeezed into available RAM, but
with even a little fragmentation the missing indexes and bad plans
caused an exponential degradation in performance.
There was initially a lot of inserting to tables with (nonsequential)
GUID clustered PKs, after that was changed to simple identity int's
much of the problem went away.
So, it was split between some sloppy code, and some scalability issues
that called for specific redesigns.
Some of these problems can be a real pain to diagnose, when they only
occur on the production box, with full-scale data, and different
critical points because of a different processor count and different
RAM layout than any dev environments.
J.
On 29 Jan 2007 22:15:25 -0800, "Osolage" <osolage@.gmail.com> wrote:
>I've been doing this DBA thing for a while. I'm having to deal with
>more production issues as I'm working in more complex businesses now.
>One of the systems that we recently put into production is being
>maintained by a non-DBA type whom I had a recent chat with. He told me
>that they've found that the performance of the system seems to degrade
>over a week as queries seem to take longer to execute as the week goes
>on. So to combat the performance loss, he scheduled nightly reindexing
>of the database.
>Nightly reindexing of a database seems okay when you have the luxury
>of not being a 24x7 business use application. However, I wouldn't have
>ordinarily expected such harsh degredation over a weeks time period
>(40 sec delays per query issued in some cases). This is a database
>that is relatively more insert/update than select/report. I'm just
>curious as to what your experiences have been? Have you found cases
>where you've run indexing every night? If so why? If not, do you have
>any opinions on what I should take a look at to investigate the
>performance decrease?
>Thanks in advance,
>Osolage|||Osolage wrote:
> I've been doing this DBA thing for a while. I'm having to deal with
> more production issues as I'm working in more complex businesses now.
> One of the systems that we recently put into production is being
> maintained by a non-DBA type whom I had a recent chat with. He told me
> that they've found that the performance of the system seems to degrade
> over a week as queries seem to take longer to execute as the week goes
> on. So to combat the performance loss, he scheduled nightly reindexing
> of the database.
> Nightly reindexing of a database seems okay when you have the luxury
> of not being a 24x7 business use application. However, I wouldn't have
> ordinarily expected such harsh degredation over a weeks time period
> (40 sec delays per query issued in some cases). This is a database
> that is relatively more insert/update than select/report. I'm just
> curious as to what your experiences have been? Have you found cases
> where you've run indexing every night? If so why? If not, do you have
> any opinions on what I should take a look at to investigate the
> performance decrease?
> Thanks in advance,
> Osolage
>
Depends on how the indexes are defined, how many inserts/updates across
index keys are occurring, etc. Also, as John mentioned, make sure
you're not shrinking the database - that will effectively "undo" any
reindexing that you've done.
Rather than rebuild EVERY index, consider rebuilding only those that are
fragmented. Here's a script to get you started. It needs a couple of
tweaks that I haven't gotten around to making, in particular it needs to
exclude index ID = 255, but it should get you started.
Tracy McKibben
MCDBA
http://www.realsqlguy.com|||You can look at Reorganize indexes and Reindex only highly fragmented
indexes.
BOL has good Example for it.
On Jan 30, 3:43 pm, JXStern <JXSternChange...@.gte.net> wrote:
> Yes, I've seen this.
> Generally, there was some sloppy code and design, such that the
> database ran well as long as it was squeezed into available RAM, but
> with even a little fragmentation the missing indexes and bad plans
> caused an exponential degradation in performance.
> There was initially a lot of inserting to tables with (nonsequential)
> GUID clustered PKs, after that was changed to simple identity int's
> much of the problem went away.
> So, it was split between some sloppy code, and some scalability issues
> that called for specific redesigns.
> Some of these problems can be a real pain to diagnose, when they only
> occur on the production box, with full-scale data, and different
> critical points because of a different processor count and different
> RAM layout than any dev environments.
> J.
> On 29 Jan 2007 22:15:25 -0800, "Osolage" <osol...@.gmail.com> wrote:
>
> >I've been doing this DBA thing for a while. I'm having to deal with
> >more production issues as I'm working in more complex businesses now.
> >One of the systems that we recently put into production is being
> >maintained by a non-DBA type whom I had a recent chat with. He told me
> >that they've found that the performance of the system seems to degrade
> >over a week as queries seem to take longer to execute as the week goes
> >on. So to combat the performance loss, he scheduled nightly reindexing
> >of the database.
> >Nightly reindexing of a database seems okay when you have the luxury
> >of not being a 24x7 business use application. However, I wouldn't have
> >ordinarily expected such harsh degredation over a weeks time period
> >(40 sec delays per query issued in some cases). This is a database
> >that is relatively more insert/update than select/report. I'm just
> >curious as to what your experiences have been? Have you found cases
> >where you've run indexing every night? If so why? If not, do you have
> >any opinions on what I should take a look at to investigate the
> >performance decrease?
> >Thanks in advance,
> >Osolage- Hide quoted text -
> - Show quoted text -|||Hi, everyone,
I thank you for your comments so far. They validate my suspicions.
The procedures for checking index fragmentation and what-not can be
very tedious. This is something I've traditionally avoided except in
serious cases, because of the tedium. I'd be more inclined to dive in
if there are tools that help speed up the discovery of problem spots.
Have any of you used any tools to help speed up the research or to
even automate the discovery of problemmatic indexes? Please share or
link to your experiences if you are willing to share. I would love to
learn from you as it will make my job easier.
Sincere thanks,
Osoalge|||On Feb 5, 4:38 pm, "Osolage" <osol...@.gmail.com> wrote:
> Hi, everyone,
> I thank you for your comments so far. They validate my suspicions.
> The procedures for checking index fragmentation and what-not can be
> very tedious. This is something I've traditionally avoided except in
> serious cases, because of the tedium. I'd be more inclined to dive in
> if there are tools that help speed up the discovery of problem spots.
> Have any of you used any tools to help speed up the research or to
> even automate the discovery of problemmatic indexes? Please share or
> link to your experiences if you are willing to share. I would love to
> learn from you as it will make my job easier.
> Sincere thanks,
> Osoalge
http://www.realsqlguy.com/bin/view/RealSQLGuy/DefraggingIndexes

Wednesday, March 7, 2012

Is it a complex sql query?

Hello

I am using stored procedure with sql 2005 (with Visual studio 2005)

I have two tables .. TABLE1 And TABLE2

>From TABLE1 i need to retrive the OrderID's of the 4 most top rows. so
i did:
SELECT TOP 4 OrderID FROM TABLE1 order by OrderID desc

Now what i am trying to do is take the 4 row results (4 OrderID's) i
got from
TABLE1 and check if the 4 rows (4 OrderID's) exist in TABLE2 for a
specific
userID i get by INPUT varible (@.UserId)..

What i want to return is only which OrderID'S existed in TABLE2 for the

specific user.

If only 2 OrderID'S i retrived from TABLE1 exist in TABLE2 i will
return only 2 OrderID's (so i can do my output in visual studio 2005
using the reader())

I would appreciate this if anyone knows how to do this sql query , is
it possible to do this in 1 query? i want to put it in a stored
procedure.I tried to use this query-
SELECT TOP 4 OrderID FROM TABLE1 WHERE exists (SELECT * From TABLE2
where @.UserId=TABLE2.UserID)

But this query shows me the all 4 OrderID's if it finds the USERID in
TABLE2..

What i want to return is only which OrderID'S existes in TABLE2 for the
specific user.

if i have in TABLE1:
OrderID
1
2
3
4

TABLE2:
OrderID UserId
1 1001
2 1002

I want it to return only "2" if the INPUT Parameter of @.UserID is 1002|||Another example..

if i have in TABLE1:
OrderID
1
2
3
4

TABLE2:
OrderID UserId
1 1001
2 1002
3 1002

I want it to return only "2" and "3" if the INPUT Parameter of @.UserID
is 1002|||Hi

Check out http://www.aspfaq.com/etiquette.asp?id=5006 on how to post DDL and
sample data in a usable form

You can use something like:
SELECT TOP 4 t1.OrderID
FROM TABLE1 t1
WHERE exists (SELECT * FROM TABLE2 t2
WHERE @.UserId=T2.UserId
AND T1.OrderId = T2.OrderId )

Or (better!)

SELECT TOP 4 t1.OrderID
FROM TABLE1 t1
JOIN TABLE2 t2 ON T1.OrderId = T2.OrderId AND @.UserId=T2.UserId

Check out the topics "Using Joins" and "Join Fundamentals" in books online

John

<stockblaster@.gmail.com> wrote in message
news:1137312110.273304.240990@.g47g2000cwa.googlegr oups.com...
> Another example..
> if i have in TABLE1:
> OrderID
> 1
> 2
> 3
> 4
>
> TABLE2:
> OrderID UserId
> 1 1001
> 2 1002
> 3 1002
>
> I want it to return only "2" and "3" if the INPUT Parameter of @.UserID
> is 1002|||Excellent!

Thanks a lot John, it seems to work just fine.. i used the second
example.|||Hello again

Finally i decieded to use SELECT TOP 4 t1.OrderID
FROM TABLE1 t1
WHERE exists (SELECT * FROM TABLE2 t2
WHERE @.UserId=T2.UserId
AND T1.OrderId = T2.OrderId )

and modifed it to:
SELECT TOP 4 t1.OrderID
FROM TABLE1 t1
WHERE NOT exists (SELECT * FROM TABLE2 t2
WHERE @.UserId=T2.UserId
AND T1.OrderId = T2.OrderId )

(Notice the "NOT")
Because i wanted it to return me the OrderID's (from the top 4 of
course) that does not exist in TABLE2 ..

I couldn't do it with the JOIN thingy even if i changed OrderId <>
T2.OrderId ..|||I tried to find this in the documents on the web ..I couldn't find a
way of how to perform this only for the TOP 4 of TABLE1.

Now what happenes:
stockblas...@.gmail.com
Jan 15, 10:01 am show options

Newsgroups: comp.databases.ms-sqlserver
From: stockblas...@.gmail.com - Find messages by this author
Date: 15 Jan 2006 00:01:50 -0800
Local: Sun, Jan 15 2006 10:01 am
Subject: Re: Is it a complex sql query?
Reply | Reply to Author | Forward | Print | Individual Message | Show
original | Remove | Report Abuse

Another example..

TABLE1:
OrderID
1
2
3
4
5
6
7
8
9
10
TABLE2:
OrderID UserId
1 1001
2 1002
3 1002

It will return me: 4 5 6 7 (the top 4 of what it finds)
i use now:
SELECT TOP 4 t1.OrderID
FROM TABLE1 t1
WHERE NOT exists (SELECT * FROM TABLE2 t2
WHERE @.UserId=T2.UserId
AND T1.OrderId = T2.OrderId )

Any ideas?|||Hi

I should have said that TOP without and ORDER BY clause is a bit
meaningless.

SELECT TOP 4 t1.OrderID
FROM TABLE1 t1
WHERE NOT EXISTS (SELECT * FROM TABLE2 t2
WHERE @.UserId=T2.UserId
AND T1.OrderId = T2.OrderId )
ORDER BY t1.OrderID

Will return you all rows OrderIds from Table1 where a row in Table2 does not
exist for that OrderId AND has a UserId of @.UserId. With the ORDER BY means
1, 4, 5 and 6 are returned.

To do this using a JOIN, an OUTER JOIN is required.

SELECT TOP 4 t1.OrderID
FROM TABLE1 t1
LEFT JOIN TABLE2 t2 ON t1.OrderId = t2.OrderId AND @.UserId = t2.UserId
WHERE t2.OrderID IS NULL
ORDER BY t1.OrderID

John

<stockblaster@.gmail.com> wrote in message
news:1137325768.003889.45140@.g47g2000cwa.googlegro ups.com...
> Hello again
> Finally i decieded to use SELECT TOP 4 t1.OrderID
> FROM TABLE1 t1
> WHERE exists (SELECT * FROM TABLE2 t2
> WHERE @.UserId=T2.UserId
> AND T1.OrderId = T2.OrderId )

> and modifed it to:
> SELECT TOP 4 t1.OrderID
> FROM TABLE1 t1
> WHERE NOT exists (SELECT * FROM TABLE2 t2
> WHERE @.UserId=T2.UserId
> AND T1.OrderId = T2.OrderId )

> (Notice the "NOT")
> Because i wanted it to return me the OrderID's (from the top 4 of
> course) that does not exist in TABLE2 ..
> I couldn't do it with the JOIN thingy even if i changed OrderId <>
> T2.OrderId ..|||Hello

I am sorry, i didn't explain my self what i wanted to acchive exactly.
For this query:
SELECT TOP 4 t1.OrderID
FROM TABLE1 t1
LEFT JOIN TABLE2 t2 ON t1.OrderId = t2.OrderId AND @.UserId = t2.UserId
WHERE t2.OrderID IS NULL
ORDER BY t1.OrderID DESC

There is a problem with that..
For example:
Table1:
OrderID
1
2
3
4
5
6
7
8
Table2:
OrderID UserID
6 1001
7 1001
3 1002
4 1002
the result will be:
for user 1001
8
5
4
3

I only need to get 8 and 5 which are the two orderID's the user didn't
have from the top 4 in table 1 ..

can't figure that out :(|||On 15 Jan 2006 10:09:18 -0800, stockblaster@.gmail.com wrote:

>Hello
>I am sorry, i didn't explain my self what i wanted to acchive exactly.
(snip)

Hi Stockblaster,

That's exactly the reason why John suggested you to read the information
at www.aspfaq.com/5006 in his first post to you - posting CREATE TABLE
and INSERT statements and expected output is a much better way to
explain your needs than pure narrative.

If I understand your requirements correctly, then maybe something like
this will work:

SELECT t1.OrderId
FROM (SELECT TOP 4 OrderID
FROM Table1
ORDER BY OrderID DESC) AS t1
LEFT JOIN Table2 AS t2
ON t2.OrderId = t1.OrderId
AND t2.UserId = @.UserId
WHERE t2.OrderID IS NULL

(untested - see www.aspfafq.com/5006 if you prefer a tested reply)

--
Hugo Kornelis, SQL Server MVP|||Hello Hugo..

Very nice! i believe this 1 did the work..

Thanks a lot.. this 1 was stiff.

Is there any good book you can recommend me for sql 2005 (with SQL
Server Management Studio) ... How to upload to a shared web hosting,
when to use relationships, some sql querys examples? all the basics.|||Hi

I am not sure if my interpretation is the same as Hugos!
If all 4 rows returned are below the maximum what should happen?

SELECT TOP 4 t1a.OrderID
FROM TABLE1 t1a
LEFT JOIN TABLE2 t2a ON t1.OrderId = t2a.OrderId AND @.UserId =
t2a.UserId
WHERE t2.OrderID IS NULL
AND t1a.OrderID > ( SELECT MAX(t1b.OrderID) FROM TABLE1 t1b
JOIN TABLE2 t2b ON t1b.OrderId = t2b.OrderId AND @.UserId = t2b.UserId )

ORDER BY t1a.OrderID DESC

John

stockblaster@.gmail.com wrote:
> Hello
> I am sorry, i didn't explain my self what i wanted to acchive exactly.
> For this query:
> SELECT TOP 4 t1.OrderID
> FROM TABLE1 t1
> LEFT JOIN TABLE2 t2 ON t1.OrderId = t2.OrderId AND @.UserId = t2.UserId
> WHERE t2.OrderID IS NULL
> ORDER BY t1.OrderID DESC
>
> There is a problem with that..
> For example:
> Table1:
> OrderID
> 1
> 2
> 3
> 4
> 5
> 6
> 7
> 8
> Table2:
> OrderID UserID
> 6 1001
> 7 1001
> 3 1002
> 4 1002
> the result will be:
> for user 1001
> 8
> 5
> 4
> 3
>
> I only need to get 8 and 5 which are the two orderID's the user didn't
> have from the top 4 in table 1 ..
> can't figure that out :(|||Hi

I don't think you will get a single books to cover all these topics,
and you will have to be careful of books based on the pre-release
versions. You may want to check out THe Microsoft SQL Server 2005
Administrator's Pocket Consultant ISDN 0735621071 for configuration
information, and there is always books online. Also check out SQL
Server magazine which has many articles that will be benificial
http://www.windowsitpro.com/SQLServer/

John|||On 15 Jan 2006 15:27:13 -0800, stockblaster@.gmail.com wrote:

>Hello Hugo..
>Very nice! i believe this 1 did the work..
>Thanks a lot.. this 1 was stiff.
>Is there any good book you can recommend me for sql 2005 (with SQL
>Server Management Studio) ... How to upload to a shared web hosting,
>when to use relationships, some sql querys examples? all the basics.

Hi Stockblaster,

I'm sorry, I can't help you here.

Personally, I'm going to wait for Inside SQL Server 2005, that Kalen
Delaney is (hopefully) working on right now. However, the "Inside..."
series are "how does it work" kind of books; you seem to be seeking the
"how do I operate it" kind of books.

--
Hugo Kornelis, SQL Server MVP|||Hello John.

I am not sure i understand, do you mean if table1 contains only two
records? so the top 4 will not work?|||Hi

Sorry for the delayed reply, this one slipped through the net.

My question was related to

There is a problem with that..
For example:
Table1:
OrderID
1
2
3
4
5
6
7
8
Table2:
OrderID UserID
6 1001
7 1001
3 1002
4 1002
the result will be:
for user 1001
8
5
4
3

Do you actually want 3,4,5 as this is less than the maximum for 1001 which
is already 7?

John
<stockblaster@.gmail.com> wrote in message
news:1137449155.173528.136550@.g14g2000cwa.googlegr oups.com...
> Hello John.
> I am not sure i understand, do you mean if table1 contains only two
> records? so the top 4 will not work?

Monday, February 20, 2012

Is Cursor Best Way To Go?

I need to get two values from a complex SQL statement which returns a single
record and use those two values to update a single record in a table. In
order to assign those two values to variables and then use those variables
in the UPDATE statement, I created a cursor and used Fetch Next... Into.
This way, I only have to call the complex SQL once instead of twice.
This seems like the best way to go. However, I've always used cursors for
scrolling through resultsets. In this case, though, there is just a single
record being returned, and the cursor doesn't scroll.
Is that the most efficient way to go, or is there a better way to be able to
use both values from the SQL statement without having to call it twice?
Thanks.Hi Neil
I'd need more details regarding the query/DDL to say anything too
meaningful, but certainly a set-based solution is always preferable to
an iterative/cursor-solution.|||here is a guess without seeing your code.
declare @.v1 int, @.v2 int
select @.v1=[col1], @.v2=[colx]
from (
-- your complex query
) as derived_table
-oj
"Neil" <nospam@.nospam.net> wrote in message
news:vhAne.4180$s64.2269@.newsread1.news.pas.earthlink.net...
>I need to get two values from a complex SQL statement which returns a
>single record and use those two values to update a single record in a
>table. In order to assign those two values to variables and then use those
>variables in the UPDATE statement, I created a cursor and used Fetch
>Next... Into. This way, I only have to call the complex SQL once instead
>of twice.
> This seems like the best way to go. However, I've always used cursors for
> scrolling through resultsets. In this case, though, there is just a single
> record being returned, and the cursor doesn't scroll.
> Is that the most efficient way to go, or is there a better way to be able
> to use both values from the SQL statement without having to call it twice?
> Thanks.
>|||SQL Server doesn't support the standard SQL syntax for this but it does
have a proprietary syntax to do the same job:
UPDATE T1
SET x = foo,
y = bar
FROM
(SELECT foo, bar /* your query here */
FROM ... ) AS T2
WHERE T2.key_col = T1.key_col
/* join condition should yield a single row from T2 for each row in
T1 */

> I've always used cursors for
> scrolling through resultsets
Really? For what purpose? Cursors should be the rare exception rather
than the rule. Usually there are better set-based solutions.
David Portas
SQL Server MVP
--|||> SQL Server doesn't support the standard SQL syntax for this but it does
> have a proprietary syntax to do the same job:
> UPDATE T1
> SET x = foo,
> y = bar
> FROM
> (SELECT foo, bar /* your query here */
> FROM ... ) AS T2
> WHERE T2.key_col = T1.key_col
> /* join condition should yield a single row from T2 for each row in
> T1 */
Yes, that was what I was looking for (though I needed to use UPDATE T1
SET... From T1, (Select foo...) As T2...)
Also, since I'm only updating a single row in T1, and since T2 only returns
a single row with values, I eliminated the WHERE T2.keycol=T1.keycol. My SQL
looks like:
UPDATE T1
SET X = T2.FOO, Y=T2.BAR
FROM T1, (SELECT FOO, BAR FROM MYQUERY WHERE ID=@.VALUE) AS T2
WHERE T1.ID=@.VALUE
Do you see any problem with that?

> Really? For what purpose? Cursors should be the rare exception rather
> than the rule. Usually there are better set-based solutions.
I guess one of the main areas where I've used them is in order-rearranging
functions -- such as where there are a set of items in a table, each with a
value in a field that specifies the order. The user clicks, say, an up arrow
in the interface, and the current item needs to move up one in order --
decrement it's field value by one, and increment the preceding item's by
one.
Another time I used a cursor was in a procedure in which the length of two
fields combined needed to be compared to a value and then, based on the
length of the combined fields, different values would be placed in a certain
field. I suppose that could have just been done with a set-based solution;
but the cursor seemed more straightforward. It was also only dealing with
one record at a time.
Thanks for your help!
Neil

> --
> David Portas
> SQL Server MVP
> --
>|||Re-arranging order based on a column (pos):
UPDATE foo
SET pos = CASE pos
WHEN @.old_pos
THEN @.new_pos
ELSE pos + SIGN(@.old_pos - @.new_pos)
END
WHERE pos BETWEEN @.old_pos AND @.new_pos
OR pos BETWEEN @.new_pos AND @.old_pos
Update different columns based on the length of a string value:
UPDATE YourTable
SET col1 =
CASE
WHEN LEN(x+y)<=10
THEN a ELSE b END,
col2 =
CASE
WHEN LEN(x+y)>10
THEN a ELSE b END
WHERE ...
David Portas
SQL Server MVP
--
UPDATE|||David Portas Jun 2, 7:07 am show options
Newsgroups: comp.databases.ms-sqlserver,
microsoft.public.sqlserver.programming
From: "David Portas" <REMOVE_BEFORE_REPLYING_dpor...@.acm.o=ADrg> - Find
messages by this author
Date: 2 Jun 2005 04:07:17 -0700
Local: Thurs,Jun 2 2005 7:07 am
Subject: Re: Is Cursor Best Way To Go?
Reply | Reply to Author | Forward | Print | Individual Message | Show
original | Report Abuse
Re-arranging order based on a column (pos):
UPDATE foo
SET pos =3D CASE pos
WHEN @.old_pos
THEN @.new_pos
ELSE pos + SIGN(@.old_pos - @.new_pos)
END
WHERE pos BETWEEN @.old_pos AND @.new_pos
OR pos BETWEEN @.new_pos AND @.old_pos;
Very neat! I always did a monster CASE expression with extra WHEN
clauses based on (old_pos ' newpos).|||Hi, David.
Here's another one for you. I have an sp that takes various input parameters
for a customer, and processes the data using various case statements. I now
want to run this sp for all customers on a nightly basis. My immediate
reaction, as previously, would be to use a cursor to loop through all the
customers, get the input parameters for the sp from the Customer table, and
call the sp once for each customer. Is there a way to do this without a
cursor?
Thanks,
Neil
"David Portas" <REMOVE_BEFORE_REPLYING_dportas@.acm.org> wrote in message
news:1117710437.665131.255080@.g47g2000cwa.googlegroups.com...
> Re-arranging order based on a column (pos):
> UPDATE foo
> SET pos = CASE pos
> WHEN @.old_pos
> THEN @.new_pos
> ELSE pos + SIGN(@.old_pos - @.new_pos)
> END
> WHERE pos BETWEEN @.old_pos AND @.new_pos
> OR pos BETWEEN @.new_pos AND @.old_pos
> Update different columns based on the length of a string value:
> UPDATE YourTable
> SET col1 =
> CASE
> WHEN LEN(x+y)<=10
> THEN a ELSE b END,
> col2 =
> CASE
> WHEN LEN(x+y)>10
> THEN a ELSE b END
> WHERE ...
> --
> David Portas
> SQL Server MVP
> --
>
>
>
> UPDATE
>|||Neil (nospam@.nospam.net) writes:
> Here's another one for you. I have an sp that takes various input
> parameters for a customer, and processes the data using various case
> statements. I now want to run this sp for all customers on a nightly
> basis. My immediate reaction, as previously, would be to use a cursor to
> loop through all the customers, get the input parameters for the sp from
> the Customer table, and call the sp once for each customer. Is there a
> way to do this without a cursor?
Yes, but you will of course have to rewrite the procedure, so that it
works with many customers. To do this, you need to pass the input
parameters in a table rather than as parameter. This table can be a temp
table, or a permanent table which is keyed by @.@.spid or similar. I discuss
this on http://www.sommarskog.se/share_data.html#temptables.
Well, rather you would write a new procedure that works with many, and
then rewrite the old procedure to be a wrapper on the new procedure.
Now, whether you actually should go this route depends. Let's say that
it takes 10 minutes to run a cursor over all customers and call the
existing procedure, and that you have plenty of time to spare in the
night. In this case, it's not likely to be worth the development effort.
Also, if you opt to use a temp table to pass the input parameters, the
procedure will be recompiled each time. This will have the net effect
that calls for single customers will now be more expensive, and could
even be performance problems, if the procedure is huge.
We actually did this exercise with a core procedure in our system, and
in our case it was really necessary. But it was a major developement task.
Our estimate was 200 hours for development, but I think the true outcome
was more than 300 hours. But that was a long procedure, on 700-800 lines
and which called several sub-procedures. The final multi-version is a
3000-line monster with no less than 43 table variables.
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||Everything Erland has said. This is where it pays to have a good design
pattern from kick-off. For an UPDATE/INSERT/DELETE proc servicing the
UI you may typically want to pass parameters for a single row. For
procs that implement other business logic however, you should generally
design with a set-based approach in mind. Unfortunately, programmers
used to other languages too often try to encapsulate all logic in procs
that act like scalar functions - a sure route to cursor hell!
David Portas
SQL Server MVP
--

Is Cursor Best Way To Go?

I need to get two values from a complex SQL statement which returns a single
record and use those two values to update a single record in a table. In
order to assign those two values to variables and then use those variables
in the UPDATE statement, I created a cursor and used Fetch Next... Into.
This way, I only have to call the complex SQL once instead of twice.

This seems like the best way to go. However, I've always used cursors for
scrolling through resultsets. In this case, though, there is just a single
record being returned, and the cursor doesn't scroll.

Is that the most efficient way to go, or is there a better way to be able to
use both values from the SQL statement without having to call it twice?

Thanks.Hi Neil

I'd need more details regarding the query/DDL to say anything too
meaningful, but certainly a set-based solution is always preferable to
an iterative/cursor-solution.|||here is a guess without seeing your code.

declare @.v1 int, @.v2 int
select @.v1=[col1], @.v2=[colx]
from (
-- your complex query
) as derived_table

--
-oj

"Neil" <nospam@.nospam.net> wrote in message
news:vhAne.4180$s64.2269@.newsread1.news.pas.earthl ink.net...
>I need to get two values from a complex SQL statement which returns a
>single record and use those two values to update a single record in a
>table. In order to assign those two values to variables and then use those
>variables in the UPDATE statement, I created a cursor and used Fetch
>Next... Into. This way, I only have to call the complex SQL once instead
>of twice.
> This seems like the best way to go. However, I've always used cursors for
> scrolling through resultsets. In this case, though, there is just a single
> record being returned, and the cursor doesn't scroll.
> Is that the most efficient way to go, or is there a better way to be able
> to use both values from the SQL statement without having to call it twice?
> Thanks.|||SQL Server doesn't support the standard SQL syntax for this but it does
have a proprietary syntax to do the same job:

UPDATE T1
SET x = foo,
y = bar
FROM
(SELECT foo, bar /* your query here */
FROM ... ) AS T2
WHERE T2.key_col = T1.key_col
/* join condition should yield a single row from T2 for each row in
T1 */

> I've always used cursors for
> scrolling through resultsets

Really? For what purpose? Cursors should be the rare exception rather
than the rule. Usually there are better set-based solutions.

--
David Portas
SQL Server MVP
--|||> SQL Server doesn't support the standard SQL syntax for this but it does
> have a proprietary syntax to do the same job:
> UPDATE T1
> SET x = foo,
> y = bar
> FROM
> (SELECT foo, bar /* your query here */
> FROM ... ) AS T2
> WHERE T2.key_col = T1.key_col
> /* join condition should yield a single row from T2 for each row in
> T1 */

Yes, that was what I was looking for (though I needed to use UPDATE T1
SET... From T1, (Select foo...) As T2...)

Also, since I'm only updating a single row in T1, and since T2 only returns
a single row with values, I eliminated the WHERE T2.keycol=T1.keycol. My SQL
looks like:

UPDATE T1
SET X = T2.FOO, Y=T2.BAR
FROM T1, (SELECT FOO, BAR FROM MYQUERY WHERE ID=@.VALUE) AS T2
WHERE T1.ID=@.VALUE

Do you see any problem with that?

>> I've always used cursors for
>> scrolling through resultsets
> Really? For what purpose? Cursors should be the rare exception rather
> than the rule. Usually there are better set-based solutions.

I guess one of the main areas where I've used them is in order-rearranging
functions -- such as where there are a set of items in a table, each with a
value in a field that specifies the order. The user clicks, say, an up arrow
in the interface, and the current item needs to move up one in order --
decrement it's field value by one, and increment the preceding item's by
one.

Another time I used a cursor was in a procedure in which the length of two
fields combined needed to be compared to a value and then, based on the
length of the combined fields, different values would be placed in a certain
field. I suppose that could have just been done with a set-based solution;
but the cursor seemed more straightforward. It was also only dealing with
one record at a time.

Thanks for your help!

Neil

> --
> David Portas
> SQL Server MVP
> --|||Re-arranging order based on a column (pos):

UPDATE foo
SET pos = CASE pos
WHEN @.old_pos
THEN @.new_pos
ELSE pos + SIGN(@.old_pos - @.new_pos)
END
WHERE pos BETWEEN @.old_pos AND @.new_pos
OR pos BETWEEN @.new_pos AND @.old_pos

Update different columns based on the length of a string value:

UPDATE YourTable
SET col1 =
CASE
WHEN LEN(x+y)<=10
THEN a ELSE b END,
col2 =
CASE
WHEN LEN(x+y)>10
THEN a ELSE b END
WHERE ...

--
David Portas
SQL Server MVP
--

UPDATE|||David Portas Jun 2, 7:07 am show options

Newsgroups: comp.databases.ms-sqlserver,
microsoft.public.sqlserver.programming
From: "David Portas" <REMOVE_BEFORE_REPLYING_dpor...@.acm.o*rg> - Find
messages by this author
Date: 2 Jun 2005 04:07:17 -0700
Local: Thurs,Jun 2 2005 7:07 am
Subject: Re: Is Cursor Best Way To Go?
Reply | Reply to Author | Forward | Print | Individual Message | Show
original | Report Abuse

Re-arranging order based on a column (pos):

UPDATE foo
SET pos = CASE pos
WHEN @.old_pos
THEN @.new_pos
ELSE pos + SIGN(@.old_pos - @.new_pos)
END
WHERE pos BETWEEN @.old_pos AND @.new_pos
OR pos BETWEEN @.new_pos AND @.old_pos;

Very neat! I always did a monster CASE expression with extra WHEN
clauses based on (old_pos ?? newpos).|||Hi, David.

Here's another one for you. I have an sp that takes various input parameters
for a customer, and processes the data using various case statements. I now
want to run this sp for all customers on a nightly basis. My immediate
reaction, as previously, would be to use a cursor to loop through all the
customers, get the input parameters for the sp from the Customer table, and
call the sp once for each customer. Is there a way to do this without a
cursor?

Thanks,

Neil

"David Portas" <REMOVE_BEFORE_REPLYING_dportas@.acm.org> wrote in message
news:1117710437.665131.255080@.g47g2000cwa.googlegr oups.com...
> Re-arranging order based on a column (pos):
> UPDATE foo
> SET pos = CASE pos
> WHEN @.old_pos
> THEN @.new_pos
> ELSE pos + SIGN(@.old_pos - @.new_pos)
> END
> WHERE pos BETWEEN @.old_pos AND @.new_pos
> OR pos BETWEEN @.new_pos AND @.old_pos
> Update different columns based on the length of a string value:
> UPDATE YourTable
> SET col1 =
> CASE
> WHEN LEN(x+y)<=10
> THEN a ELSE b END,
> col2 =
> CASE
> WHEN LEN(x+y)>10
> THEN a ELSE b END
> WHERE ...
> --
> David Portas
> SQL Server MVP
> --
>
>
>
> UPDATE|||Neil (nospam@.nospam.net) writes:
> Here's another one for you. I have an sp that takes various input
> parameters for a customer, and processes the data using various case
> statements. I now want to run this sp for all customers on a nightly
> basis. My immediate reaction, as previously, would be to use a cursor to
> loop through all the customers, get the input parameters for the sp from
> the Customer table, and call the sp once for each customer. Is there a
> way to do this without a cursor?

Yes, but you will of course have to rewrite the procedure, so that it
works with many customers. To do this, you need to pass the input
parameters in a table rather than as parameter. This table can be a temp
table, or a permanent table which is keyed by @.@.spid or similar. I discuss
this on http://www.sommarskog.se/share_data.html#temptables.

Well, rather you would write a new procedure that works with many, and
then rewrite the old procedure to be a wrapper on the new procedure.

Now, whether you actually should go this route depends. Let's say that
it takes 10 minutes to run a cursor over all customers and call the
existing procedure, and that you have plenty of time to spare in the
night. In this case, it's not likely to be worth the development effort.
Also, if you opt to use a temp table to pass the input parameters, the
procedure will be recompiled each time. This will have the net effect
that calls for single customers will now be more expensive, and could
even be performance problems, if the procedure is huge.

We actually did this exercise with a core procedure in our system, and
in our case it was really necessary. But it was a major developement task.
Our estimate was 200 hours for development, but I think the true outcome
was more than 300 hours. But that was a long procedure, on 700-800 lines
and which called several sub-procedures. The final multi-version is a
3000-line monster with no less than 43 table variables.

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

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||Everything Erland has said. This is where it pays to have a good design
pattern from kick-off. For an UPDATE/INSERT/DELETE proc servicing the
UI you may typically want to pass parameters for a single row. For
procs that implement other business logic however, you should generally
design with a set-based approach in mind. Unfortunately, programmers
used to other languages too often try to encapsulate all logic in procs
that act like scalar functions - a sure route to cursor hell!

--
David Portas
SQL Server MVP
--|||David Portas (REMOVE_BEFORE_REPLYING_dportas@.acm.org) writes:
> Everything Erland has said. This is where it pays to have a good design
> pattern from kick-off. For an UPDATE/INSERT/DELETE proc servicing the
> UI you may typically want to pass parameters for a single row. For
> procs that implement other business logic however, you should generally
> design with a set-based approach in mind. Unfortunately, programmers
> used to other languages too often try to encapsulate all logic in procs
> that act like scalar functions - a sure route to cursor hell!

Permit me to expand a bit on what I touched in my previous post.

In many cases it is reasonable to write a procedure that operates
on a scalar set of values. It cannot be denied that writing such a
procedure is simpler, and thus cuts development costs at that stage.

Passing data in tables is actually quite messy. Let's look at the options:
1) Use a temp table. The caller must create the temp table, and the callee
trust the caller. If the procedure is called from many places, many
callers must create the table. This can be address with an include-
file, if you have the luxury of a preprocessor. We have that, but it's
not a standard feature.
And if even you get by all this, the callee is recompiled for each
new instance of the caller. This can be expensive.
2) A permanent table, typically spid-keyed. We use this technique for the
really heavy-duty stuff. If you make this routine, you get lots of
these tables. Note also that the tables are typically stored disjunct
in the version-control system, which means that procedure and
"parameter list" are in two places.
3) Clients can't use any of 1 or 2, but they can pass comma-separated
lists or XML-documents. But if A_SP calls B_SP, it would be a bad
idea if A_SP built an XML document from its data, only to be able
to call B_SP. What you can to is to have a wrapper that accepts
the XML document, and unpacks that into the temp table or spid-
keyed table. If the client is mainly interested in single-row
operations, it probably needs a scalar wrapper as well. Else, it
will be a lot extra development overhead to build XML documents.

So, clearly, if you at point A in your devleopment cycle only have a need
for a procedure that operates on scalar parameters, you write a procedure
that works with scalar procedure only, because that is what you are paid
for.

If you later at point B need to do the same operation on many rows,
you have to make a judicious choice between:

1) Write a cursor loop.
2) Just forget about the old procedure, and write a new set-based.
3) Replace the old procedure.

If the logic of the procedure is trivial, like "IF NOT EXISTS INSERT ELSE
UPDATE" you should pick #2. But say that the logic is non-trivial, for
instance includes updates to dependent tables in some unnormalised
scenario, then at some point #2 becomes completely impermissible. At
this point #1 can very well be the best pick. Say that you know that
it will be rare that the cursor will comprise as much as 100 rows. If
the procedure takes 100 ms to run, it may be very difficult to motivate
to rewrite the old procedure, if this would take 100 hours.

There is also another issue here that is worth mentioning. Say that your
procedure performs some sort of INSERT operation (in a couple of tables),
and the data comes from some less trustable source, which thus may
supply non-conformant data. If you have a scalar procedure, error
handling is fairly simple. You can do explicit checks on anticipated
errors, but you can be fairly relaxed, because if some data violates a
constraint or trigger check, the operation will fail.

This because a lot more complex if you accept input data in a table.
Because if you apply the same strategy, 1000 rows could fail to insert
when there is an error in a single one. This could very likely be
entirely unacceptable. Thus in case, you will need to duplicate all
constraint and trigger checks in your code, so you can mark which rows
that are illegal.

So while it is easy to say "replace cursor loops with set-based
statments", one should realise that in complex cases, this is far from
trivial.

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

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp