473,769 Members | 5,910 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Variable inside a nested loop

I am trying to write a utility/query to get a report from a table. Below
is the some values in the table:
table name: dba_daily_resou rce_usage_v1
conn|loginame|d bname|cum_cpu|c um_io|cum_mem|l ast_batch
------------------------------------------------------------
80 |farmds_w|Farm_ R|4311 |88 |5305 |11/15/2004 11:30
80 |abcdes_w|efgh_ R|5000 |88 |4000 |11/15/2004 12:30
45 |dcp_webu|DCP |5967 |75 |669 |11/16/2004 11:30
95 |dcp_webu|XYZ |5967 |75 |669 |11/17/2004 11:30

I need to write a query which for a given date (say 11/15/2004),
generate a resource usage report for a given duration (say 3 days).

Here is my query:
*************** *************** ******
set quoted_identifi er off
declare @var1 int
set @var1=0

--BEGIN OUTER LOOP
while @var1<=3 --INPUT runs the report for 3 days
begin
declare @vstartdate char (10) --INPUT starting date
set @vstartdate='11/15/2004'

--builds a range of date
declare @var2 datetime
set @var2=(select distinct (dateadd(day,@v ar1,convert(var char
(10),last_batch ,101)))
--set @var2=(select distinct (dateadd(day,@v ar1,last_batch) )
from dba_daily_resou rce_usage_v1
where convert(varchar (10),last_batch ,101)=@vstartda te)

set @var1=@var1+1 --increments a day

declare @var5 varchar (12)
--set dateformat mdy

--converts the date into 11/15/2004 format from @var2
set @var5="'"+(conv ert(varchar(10) ,@var2,101))+"' "
--print @var5 produces '11/15/2004' as result

declare @vloginame varchar (50)
declare @vdbname varchar (50)

--BEGIN INNER LOOP
declare cur1 cursor read_only for
select distinct loginame,dbname from
dba_daily_resou rce_usage_v1
where convert(varchar (10),last_batch ,101)=@var5
--??????PROBLEM AREA ABOVE STATEMENT??????
--print @var5 produces '11/15/2004' as result
--however cursor is not being built and hence it exits the
--inner loop (cursor)
open cur1
fetch next from cur1 into @vloginame, @vdbname
while @@fetch_status= 0
begin
--print @var5 produces '11/15/2004' as result
declare @vl varchar (50)
set @vl="'"+rtrim(@ vloginame)+"'"
declare @vd varchar (50)
set @vd="'"+@vdbnam e+"'"

--processes the cursors
declare @scr varchar (200)
set @scr=("select max(cum_cpu) from dba_daily_resou rce_usage_v1 where
loginame="+@vl+
" and dbname="+@vd+" and "+"convert(varc har
(10),last_batch ,101)="+@var5)
--set @var3 =(select max(cum_cpu) from dba_daily_resou rce_usage_v1
where
--loginame=@vlogi name and dbname=@vdbname
--and convert(varchar (10),last_batch ,101)=@var5)
print @scr
--exec @scr
fetch next from cur1 into @vloginame, @vdbname
end
--END INNER LOOP
select @var2 as "For date"
deallocate cur1
end
--END OUTER LOOP
*************** *************** ******
PROBLEM:
Even though variable @var5 is being passed as '11/15/2004' inside the
cursor fetch (see print @var5 inside the fetch), the value is not being
used to build the cursor. Hence, the cursor has no row set.
Basically, the variable @var5 is not being processed/passed correctly
from outside the cursor to inside the cursor.

Any help please.
Thanks


*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Jul 20 '05 #1
3 3354
Sorry to answer with another question but why are you using cursors here?
You should always try to avoid using cursors as they increase the complexity
of your code and usually perform poorly. The best way to get help with your
problem is to post DDL, some sample data INSERTs and show your required end
result. See:

http://www.aspfaq.com/etiquette.asp?id=5006

That way we can help you with a query based solution instead.

--
David Portas
SQL Server MVP
--
Jul 20 '05 #2
On Fri, 03 Dec 2004 02:14:09 GMT, r rk wrote:
I am trying to write a utility/query to get a report from a table. Below
is the some values in the table:
table name: dba_daily_resou rce_usage_v1
conn|loginame| dbname|cum_cpu| cum_io|cum_mem| last_batch
------------------------------------------------------------
80 |farmds_w|Farm_ R|4311 |88 |5305 |11/15/2004 11:30
80 |abcdes_w|efgh_ R|5000 |88 |4000 |11/15/2004 12:30
45 |dcp_webu|DCP |5967 |75 |669 |11/16/2004 11:30
95 |dcp_webu|XYZ |5967 |75 |669 |11/17/2004 11:30

I need to write a query which for a given date (say 11/15/2004),
generate a resource usage report for a given duration (say 3 days). (snip)PROBLEM:
Even though variable @var5 is being passed as '11/15/2004' inside the
cursor fetch (see print @var5 inside the fetch), the value is not being
used to build the cursor. Hence, the cursor has no row set.
Hi r rk,

You didn't post CREATE TABLE stattements and INSERT statements for sample
data that would allow me to test run your code. However, I already see
lots of problems. I think you should get rid of all those implicit and
explicit date/string conversions, get rid of both loops (both the
cursor-driven and the non-cursor driven) and get rid of the dynamic SQL.
That would not only solve your problem, it would improve the performance,
improve maintainability and conform to good coding practices.

Before suggesting a set-based alternative to this procedural code, allow
me to comment on the current code first:

set @var2=(select distinct (dateadd(day,@v ar1,convert(var char
(10),last_batc h,101)))
--set @var2=(select distinct (dateadd(day,@v ar1,last_batch) )
from dba_daily_resou rce_usage_v1
where convert(varchar (10),last_batch ,101)=@vstartda te)
This will set @var2 to NULL if no row exists in the table with the date in
last_batch equal to @vstartdate.
The third argument in dateadd must me of datetime datatype. Your
conversion to varchar is not necessary as it will be converted back to
datetime immediately. If you do this to get rid of the time portion, then
at least use a safe date format (112 is recommended).
--converts the date into 11/15/2004 format from @var2
set @var5="'"+(conv ert(varchar(10) ,@var2,101))+"' "
--print @var5 produces '11/15/2004' as result

declare @vloginame varchar (50)
declare @vdbname varchar (50)

--BEGIN INNER LOOP
declare cur1 cursor read_only for
select distinct loginame,dbname from
dba_daily_resou rce_usage_v1
where convert(varchar (10),last_batch ,101)=@var5
--??????PROBLEM AREA ABOVE STATEMENT??????


You have added singe quotes to @var5 in the set statement above. This
means that for each row in dba_daily_resou rce_usage_v1, SQL Server will
convert the date, get something like 11/15/2004 (without quotes!!) and
compare that to @v5, which is '11/15/2004' (with quotes!!!)

Changing this would probably fix your code, but do read on, please.
Though it is probably possible to fix the errors in your code, it will
always remain slow and (as a result of using unsafe date formats) buggy.
Here is a singe set-based SELECT statement that should result in the same
rows as your procedure (though not in the exact same format, but that
would be easy to fix in the presentation tier).

DECLARE @vstartdate datetime --INPUT starting date
SET @vstartdate = '20041115'
-- NOTE: I changed the datatype for the variable
-- and the date format used for the date constant.

SELECT loginname, dbname, lb_date, MAX(cum_cpu)
FROM (SELECT loginname, dbname, cum_cpu
DATEADD(day,DAT EDIFF(day,'2000 0101',last_batc h),'20000101')
FROM dba_daily_resou rce_usage_v1
WHERE last_batch >= @vstartdate
AND last_batch < DATEADD(day, @vstartdate, 4)
-- gives report for @vstartdate up to and including @vstartdate + 3 days
) AS D (loginname, dbname, cum_cpu, lb_date)
GROUP BY loginname, dbname, cum_cpu

(untested)

Best, Hugo
--

(Remove _NO_ and _SPAM_ to get my e-mail address)
Jul 20 '05 #3
On Fri, 03 Dec 2004 02:14:09 GMT, r rk wrote:
I am trying to write a utility/query to get a report from a table. Below
is the some values in the table:
table name: dba_daily_resou rce_usage_v1
conn|loginame| dbname|cum_cpu| cum_io|cum_mem| last_batch
------------------------------------------------------------
80 |farmds_w|Farm_ R|4311 |88 |5305 |11/15/2004 11:30
80 |abcdes_w|efgh_ R|5000 |88 |4000 |11/15/2004 12:30
45 |dcp_webu|DCP |5967 |75 |669 |11/16/2004 11:30
95 |dcp_webu|XYZ |5967 |75 |669 |11/17/2004 11:30

I need to write a query which for a given date (say 11/15/2004),
generate a resource usage report for a given duration (say 3 days). (snip)PROBLEM:
Even though variable @var5 is being passed as '11/15/2004' inside the
cursor fetch (see print @var5 inside the fetch), the value is not being
used to build the cursor. Hence, the cursor has no row set.
Hi r rk,

You didn't post CREATE TABLE stattements and INSERT statements for sample
data that would allow me to test run your code. However, I already see
lots of problems. I think you should get rid of all those implicit and
explicit date/string conversions, get rid of both loops (both the
cursor-driven and the non-cursor driven) and get rid of the dynamic SQL.
That would not only solve your problem, it would improve the performance,
improve maintainability and conform to good coding practices.

Before suggesting a set-based alternative to this procedural code, allow
me to comment on the current code first:

set @var2=(select distinct (dateadd(day,@v ar1,convert(var char
(10),last_batc h,101)))
--set @var2=(select distinct (dateadd(day,@v ar1,last_batch) )
from dba_daily_resou rce_usage_v1
where convert(varchar (10),last_batch ,101)=@vstartda te)
This will set @var2 to NULL if no row exists in the table with the date in
last_batch equal to @vstartdate.
The third argument in dateadd must me of datetime datatype. Your
conversion to varchar is not necessary as it will be converted back to
datetime immediately. If you do this to get rid of the time portion, then
at least use a safe date format (112 is recommended).
--converts the date into 11/15/2004 format from @var2
set @var5="'"+(conv ert(varchar(10) ,@var2,101))+"' "
--print @var5 produces '11/15/2004' as result

declare @vloginame varchar (50)
declare @vdbname varchar (50)

--BEGIN INNER LOOP
declare cur1 cursor read_only for
select distinct loginame,dbname from
dba_daily_resou rce_usage_v1
where convert(varchar (10),last_batch ,101)=@var5
--??????PROBLEM AREA ABOVE STATEMENT??????


You have added singe quotes to @var5 in the set statement above. This
means that for each row in dba_daily_resou rce_usage_v1, SQL Server will
convert the date, get something like 11/15/2004 (without quotes!!) and
compare that to @v5, which is '11/15/2004' (with quotes!!!)

Changing this would probably fix your code, but do read on, please.
Though it is probably possible to fix the errors in your code, it will
always remain slow and (as a result of using unsafe date formats) buggy.
Here is a singe set-based SELECT statement that should result in the same
rows as your procedure (though not in the exact same format, but that
would be easy to fix in the presentation tier).

DECLARE @vstartdate datetime --INPUT starting date
SET @vstartdate = '20041115'
-- NOTE: I changed the datatype for the variable
-- and the date format used for the date constant.

SELECT loginname, dbname, lb_date, MAX(cum_cpu)
FROM (SELECT loginname, dbname, cum_cpu
DATEADD(day,DAT EDIFF(day,'2000 0101',last_batc h),'20000101')
FROM dba_daily_resou rce_usage_v1
WHERE last_batch >= @vstartdate
AND last_batch < DATEADD(day, @vstartdate, 4)
-- gives report for @vstartdate up to and including @vstartdate + 3 days
) AS D (loginname, dbname, cum_cpu, lb_date)
GROUP BY loginname, dbname, cum_cpu

(untested)

Best, Hugo
--

(Remove _NO_ and _SPAM_ to get my e-mail address)
Jul 23 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
3740
by: Gord | last post by:
Hello, I think that what I'm trying to do is impossible, but before I give up I thought I'd try and pick a few more knowledgeable brains than my own. I have any array of user defined type variables. I need to loop through the array (doing certain calculations) on a particular member variable. I then want to loop through the array again on a different member variable doing very similar calculations. I only need to change a couple...
3
2869
by: Thomas Matthews | last post by:
Hi, While coding programs, I cam about a conundrum regarding variables defined in an iterative loop. The issue is whether it is more efficient to factor the definition out of the loop or maintain encapsulation by leaving it inside the loop? Common stuff for examples: class Data;
3
7731
by: Nelson Broat | last post by:
In jsp land you can have the following: <% String name = "Nelson"; %> Hi, my name is <%= name %>. Such that, in your browser you see:
15
2538
by: Robin Eidissen | last post by:
What I try to do is to iterate over two variables using template metaprogramming. I've specialized it such that when it reaches the end of a row ot starts on the next and when it reaches the last row it stops.. At least that's what I thought I did, but VC71 says "warning C4717: 'LOOP<0,1>::DO' : recursive on all control paths, function will cause runtime stack overflow". What's wrong? Here's the code: template<int M, int N>
9
6613
by: Rodusa | last post by:
I am trying to assign @sql variable to @total, where @sql is a sql statement stored on the database, however what I am getting is its string value and not its calcuation. Could anybody help? DECLARE my_cursor CURSOR FOR SELECT sqlstatement from Sn_SalesReport declare @sql varchar(255), @total varchar(20) OPEN my_cursor FETCH NEXT FROM my_cursor INTO @sql
77
5248
by: Peter Olcott | last post by:
http://www.tommti-systems.de/go.html?http://www.tommti-systems.de/main-Dateien/reviews/languages/benchmarks.html The above link shows that C# is 450% slower on something as simple as a nested loop. Is this because .NET is inherently slower or does the C# compiler merely produce code that is not as well optimized as the C++ compiler?
4
2722
by: Ray | last post by:
Hello, I think I've had JavaScript variable scope figured out, can you please see if I've got it correctly? * Variables can be local or global * When a variable is declared outside any function, it is global regardless of whether it's declared with or without "var" * When it is declared inside a function, if declared with "var", it's local, if not, it's global
9
1427
by: Pyenos | last post by:
Approach 1: class Class1: class Class2: def __init__(self):self.variable="variable" class Class3: def method():print Class1().Class2().variable #problem Approach 1.1:
20
24718
by: Sun | last post by:
Maybe this is a very primative question, but I just get a bit confused about 'set' and 'Set' module in python. I understand 'set' is a build in type in python after 2.4(or 2.3) and Set a seperate module, anyhow, I gonna use build in 'set'. then the question is how can I declare a empty set variable as a 'var= ' do to a list variable?
0
9589
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10048
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9865
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8872
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7410
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6674
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5304
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5447
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3563
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.