Thursday, March 29, 2012
Cursor vs. Multiple hits from the client
The question I'm about to pose is because of performance concerns so please
hear me out.
I'm trying to get a better understanding of what the impact of round trips
from the client to the server are, not the impact on the client, but on the
server. If I have a query that returns 30 rows and then each of the 30 rows
needs to have some work done -- that can all be done in SQL Server and
doesn't require any outside resources -- and then have a final result set
returned, am I better off with A or B:
A Call proc1 from client and get 30 rows. Loop on client and make 30
consecutive calls to the server to proc2
B. Have one proc that does cursor over 30 rows and and then processes each
one and then returns final result set
I know an RDBMS isn't designed for procedural stuff and its more efficient
to do conditional and loop processing on a client. But the processing in
this proc is minimal. I can't do a set based solution because I'm working
with possibly locked records that I need to pass over using SET LOCK_TIMEOUT
0 (and I can't use READPAST because its very specific in nature and doesn't
work in this scenario).
So what it boils down to is how do I determine if the network layer/etc.
processing of 30 client requests is more expensive than having a very
minimal cursor (one int column, 30 rows max) and doing looping in the
procedure? I want to answer this question not only for this specific
instance but also to be able intelligently determine it for future cases.
Thanks for any help,
Mike<disclaimer> In general cursors are bad, very bad. That said they are a tool
and every tool has its purpose in life so choose your tools wisely.
</disclaimer>
From what you've described, I'd choose option B. For me, the situation
comes down to answering he question, why incur the added overhead of round
trips to the client, if they are not need? Just ensure that the transaction
scope managed appropriately for your situation and do the work on the
server.
--Brian
(Please reply to the newsgroups only.)
"Mike Jansen" <mjansen_nntp@.mail.com> wrote in message
news:%23pGAbQTuFHA.1132@.TK2MSFTNGP10.phx.gbl...
>I know cursors are controversial and can cause performance, etc. issues.
>The question I'm about to pose is because of performance concerns so please
>hear me out.
> I'm trying to get a better understanding of what the impact of round trips
> from the client to the server are, not the impact on the client, but on
> the server. If I have a query that returns 30 rows and then each of the
> 30 rows needs to have some work done -- that can all be done in SQL Server
> and doesn't require any outside resources -- and then have a final result
> set returned, am I better off with A or B:
> A Call proc1 from client and get 30 rows. Loop on client and make 30
> consecutive calls to the server to proc2
> B. Have one proc that does cursor over 30 rows and and then processes each
> one and then returns final result set
> I know an RDBMS isn't designed for procedural stuff and its more efficient
> to do conditional and loop processing on a client. But the processing in
> this proc is minimal. I can't do a set based solution because I'm working
> with possibly locked records that I need to pass over using SET
> LOCK_TIMEOUT 0 (and I can't use READPAST because its very specific in
> nature and doesn't work in this scenario).
> So what it boils down to is how do I determine if the network layer/etc.
> processing of 30 client requests is more expensive than having a very
> minimal cursor (one int column, 30 rows max) and doing looping in the
> procedure? I want to answer this question not only for this specific
> instance but also to be able intelligently determine it for future cases.
> Thanks for any help,
> Mike
>|||> B. Have one proc that does cursor over 30 rows and and then processes each
> one and then returns final result set
If you can provide more specific details, I think it is quite possible that
you can remove this requirement of "processes each one" and treat the 30
rows as a set. Eliminating any kind of iteration / looping on both client
and server is really going to speed up this process. With "possibly locked
records" you can either set an isolation level that allows you to wait for
the current locks to be released, and still treat them as a set, or you can
come back to the client and say, couldn't lock all rows, try again. I'm
curious how you are going to handle the case where the fifth row you are
trying to process is locked. You're going to skip past it, and return to
the client, guess what, I updated 29 of 30 rows?
If the cursor really is required (in most cases it's not), then Brian is
right, you are probably better off avoiding the multiple round trips. But
even that is not guaranteed, so it comes down to testing in your actual
environment under realistic load.|||> If you can provide more specific details...
For ludicrous level details see: (make sure to read the quoted text at the
end which is the actual description)
http://groups.google.com/group/micr...1089d9f553f62a2
Yup. Its being used as a work queue. I grab up to 30 "candidate" records
using WITH (NOLOCK) and then SET LOCK_TIMEOUT 0 and use the cursor to
attempt to "grab" each record by updating a status. If I get the lock
timeout error, I just skip it. It will be tried again on a subsequent poll.
There's a lot more to it if you see the link above, but that's the basics
and should be enough to show why I need a cursor (or multiple calls from
client).
I don't use READPAST hint because its very specific in its application.
From my research and experimenting, the work queue table has to be designed
very specifically and accessed very specifically since READPAST only reads
past index locks on the same index its currently using, doesn't read past
data locks, and doesn't read past locks from non READ COMMITTED
transactions. I'm doing optimizations on an existing database and don't
have the luxury of doing major modifications to the structure currently to
make it work with READPAST.
Mike|||> and should be enough to show why I need a cursor (or multiple calls from
> client).
Okay, I'm not convinced but you seem to be, so test, test, test. If you
absolutely have to use a cursor here, I think it will be very difficult for
anyone to tell you "using cursor approach a will be better than cursor
approach b"... because there are far more variables involved than just the
number of rows and the two high-level methodologies.|||> Okay, I'm not convinced but you seem to be, so test, test, test. If you
> absolutely have to use a cursor here,
If I had an approach to do this without cursors or multiple clients calls, I
would do it in a flash.
I don't know any other way to "grab a set of rows, but only the rows that
aren't locked" (besides READPAST which I've already described doesn't work
in this scenario).
> I think it will be very difficult for anyone to tell you "using cursor
> approach a will be better than cursor approach b"... because there are far
> more variables involved than just the number of rows and the two
> high-level methodologies.
What I'm looking for specifically is a way to measure the overhead of client
calls vs. doing the same logic inside a stored proc using a cursor if
necessary. Can I measure the cpu and other cost of the various layers on
the server in between the client request (coming in on a socket) and the
actual execution in SQL? Or is this overhead so negligible that I shouldn't
worry about 30 client calls to the server? (the connection is already
established so there's no extra overhead there). We hear comments about
this performing badly and that performing badly, and I'm just trying to get
a grasp on what will perform badly in 30 client calls. I understand that
network latency can have performance effects on the overall transaction (if
an actual transaction is held across calls) and client performance (because
the overall time of 30 round trips may be much slower than 1 single call
over the network to the server). What I want to understand is the
effect/overhead on the _server_ of each client request.
If I can figure out how to monitor that kind of performance and compare it
to the performance/overhead of the cursor and the logic in the stored proc,
I can then make a case-by-case decision on which is better. Sorry if I
wasn't super clear initially. I think I'm just realizing myself what
exactly it is I'm looking for.
Thanks,
Mike|||> What I'm looking for specifically is a way to measure the overhead of
> client calls vs. doing the same logic inside a stored proc using a cursor
> if necessary. Can I measure the cpu and other cost of the various layers
> on the server in between the client request (coming in on a socket) and
> the actual execution in SQL?
Well, you could buy a testing suite which measures the performance end to
end in each scenario (http://www.aspfaq.com/2139) and on SQL Server directly
(http://www.aspfaq.com/2513). You could use Profiler / Performance Monitor
for the back-end side. In both cases, I think it might be tough to
disseminate between delays caused by round trips and client processing and
delays due to the different methods in SQL.
Also see http://www.aspfaq.com/2245 for some direct methods (though not all
are applicable).
A|||Thanks for the info.
"Aaron Bertrand [SQL Server MVP]" <ten.xoc@.dnartreb.noraa> wrote in message
news:uwe6VQWuFHA.1572@.TK2MSFTNGP10.phx.gbl...
> Well, you could buy a testing suite which measures the performance end to
> end in each scenario (http://www.aspfaq.com/2139) and on SQL Server
> directly (http://www.aspfaq.com/2513). You could use Profiler /
> Performance Monitor for the back-end side. In both cases, I think it
> might be tough to disseminate between delays caused by round trips and
> client processing and delays due to the different methods in SQL.
> Also see http://www.aspfaq.com/2245 for some direct methods (though not
> all are applicable).
> A
>
Cursor versus While Loop
Thanks!!The short answer boils down to both options are bad, and you are correct that the WHILE/SELECT/DELETE choice is even worse than the cursor.
More than 99 percent of the time there is a set-based solution that is hundreds or thousands of times faster/better than any loop can be, so the set based solution is what should be your "holy grail". Fix the problem instead of trying to find ways to make the loop less of an annoyance!
-PatP|||Why don't you post what it is you're trying to dosql
cursor to slow
set nocount on
Declare @.entry bigint, @.mobile int, @.fid int, @.rid int, @.pin char(10), @.commission tinyint,
@.barred tinyint, @.barred_acse tinyint, @.les char(10), @.mobile1 int, @.fid1 int,
@.rid1 int, @.pin1 char(10), @.commission1 tinyint, @.barred1 tinyint, @.barred_acse1 tinyint,
@.les1 char(10)
DECLARE changes CURSOR
FOR
select mobile, fid, rid, pin, commission, barred, barred_acse, les
from mobile_changes
OPEN changes
FETCH NEXT from changes
INTO @.mobile, @.fid, @.rid, @.pin, @.commission, @.barred, @.barred_acse, @.les
WHILE @.@.FETCH_STATUS = 0
BEGIN
DECLARE history CURSOR
FOR
select max(entry), mobile, fid, rid, pin, commission, barred, barred_acse, les
from mobile_history
where mobile = @.mobile
group by mobile, fid, rid, pin, commission, barred, barred_acse, les
OPEN history
FETCH NEXT FROM history
INTO @.entry, @.mobile1, @.fid1, @.rid1, @.pin1, @.commission1, @.barred1, @.barred_acse1, @.les1
IF (
@.mobile = @.mobile1 and @.fid = @.fid1 and @.rid = @.rid1 and @.pin = @.pin1 and
@.commission = @.commission1 and @.barred = @.barred1 and @.barred_acse = @.barred_acse1 and
@.les = @.les1)
BEGIN
DELETE FROM mobile_changes where mobile = @.mobile
END
CLOSE history
deallocate history
FETCH NEXT FROM changes
INTO @.mobile, @.fid, @.rid, @.pin, @.commission, @.barred, @.barred_acse, @.les
END
close changes
deallocate changesTo speed up your processing, you can avoid the cursors. Use temp table instead.
Try the following steps:
1. Create temp table from mobile_history with all required fields.
select max(a.entry) MaxEntry, a.mobile, a.fid, a.rid,
a.pin, a.commission, a.barred, a.barred_acse, a.les
into #temp_history
from mobile_history a, mobile_changes b
where a.mobile = b.mobile
group by mobile, fid, rid, pin, commission, barred, barred_acse, les
2. Delete records from the table mobile_changes using temp table.
delete mobile_changes
from mobile_changes a, #temp_history b
where a.mobile_no = b.mobile_no
and a.fid = b.fid
and a.rid = b.rid
and a.pin = b.pin
and a.commission = b.commission
and a.barred = b.barred
and a.barred_acse = b.barred_acse
and a.les = b.les
The above will do the same thing. Here, my only confusion is why do you need max(entry) in mobile_history table. Anyway, you are not using it anywhere. If i assume that u are not using it anywhere, our query can be even simpler. Just use the following query.
delete mobile_changes
from mobile_changes a, #mobile_history b
where a.mobile_no = b.mobile_no
and a.fid = b.fid
and a.rid = b.rid
and a.pin = b.pin
and a.commission = b.commission
and a.barred = b.barred
and a.barred_acse = b.barred_acse
and a.les = b.les
Thanks.
Prabhanjan|||The Entry field is a auto numbered primary key. The max(entry) returns the latest record grouped by mobile. Thanks for the help the cursor method was taking up to 50 minutes to complete, your method takes < 10 seconds.
Cursor to loop through all tables in db
I have a db with 285 tables. I want to add 1 varchar(10) column to all 285
tables called 'year' and I always want year to be '1999'.
I am struggling with setting up the cursor though. This is what I have so
far:
declare table_loop cursor
For select name from sysobjects where xtype = 'u'
open table_loop
Fetch table_loop
alter table [name]
add db_year varchar(10)
close table_loop
deallocate table_loop
go
Any help would be greatly appreciated.
Thanks.
ArcherIt has to be something like
declare @.name varchar(')
declare table_loop cursor for select name from sysobjects where xtype = 'u'
open table_loop
fetch next from table_loop into @.Name
while @.@.FETCH_STATUS = 0
begin
-- this migth have to be some dynamic thing, like:
-- exec 'alter table ' + @.name + ' add db_year varchar(10)'
alter table [@.name]
add db_year varchar(10)
fetch next from table_loop into @.name
end
close table_loop
deallocate table_loop
go
Kr.
Soren
"bagman3rd" <bagman3rd@.discussions.microsoft.com> skrev i en meddelelse
news:24C3F48A-4961-4285-9FDF-F790961789C5@.microsoft.com...
> So far, I have avoided using cursors, but I see no other way to do this.
> I have a db with 285 tables. I want to add 1 varchar(10) column to all
> 285
> tables called 'year' and I always want year to be '1999'.
> I am struggling with setting up the cursor though. This is what I have so
> far:
> declare table_loop cursor
> For select name from sysobjects where xtype = 'u'
> open table_loop
> Fetch table_loop
> alter table [name]
> add db_year varchar(10)
> close table_loop
> deallocate table_loop
> go
> Any help would be greatly appreciated.
> Thanks.
> Archer|||HI
There is a straight forward method for this
google for undocumented sp_Msforeachtable command
Regards
R.D
"Soeren S. Joergensen" wrote:
> It has to be something like
> declare @.name varchar(')
> declare table_loop cursor for select name from sysobjects where xtype = 'u
'
> open table_loop
> fetch next from table_loop into @.Name
> while @.@.FETCH_STATUS = 0
> begin
> -- this migth have to be some dynamic thing, like:
> -- exec 'alter table ' + @.name + ' add db_year varchar(10)'
> alter table [@.name]
> add db_year varchar(10)
> fetch next from table_loop into @.name
> end
> close table_loop
> deallocate table_loop
> go
> Kr.
> Soren
> "bagman3rd" <bagman3rd@.discussions.microsoft.com> skrev i en meddelelse
> news:24C3F48A-4961-4285-9FDF-F790961789C5@.microsoft.com...
>
>|||Wouldn't you be better off with a DDL script that you can check into source
control and deploy to test and live environments? Try this:
SELECT
'ALTER TABLE '+QUOTENAME(table_schema)+'.'+QUOTENAME(table_name)+
' ADD [year_num] VARCHAR(10) NOT NULL'+
' CONSTRAINT [df_year_num] DEFAULT (''1999'')'
FROM information_schema.tables ;
Output as text and you have your script.
Note that "YEAR" is a reserved word so not a good choice for a column name.
Why make the year number a VARCHAR anyway?
David Portas
SQL Server MVP
--|||CORRECTION:
SELECT
'ALTER TABLE '+QUOTENAME(table_schema)+'.'+QUOTENAME(table_name)+
' ADD [year_num] VARCHAR(10) NOT NULL'+
' CONSTRAINT [df_'+table_name+'_year_num] DEFAULT (''1999'')'
FROM information_schema.tables ;
David Portas
SQL Server MVP
--sql
Cursor syntax / help :)
Below is the code that I have written so far, which is trying to do something like this -
1) Create table - tServiceCategory
2) Create table - tTemp
3) Populate tServiceCategory
4) Declare variables and cursor
5) Run SQL I want to cursor through
6) Open cursor
7) While @.@.FETCH_STATUS = 0 insert the values obtained by the cursor into tTemp
8) Close and deallocate cursor
9) Drop tables
CREATE TABLE tServiceCategory
(
Lower_Limit numeric,
Upper_Limit numeric,
Sort_Order numeric
)
CREATE TABLE tTemp
(
Total numeric,
Limit_Desc varchar(16)
)
INSERT INTO tServiceCategory(Lower_Limit, Upper_Limit, Sort_Order) VALUES (0, 6, 1)
INSERT INTO tServiceCategory(Lower_Limit, Upper_Limit, Sort_Order) VALUES (7, 12, 2)
INSERT INTO tServiceCategory(Lower_Limit, Upper_Limit, Sort_Order) VALUES (13, 24, 3)
INSERT INTO tServiceCategory(Lower_Limit, Upper_Limit, Sort_Order) VALUES (25, 60, 4)
INSERT INTO tServiceCategory(Lower_Limit, Upper_Limit, Sort_Order) VALUES (61, 120 , 5)
INSERT INTO tServiceCategory(Lower_Limit, Upper_Limit, Sort_Order) VALUES (121, 240, 6)
INSERT INTO tServiceCategory(Lower_Limit, Upper_Limit, Sort_Order) VALUES (241, 1200, 7)
DECLARE @.Total numeric
DECLARE @.Limit_Description varchar(16)
DECLARE MyCursor CURSOR FOR
SELECT Count(*) AS 'Total'
,CAST(Lower_Limit AS VARCHAR) +
(CASE WHEN Sort_Order = (SELECT Max(Sort_Order) FROM dbo.tServiceCategory)
THEN '+'
ELSE ( + ' to ' + CAST(Upper_Limit AS VARCHAR))
END) + ' months'
AS Limit_Description
FROM Employee e
INNER JOIN tServiceCategory s
ON DateDiff(mm, e.continuous_start_date, GetDate()) BETWEEN s.Lower_Limit AND s.Upper_Limit
GROUP
BY s.Sort_Order, s.Lower_Limit, s.Upper_Limit
ORDER
BY s.Sort_Order
OPEN MyCursor
-- FETCH NEXT FROM MyCursor
-- INTO @.Total, @.Limit_Description
WHILE @.@.FETCH_STATUS = 0
BEGIN
FETCH NEXT FROM MyCursor
INTO @.Total, @.Limit_Description
INSERT INTO tTemp(Total) VALUES (@.Total)
END
SELECT * FROM tTemp
SELECT Count(*) AS 'Total'
,CAST(Lower_Limit AS VARCHAR) +
(CASE WHEN Sort_Order = (SELECT Max(Sort_Order) FROM dbo.tServiceCategory)
THEN '+'
ELSE ( + ' to ' + CAST(Upper_Limit AS VARCHAR))
END) + ' months'
AS Limit_Description
FROM Employee e
INNER JOIN tServiceCategory s
ON DateDiff(mm, e.continuous_start_date, GetDate()) BETWEEN s.Lower_Limit AND s.Upper_Limit
GROUP
BY s.Sort_Order, s.Lower_Limit, s.Upper_Limit
ORDER
BY s.Sort_Order
CLOSE MyCursor
DEALLOCATE MyCursor
DROP TABLE tTemp
DROP TABLE tServiceCategory
Results
Select * FROM Ttemp
Total | Limit_Desc
------
Total | Limit_Desc
------
227 0 to 6 months
448 7 to 12 months
573 13 to 24 months
910 25 to 60 months
911 61 to 120 months
614 121 to 240 months
250 241+ months
So it appears that tTemp is not getting populated... But I'm banging my head against the wall with these cursors, and I can't work out what I'm doing wrong :p
If I havn't provided enough information then let me know please :)
-GeorgeVAre you doing this for fun or because you think you need to? Coz a cursor does not look like the ideal mechanism here.|||Beause I've been asked to make this a query in FoxPro so that our users can run it... Except the system doesn't support the kind of join in a regular query, so I'm making it a process. I am trying to put the results of the SQL statement into a temporary table so I can report on it... Complicated to explain, but this was the solution I came up with!
If you can think of a better way then please feel free to pass opinion :)|||What is the value of @.@.FETCH_STATUS before the first fetch?
I usually fetch before checking that value, like so:
FETCH NEXT FROM MyCursor
INTO @.Total, @.Limit_Description
WHILE @.@.FETCH_STATUS = 0
BEGIN
INSERT INTO tTemp(Total) VALUES (@.Total)
FETCH NEXT FROM MyCursor
INTO @.Total, @.Limit_Description
END|||Are you able to create a view\ stored procedure in sql server and call that from fox pro?|||Also - your problem is the bit you commented out. Why you do that George? Why? :)|||Oops - you also need to jiggle a couple of lines:
CREATE TABLE tServiceCategory
(
Lower_Limit numeric,
Upper_Limit numeric,
Sort_Order numeric
)
CREATE TABLE tTemp
(
Total numeric,
Limit_Desc varchar(16)
)
CREATE TABLE Employee
(
continuous_start_date SMALLDATETIME
)
INSERT INTO employee
SELECT '20050101'
UNION ALL
SELECT '20060101'
UNION ALL
SELECT '20070101'
UNION ALL
SELECT '20070202'
INSERT INTO tServiceCategory(Lower_Limit, Upper_Limit, Sort_Order) VALUES (0, 6, 1)
INSERT INTO tServiceCategory(Lower_Limit, Upper_Limit, Sort_Order) VALUES (7, 12, 2)
INSERT INTO tServiceCategory(Lower_Limit, Upper_Limit, Sort_Order) VALUES (13, 24, 3)
INSERT INTO tServiceCategory(Lower_Limit, Upper_Limit, Sort_Order) VALUES (25, 60, 4)
INSERT INTO tServiceCategory(Lower_Limit, Upper_Limit, Sort_Order) VALUES (61, 120 , 5)
INSERT INTO tServiceCategory(Lower_Limit, Upper_Limit, Sort_Order) VALUES (121, 240, 6)
INSERT INTO tServiceCategory(Lower_Limit, Upper_Limit, Sort_Order) VALUES (241, 1200, 7)
DECLARE @.Total numeric
DECLARE @.Limit_Description varchar(16)
DECLARE MyCursor CURSOR FOR
SELECT Count(*) AS 'Total'
,CAST(Lower_Limit AS VARCHAR) +
(CASE WHEN Sort_Order = (SELECT Max(Sort_Order) FROM dbo.tServiceCategory)
THEN '+'
ELSE ( + ' to ' + CAST(Upper_Limit AS VARCHAR))
END) + ' months'
AS Limit_Description
FROM Employee e
INNER JOIN tServiceCategory s
ON DateDiff(mm, e.continuous_start_date, GetDate()) BETWEEN s.Lower_Limit AND s.Upper_Limit
GROUP
BY s.Sort_Order, s.Lower_Limit, s.Upper_Limit
ORDER
BY s.Sort_Order
OPEN MyCursor
FETCH NEXT FROM MyCursor
INTO @.Total, @.Limit_Description
WHILE @.@.FETCH_STATUS = 0
BEGIN
INSERT INTO tTemp(Total) VALUES (@.Total)
FETCH NEXT FROM MyCursor
INTO @.Total, @.Limit_Description
END
SELECT * FROM tTemp
SELECT Count(*) AS 'Total'
,CAST(Lower_Limit AS VARCHAR) +
(CASE WHEN Sort_Order = (SELECT Max(Sort_Order) FROM dbo.tServiceCategory)
THEN '+'
ELSE ( + ' to ' + CAST(Upper_Limit AS VARCHAR))
END) + ' months'
AS Limit_Description
FROM Employee e
INNER JOIN tServiceCategory s
ON DateDiff(mm, e.continuous_start_date, GetDate()) BETWEEN s.Lower_Limit AND s.Upper_Limit
GROUP
BY s.Sort_Order, s.Lower_Limit, s.Upper_Limit
ORDER
BY s.Sort_Order
CLOSE MyCursor
DEALLOCATE MyCursor
DROP TABLE tTemp
DROP TABLE tServiceCategory
DROP TABLE Employee|||Original
OPEN MyCursor
-- FETCH NEXT FROM MyCursor
-- INTO @.Total, @.Limit_Description
WHILE @.@.FETCH_STATUS = 0
BEGIN
FETCH NEXT FROM MyCursor
INTO @.Total, @.Limit_Description
INSERT INTO tTemp(Total) VALUES (@.Total)
END
With changes (they seem so obvious now!)
OPEN MyCursor
FETCH NEXT FROM MyCursor
INTO @.Total, @.Limit_Description
WHILE @.@.FETCH_STATUS = 0
BEGIN
INSERT INTO tTemp(Total) VALUES (@.Total)
FETCH NEXT FROM MyCursor
INTO @.Total, @.Limit_Description
END
Thank you for your help guys, much appreciated. My first attempt at a cursor wasn't so bad ;)
*gives Poots and ivon gold stars* :)|||My first attempt at a cursor wasn't so bad ;)
Apart from the fact that a cursor appears totally inappropriate for what you are doing ;) have you not had the "OMG - don't write cursors unless you are certain there is no other way to do it" speil yet?|||OOh, nobody has given me that talk so far!
The resident SQL expert uses cursors a fair amount, so he's not likely to give me "the talk" :p
So what would be my other options? I'm more than willing to re-evaluate my approach... But coding in our system sucks, I don't need a cursor or anything if I didn't have to make it available to users... I hate users! :D|||If you can think of a better way then please feel free to pass opinion :)Two cursor-less alternatives:
CREATE TABLE tServiceCategory
(
Lower_Limit numeric,
Upper_Limit numeric,
Sort_Order numeric
)
CREATE TABLE tTemp
(
Total numeric,
Limit_Desc varchar(16)
)
CREATE TABLE Employee
(
continuous_start_date SMALLDATETIME
)
INSERT INTO employee
SELECT '20050101'
UNION ALL
SELECT '20060101'
UNION ALL
SELECT '20070101'
UNION ALL
SELECT '20070202'
INSERT INTO tServiceCategory(Lower_Limit, Upper_Limit, Sort_Order) VALUES (0, 6, 1)
INSERT INTO tServiceCategory(Lower_Limit, Upper_Limit, Sort_Order) VALUES (7, 12, 2)
INSERT INTO tServiceCategory(Lower_Limit, Upper_Limit, Sort_Order) VALUES (13, 24, 3)
INSERT INTO tServiceCategory(Lower_Limit, Upper_Limit, Sort_Order) VALUES (25, 60, 4)
INSERT INTO tServiceCategory(Lower_Limit, Upper_Limit, Sort_Order) VALUES (61, 120 , 5)
INSERT INTO tServiceCategory(Lower_Limit, Upper_Limit, Sort_Order) VALUES (121, 240, 6)
INSERT INTO tServiceCategory(Lower_Limit, Upper_Limit, Sort_Order) VALUES (241, 1200, 7)
GO
--Alternative #1 - use a view
CREATE VIEW myview
AS
SELECT Count(*) AS 'Total'
,CAST(Lower_Limit AS VARCHAR) +
(CASE WHEN Sort_Order = (SELECT Max(Sort_Order) FROM dbo.tServiceCategory)
THEN '+'
ELSE ( + ' to ' + CAST(Upper_Limit AS VARCHAR))
END) + ' months'
AS Limit_Description
FROM Employee e
INNER JOIN tServiceCategory s
ON DateDiff(mm, e.continuous_start_date, GetDate()) BETWEEN s.Lower_Limit AND s.Upper_Limit
GROUP BY s.Sort_Order, s.Lower_Limit, s.Upper_Limit
GO
SELECT *
FROM dbo.myview
--Alternative #2 - if you simply MUST populate a temp table use SET BASED logic
INSERT INTO tTemp (total, limit_desc)
SELECT Count(*) AS 'Total'
,CAST(Lower_Limit AS VARCHAR) +
(CASE WHEN Sort_Order = (SELECT Max(Sort_Order) FROM dbo.tServiceCategory)
THEN '+'
ELSE ( + ' to ' + CAST(Upper_Limit AS VARCHAR))
END) + ' months'
AS Limit_Description
FROM Employee e
INNER JOIN tServiceCategory s
ON DateDiff(mm, e.continuous_start_date, GetDate()) BETWEEN s.Lower_Limit AND s.Upper_Limit
GROUP BY s.Sort_Order, s.Lower_Limit, s.Upper_Limit
SELECT *
FROM dbo.ttemp
DROP TABLE tTemp
DROP TABLE tServiceCategory
DROP TABLE Employee
DROP VIEW myview|||The resident SQL expert uses cursors a fair amount, so he's not likely to give me "the talk" :p
Either he is doing a lot of specialised struff or he is not a SQL expert.
SQL Server is rubbish at iterative stuff - SQL is a declarative, set based language. ALWAYS try to do everything set based where possible and only consider curosrs as a last resort. This is an area where a lot of procedural coders get tripped up when programming in SQL.
Cursors are useful for:
Admin DDL (building dynamic strings by looping through "collections" (for example looping through a table with database names and performing the same SQL action on each database)).
Certain DML statements where "previous"\ "later" rows (logically speaking of course ;)) need to be prepared to the "current" row (e.g. culminative row counts). Even here though you are best off testing. I have some links to articles if you would like.
I can't, off the top of my head, think of another time you would want to use a cursor.
HTH|||INSERT INTO! D'oh!
Well, it was nice learning cursors a wee bit anyway ;)
Why didn't I think of that?
Well, I guess it's high time to port this into FoxPro so I can play with it and see what damage I can cause :D
The table isn't neccessarily temporary, as in, it might not be dropped depending on how I can get FoxPro to interact with temporary tables... We'll see I suppose!
I'll definately come back with an answer on how I solved the overall problem :D|||... and finally. Do you remember me saying I am hopeless with cursor syntax? The reason is the above - I barely use them. In fact, I code up loops anyway so I never use them but the point is I do very little iterative stuff in SQL.
:)|||I'll definately come back with an answer on how I solved the overall problem :DHeh heh - if you want one last bit of advice - dump the temp table thing too and just use the view. My last tuppeneth I promise ;)|||Always open to advice :)
I don't think it's going to be a temp table or a view - I think it's simply going to be a table, which will be populated once and left to rot. I just needed a way of putting the results of my SQL statement into a table so I could display them for the user.
Thanks for everything Poots :beer:|||I don't think it's going to be a temp table or a view - I think it's simply going to be a table, which will be populated once and left to rot. I just needed a way of putting the results of my SQL statement into a table so I could display them for the user.
My last tuppeneth I promise ;)must... try ... to ...resist...
it's no good - what happens next month when all your counts are out?|||Ah sorry, meant to clarify that.
This little fella will run before you run the INSERT INTO
DELETE FROM <mytable>|||Hmm, so my insert into wasn't working, so I tried views.
...Which works fantastically well using QA...
But the view is not picked up by the system and cannot be created the same by the system either...
Looks like the temp table + cursor might be the way to go (*sigh*)
I hate FoxPro / our HR system.
I'll keep you posted.|||Hmm, so my insert into wasn't working, so I tried views.
...Which works fantastically well using QA...
But the view is not picked up by the system and cannot be created the same by the system either...
Looks like the temp table + cursor might be the way to go (*sigh*)
I hate FoxPro / our HR system.
I'll keep you posted.No - trouble shoot the view. The cursor is terrible. The delete\ insert is not much cop either.
Volatile data like this should always be derived at run time rather than stored if at all possible.
What do you mean by " the view is not picked up by the system and cannot be created the same by the system either..."?|||the system can only see views that it creates using it's in built data dictionary. Anything I produce in QA or EM simply canot be seen by the system - you cannot query it or even look at it.
The view cannot be built in the system because it exceeds the maximum characters (no matter how much I trim it down)... WHY IS THERE A LIMIT?!?
I'm afraid to say that I'm fed up of this problem today, so I'm going to get on with something else. The problem was solved hours and hours ago in QA, but porting this into our system is an absolute bitch.|||Ah - I think I see.
A third party system?
What is the char limit? Is it a limit on the SQL within the view? Can you not just insert info into one of application tables (*note - please don't try this - just a question)?|||3rd Party... Limit on the SQL... Don't understand :p|||I've effing done it!
Created a view using the software and then altered the view in QA.
Basically tricking it into doing what I wanted it to do :)
Damn that feels good.
(EDIT: want to know the best part? I didn't have to use any FoxPro! :D:D:D:D:D)
Now... to get exclusive access so I can put this live...
Thanks to everybody's 2 cents (and Poots's $2)!
I've learned a lot and finally cracked it (technically, I guess by "hacking" the program, but still!)
Cursor question
I've recently began studying cursors. The following code is from my server but in don't understand the purpose of the highlighted part.
declare c_cursor cursor for
select distinct suniq from Stustat where trkuniq in (select trkuniq from track where schoolc = @.schoolc) and
graden >= @.beginningGradeForCalc
open c_cursor
fetch next from c_cursor into @.variable
while (@.@.fetch_status= 0)
begin
-- CHECK GPA (FIRES OFF SINGLE STUDENT DYNAMIC GPA CALCULATION FOR EACH SUNIQ IN STUGRP_ACTIVE FOR A SPECIFIED SCHOOL)
-- exec siSp_dyngpa @.suniq, @.schyear, @.graden example: exec sisp_dyngpa @.variable, 2007, 9, 1
exec sisp_dyngpa @.variable, @.beginningYrForCalc, @.beginningGradeForCalc, '1'
fetch next from c_cursor into @.variable
end
fetch next from c_cursor into @.variable
deallocate c_cursor
Is there an obvious reason for the FETCH after teh END statment?
I don't think it should be there as its outside the while loop. Doesn't serve any purpose as you are deallocating the cursor straight afterwards anyway and so no processing is done with the results.
HTH!
|||No, there is no obvious reason. also, remember to close the cursor before deallocating it.
AMB
|||What are the ramification of not closing the cursor before deallocating it? Or it is more a matter of procedure?|||I am not familiar with the internals, but I think that the description in BOL is clear.
AMB
sqlCursor Process Coding Problem
It's been awhile since I have posted. I have a situation for the group here. I am new to working with cursors. I have a simple one here that I wish to use to update NULL fields in a table called rpt_Scr_B0000_MiniFinancials. I know for a fact that there are NULLs in this table. When I run the select query from the information_schema I get some 60 some odd fields. Anyway, when I run this I get 0 records affected which I know is incorrect. It appears that my cursor is only processing for the first field. I tried changing the @.@.FETCH_STATUS = 0 to @.@.FETCH_STATUS > 0 and that didn't work either. What am I doing wrong? Thx.
DECLARE @.FieldName char (25)
DECLARE cursor_update_rpt_Scr_B0000_MiniFinancials CURSOR For
select column_name
from information_schema.columns
where table_name = 'rpt_Scr_B0000_MiniFinancials'
open cursor_update_rpt_Scr_B0000_MiniFinancials
FETCH NEXT FROM cursor_update_rpt_Scr_B0000_MiniFinancials
INTO @.FieldName
update rpt_Scr_B0000_MiniFinancials
set @.FieldName = 0
where @.FieldName is null
WHILE @.@.FETCH_STATUS = 0
BEGIN
FETCH NEXT FROM cursor_update_rpt_Scr_B0000_MiniFinancials
INTO @.FieldName
END
CLOSE cursor_update_rpt_Scr_B0000_MiniFinancials
DEALLOCATE cursor_update_rpt_Scr_B0000_MiniFinancialsyour update needs to be inside the WHILE Loop
But aren't you worried about datatypes...and what's wrong with nulls annyway
(Here we go again)|||Ok,
I tried that but now I get all zeros. This is a step forward. I have a table with 66 fields and five records. It appears it is now processing each update but there is still something wrong. Say one of the fields, ie 'abc' has 3 records populated leaving two nulls, the two nulls should be turned into zeros. The issue is that the front end programmer creating the view wants me to populate the nulls with zeros. Is it easier if I use a coalesce function in some way instead?
Here is the updated code:
DECLARE @.FieldName char (25)
DECLARE cursor_update_rpt_Scr_B0000_MiniFinancials CURSOR For
select column_name
from information_schema.columns
where table_name = 'rpt_Scr_B0000_MiniFinancials'
open cursor_update_rpt_Scr_B0000_MiniFinancials
FETCH NEXT FROM cursor_update_rpt_Scr_B0000_MiniFinancials
INTO @.FieldName
WHILE @.@.FETCH_STATUS = 0
BEGIN
update rpt_Scr_B0000_MiniFinancials
set @.FieldName = 0
where @.FieldName is null
FETCH NEXT FROM cursor_update_rpt_Scr_B0000_MiniFinancials
INTO @.FieldName
END|||Well I would take a different approach...you do know what happens when you assign a 0 to a datetime column don't you. Anyway, cut and paste this code example into query analyzer...it should run no problem.
USE Northwind
GO
CREATE TABLE myTable99(Col1 int, Col2 char(1), Col3 datetime)
GO
INSERT INTO myTable99(Col1,Col2,Col3)
SELECT 1 , null, '2006-01-01' UNION ALL
SELECT null, 'b' , '2006-01-02' UNION ALL
SELECT 3 , 'c' , null
GO
SELECT * FROM myTable99
GO
DECLARE @.sql varchar(8000), @.collist varchar(8000), @.TABLE_NAME sysname
SET @.TABLE_NAME = 'myTable99'
SELECT @.collist = COALESCE(@.collist+', ','') + COLUMN_NAME + ' = '
+ 'CASE WHEN ' + COLUMN_NAME + ' IS NULL THEN '
+ CASE WHEN DATA_TYPE IN ('char','nchar','varchar','nvarchar','text','ntext ') THEN ''''+'0'+'''' ELSE '0' END
+ ' ELSE ' + COLUMN_NAME + ' END'
FROM INFORMATION_SCHEMA.Columns
WHERE TABLE_NAME = @.TABLE_NAME
SELECT @.sql = 'UPDATE ' + @.TABLE_NAME + ' SET ' + @.collist
SELECT @.sql
EXEC(@.sql)
SELECT * FROM myTable99
GO
DROP TABLE myTable99
GO|||OK,
I will take a look at your coding. I should have specified that none of the fields is a datetime. They are all money, int, real, or varchars. Thanks again for your time and diligence.
Dave|||We resolved it in-house. Here is the answer! Thanks again.
================================================== =====
DECLARE @.FieldName char (25)
DECLARE cursor_update_rpt_Scr_B0000_MiniFinancials CURSOR For
select column_name
from information_schema.columns
where table_name = 'rpt_Scr_B0000_MiniFinancials'
open cursor_update_rpt_Scr_B0000_MiniFinancials
FETCH NEXT FROM cursor_update_rpt_Scr_B0000_MiniFinancials
INTO @.FieldName
WHILE @.@.FETCH_STATUS = 0
BEGIN
execute('
update rpt_Scr_B0000_MiniFinancials
set '+@.FieldName+' = 0
where '+@.FieldName+' is null
')
FETCH NEXT FROM cursor_update_rpt_Scr_B0000_MiniFinancials
INTO @.FieldName
END
CLOSE cursor_update_rpt_Scr_B0000_MiniFinancials
DEALLOCATE cursor_update_rpt_Scr_B0000_MiniFinancials|||Well use mine anyway and blow their minds...cursors...ech
Besides mine will be faster|||WOuld setting default = 0 on the table structure accomplish what you want.|||I just tried that, one of the other guys here suggested this also. It fails our process due to the fact that there is an update statement we run to perform calculations, ie averaging. If I try to default the table values to zeros it blows up when it reaches this update with a can't divide by zero error. If the process gets to this update with NULLs it is fine as far not erroring out but these NULL fields don't get populated with zeros either. So the way it is set up I must perform a later update to make all NULLs zero. Make sense?
Davesql
Tuesday, March 27, 2012
Cursor performance
through data in TSQL, atleast that's what most performance tips tell
you. Using while loops and temporary tables, subqueries and so on.
So why does the MCAD/MCSE (SQL Server exam) preach the way of the
Cursor when they are perform so badly? Who is right in the matter?
Sorry posted to the wrong group
mrshrinkray@.googlemail.com wrote:
> It seems to be a well known fact that you avoid cursors when looping
> through data in TSQL, atleast that's what most performance tips tell
> you. Using while loops and temporary tables, subqueries and so on.
> So why does the MCAD/MCSE (SQL Server exam) preach the way of the
> Cursor when they are perform so badly? Who is right in the matter?
sql
Cursor performance
through data in TSQL, atleast that's what most performance tips tell
you. Using while loops and temporary tables, subqueries and so on.
So why does the MCAD/MCSE (SQL Server exam) preach the way of the
Cursor when they are perform so badly? Who is right in the matter?Sorry posted to the wrong group
mrshrinkray@.googlemail.com wrote:
> It seems to be a well known fact that you avoid cursors when looping
> through data in TSQL, atleast that's what most performance tips tell
> you. Using while loops and temporary tables, subqueries and so on.
> So why does the MCAD/MCSE (SQL Server exam) preach the way of the
> Cursor when they are perform so badly? Who is right in the matter?
Cursor performance
through data in TSQL, atleast that's what most performance tips tell
you. Using while loops and temporary tables, subqueries and so on.
So why does the MCAD/MCSE (SQL Server exam) preach the way of the
Cursor when they are perform so badly? Who is right in the matter?Sorry posted to the wrong group
mrshrinkray@.googlemail.com wrote:
> It seems to be a well known fact that you avoid cursors when looping
> through data in TSQL, atleast that's what most performance tips tell
> you. Using while loops and temporary tables, subqueries and so on.
> So why does the MCAD/MCSE (SQL Server exam) preach the way of the
> Cursor when they are perform so badly? Who is right in the matter?
Cursor inside a cursor
declare Q cursor for
select systudentid from satrans
declare @.id int
open Q
fetch next from Q into @.id
while @.@.fetch_status = 0
begin
declare c cursor for
Select
b.ssn,
SaTrans.SyStudentID,
satrans.date,
satrans.type,
SaTrans.SyCampusID,
Amount = Case SaTrans.Type
When 'P' Then SaTrans.Amount * -1
When 'C' Then SaTrans.Amount * -1
Else SaTrans.Amount END
From SaTrans , systudent b where satrans.systudentid = b.systudentid
and satrans.systudentid = @.id
declare @.arbalance money, @.type varchar, @.ssn varchar, @.amount money, @.systudentid int, @.transdate datetime, @.sycampusid int, @.before money
set @.arbalance = 0
open c
fetch next from c into @.ssn, @.systudentid, @.transdate, @.type, @.sycampusid, @.amount
while @.@.fetch_status = 0
begin
set @.arbalance = @.arbalance + @.amount
set @.before = @.arbalance -@.amount
insert c2000_utility1..tempbalhistory1
select @.systudentid systudentid, @.sycampusid sycampusid, @.transdate transdate, @.amount amount, @.type type, @.arbalance Arbalance, @.before BeforeBalance
where( convert (int,@.amount) <= -50
or @.amount * -1 > @.before * .02)
and @.type = 'P'
fetch next from c into @.ssn, @.systudentid, @.transdate, @.type, @.sycampusid, @.amount
end
close c
deallocate c
fetch next from Q into @.id
end
close Q
deallocate Q
select * from c2000_utility1..tempbalhistory1
truncate table c2000_utility1..tempbalhistory1Did you write this? Or was it given to you?
You don't need a cursor at all for this (although I'm having trouble trying to figure out what you're trying to do)...
Lose Cursor 1 altogethr.
Use the SELECT (which already has the table in it you want) as the Portion of the INSERT Statement...that's it...
Except for this
where( convert (int,@.amount) <= -50
or @.amount * -1 > @.before * .02)
and @.type = 'P'
Which I have no idea what you want.
I expect all you need to do is add that to the select
Sunday, March 25, 2012
cursor in Stored Procedures
Quote:
Originally Posted by hariharanmca
any one Explain me the details about Cursors in Stored Procedures and is there any other way to call views in stored Procedure
Its very Urgent, If i simply write select * from vw_viewName then its giving Error like
Error:
=================================
Server: Msg 8624, Level 16, State 16, Procedure sp_Add_Remove_ItemQtyForNonChargeOrder , Line 18
Internal SQL Server error.
Line 18 is select * from vw_viewName|||See problem description here.
Cursor help PLEASE!
queries and I'm pretty adept at them. This will be running once a day
in the wee small hours when minimal server activity will be taking
place, it will be handling 700-1000ish records. The box is a P4/SQL
2000 with lots of ram and multiple CPUs.
The code for creating and populating the table in question follows the
cursor code.
The application is for medical transport billing. We take people to
the doctor and home again and the health plan pays us. A one-way
trip, home -> doctor, is a single line item'. A round trip, home ->
doctor -> home is rolled up, the charge summed, and billed as a single
line item. A three-leg, home -> doctor -> pharmacy -> home, is billed
as three line items.
This code is just for identifying the data, once this works correctly
I'll add the code in for doing the rollup and I'm confident I can
handle that.
If I ruled the world, every leg of every trip would be a single line
item and I wouldn't have to deal with this rollup BS, but I don't make
the policy, I just have to code it. <g
A trip is a round trip if the date, account number, and passenger name
is the same and the origin street of record X equals the destination
street of record X+1. The problem is that X+1 could be the start of a
round trip and X+2 could be the completing leg of a round trip. So
you could have a scenario of hospital -> home -> doctor -> home in
which X is one-way and X+1 & X+2 form a round trip.
BLERG! Any help is greatly appreciated, it has me stumped.
/*
select trip_id, acct_number, passenger, street, dest_street,
flat_rate, screated, smeteroff, remark1, remark2
from zvoucherstodbf order by cast(screated as smalldatetime),
acct_number, passenger, smeteroff
*/
declare @.roundtrip integer
declare @.cmsg char(200)
declare @.Trip_ID char(11)
declare @.acct_number char(11)
declare @.passenger char(12)
declare @.created char(22)
declare @.meter_off char(22)
declare @.street char(32)
declare @.dest_street char(32)
declare @.remark1 char(32)
declare @.remark2 char(32)
declare @.flat_rate smallint
declare @.prev_cmsg char(200)
declare @.prev_Trip_ID char(11)
declare @.prev_acct_number char(11)
declare @.prev_passenger char(12)
declare @.prev_created char(22)
declare @.prev_meter_off char(22)
declare @.prev_street char(32)
declare @.prev_dest_street char(32)
declare @.prev_remark1 char(32)
declare @.prev_remark2 char(32)
declare @.prev_flat_rate smallint
declare cVoucher cursor scroll for
select trip_id, acct_number, passenger, street, dest_street, screated,
smeteroff, remark1, remark2, flat_rate
from zVouchersToDBF
--where screated = '12/03/03'
order by screated, acct_number, passenger, smeteroff
open cVoucher
--Load the @.Prev_ (previous record) variables with the first record
fetch from cVoucher into @.prev_trip_id, @.prev_acct_number,
@.prev_passenger,
@.prev_street, @.prev_dest_street, @.prev_created, @.prev_meter_off,
@.prev_remark1, @.prev_remark2, @.prev_flat_rate
--Initialize current variables
select @.trip_id = @.prev_trip_id
select @.acct_number = @.prev_acct_number
select @.passenger = @.prev_passenger
select @.street = @.prev_street
select @.dest_street = @.prev_dest_street
select @.created = @.prev_created
select @.meter_off = @.prev_meter_off
select @.remark1 = @.prev_remark1
select @.remark2 = @.prev_remark2
while @.@.fetch_status = 0--not EOF
begin
select @.roundtrip = 0
if (@.prev_created = @.created) and (@.prev_acct_number = @.acct_number)
and (@.prev_passenger = @.passenger)and (@.prev_street =
@.dest_street)-- MATCH! Apparent round trip
begin
select @.roundtrip = 1
select @.prev_trip_id = @.trip_id
select @.prev_acct_number = @.acct_number
select @.prev_passenger = @.passenger
select @.prev_street = @.street
select @.prev_dest_street = @.dest_street
select @.prev_created = @.created
select @.prev_meter_off = @.meter_off
select @.prev_remark1 = @.remark1
select @.prev_remark2 = @.remark2
end
if (@.roundtrip = 0)
begin
fetch next from cVoucher into @.trip_id, @.acct_number, @.passenger,
@.street, @.dest_street, @.created, @.meter_off, @.remark1, @.remark2,
@.flat_rate
if (@.prev_created = @.created) and (@.prev_acct_number = @.acct_number)
and (@.prev_passenger = @.passenger)and (@.prev_street =
@.dest_street)-- MATCH! Apparent round trip
select @.roundtrip = 1
else
--definitely one-way trip
select @.roundtrip = 0
fetch prior from cVoucher into @.trip_id, @.acct_number, @.passenger,
@.street, @.dest_street, @.created, @.meter_off, @.remark1, @.remark2,
@.flat_rate
end
if (@.roundtrip = 1)
begin
select @.cMsg = 'Start: ' + rtrim(@.prev_created) + ' ' +
rtrim(@.prev_trip_id) + ': ' + @.prev_acct_number + ' ' +
rtrim(@.prev_meter_off) + ' ' + @.prev_passenger + ' ' +
rtrim(@.prev_street) + ' to ' + @.prev_dest_street + ' ' + @.prev_remark1
+ ' ' + @.prev_remark2
print @.cMsg
select @.cMsg = 'End: ' + rtrim(@.created) + ' ' + rtrim(@.trip_id) +
': ' + @.acct_number + ' ' + rtrim(@.meter_off) + ' ' + @.passenger + ' '
+ rtrim(@.street) + ' to ' + @.dest_street + ' ' + @.remark1 + ' ' +
@.remark2
print @.cMsg
print ''
end
else
begin
select @.cMsg = 'One-Way: ' + rtrim(@.created) + ' ' + rtrim(@.trip_id)
+ ': ' + @.acct_number + ' ' + rtrim(@.meter_off) + ' ' + @.passenger + '
' + rtrim(@.street) + ' to ' + @.dest_street + ' ' + @.remark1 + ' ' +
@.remark2
print @.cMsg
print ''
end
select @.prev_trip_id = @.trip_id
select @.prev_acct_number = @.acct_number
select @.prev_passenger = @.passenger
select @.prev_street = @.street
select @.prev_dest_street = @.dest_street
select @.prev_created = @.created
select @.prev_meter_off = @.meter_off
select @.prev_remark1 = @.remark1
select @.prev_remark2 = @.remark2
fetch next from cVoucher into @.trip_id, @.acct_number, @.passenger,
@.street, @.dest_street, @.created, @.meter_off, @.remark1, @.remark2,
@.flat_rate
end
close cVoucher
--/*
--This code works for displaying the data set as a whole
-- so you can visually identify what constitutes a round trip.
open cVoucher
fetch from cVoucher into @.trip_id, @.acct_number, @.passenger,
@.street, @.dest_street, @.created, @.meter_off, @.remark1, @.remark2,
@.flat_rate
while @.@.fetch_status = 0
begin
select @.cMsg = rtrim(@.created) + ' ' + rtrim(@.trip_id) + ': ' +
@.acct_number + ' ' + @.passenger + ' ' + @.street + ' ' + @.dest_street +
' ' + @.meter_off + ' ' + @.remark1 + ' ' + @.remark2
print @.cMsg
fetch next from cVoucher into @.trip_id, @.acct_number, @.passenger,
@.street, @.dest_street, @.created, @.meter_off, @.remark1, @.remark2,
@.flat_rate
end
close cVoucher
--*/
deallocate cVoucher
CREATE TABLE [zVouchersToDBF] (
[house] [char] (5) NULL ,
[street] [char] (32) NULL ,
[district] [char] (8) NULL ,
[passenger] [char] (12) NULL ,
[remark1] [char] (32) NULL ,
[remark2] [char] (32) NULL ,
[dest_house] [char] (5) NULL ,
[dest_street] [char] (32) NULL ,
[dest_district] [char] (13) NULL ,
[acct_number] [char] (11) NULL ,
[sub_acct_number] [char] (15) NULL ,
[flat_rate] [money] NULL ,
[car] [char] (3) NULL ,
[driver_id] [char] (9) NULL ,
[meter_on] [char] (5) NULL ,
[meter_off] [char] (5) NULL ,
[fare] [char] (9) NULL ,
[cancelled] [char] (21) NULL ,
[no_trip] [char] (7) NULL ,
[no_trip_reason] [int] NULL ,
[auth_number] [char] (32) NULL ,
[auth_name] [char] (32) NULL ,
[trip_id] [char] (7) NULL ,
[created] [char] (8) NULL ,
[patient_birthday] [char] (16) NULL ,
[waittime] [char] (3) NULL ,
[sNoTrip] [char] (22) NULL ,
[sMeterOn] [char] (22) NULL ,
[sMeterOff] [char] (22) NULL ,
[sCancelled] [char] (22) NULL ,
[sCreated] [char] (22) NULL ,
[sPatientBirthday] [char] (22) NULL ,
[SystemRate] [money] NULL
) ON [PRIMARY]
GO
Insert zvoucherstodbf
Values (null,'100 E 1st',null,'A','X','Y',null,'200 W
2nd',null,'1000',null,5.00,null,null,null,'13:20', '5',null,null,null,null,null,'1',null,null,null,nu ll,null,'13:20',null,'12/8/2003',null,null)
Insert zvoucherstodbf
Values (null,'200 W 2nd',null,'A','X','Y',null,'100 E
1st',null,'1000',null,5.00,null,null,null,'14:20', '5',null,null,null,null,null,'2',null,null,null,nu ll,null,'14:20',null,'12/8/2003',null,null)
Insert zvoucherstodbf
Values (null,'101 E 101',null,'B','X','Y',null,'202 W
202',null,'2000',null,10.00,null,null,null,'13:50' ,'10',null,null,null,null,null,'3',null,null,null, null,null,'13:50',null,'12/8/2003',null,null)
Insert zvoucherstodbf
Values (null,'123 N 456',null,'C','X','Y',null,'234 S
321',null,'2000',null,5.00,null,null,null,'13:51', '5',null,null,null,null,null,'4',null,null,null,nu ll,null,'13:51',null,'12/8/2003',null,null)
Insert zvoucherstodbf
Values (null,'999 N 666',null,'D','X','Y',null,'666 S
999',null,'1000',null,7.50,null,null,null,'14:00', '7.5',null,null,null,null,null,'5',null,null,null, null,null,'14:00',null,'12/8/2003',null,null)
Insert zvoucherstodbf
Values (null,'666 S 999',null,'D','X','Y',null,'999 N
666',null,'1000',null,8.00,null,null,null,'14:30', '8',null,null,null,null,null,'6',null,null,null,nu ll,null,'14:30',null,'12/8/2003',null,null)
Insert zvoucherstodbf
Values (null,'123 n 456',null,'E','X','Y',null,'456 s
789',null,'3000',null,5.00,null,null,null,'14:30', '5',null,null,null,null,null,'7',null,null,null,nu ll,null,'14:30',null,'12/8/2003',null,null)You need to re-design to db
Tables
Account <-- store user info
Trip <-- Stores user info and date
TripDetail <-- stores trip, where , from
Triptype ,-subtable
"P.D.N. Tame" <wwphx@.hotmail.com> wrote in message
news:bcc5d277.0312081450.10e74cfc@.posting.google.c om...
> Yes, I know that cursors are gauche, but I can't see a solution using
> queries and I'm pretty adept at them. This will be running once a day
> in the wee small hours when minimal server activity will be taking
> place, it will be handling 700-1000ish records. The box is a P4/SQL
> 2000 with lots of ram and multiple CPUs.
> The code for creating and populating the table in question follows the
> cursor code.
> The application is for medical transport billing. We take people to
> the doctor and home again and the health plan pays us. A one-way
> trip, home -> doctor, is a single 'line item'. A round trip, home ->
> doctor -> home is rolled up, the charge summed, and billed as a single
> line item. A three-leg, home -> doctor -> pharmacy -> home, is billed
> as three line items.
> This code is just for identifying the data, once this works correctly
> I'll add the code in for doing the rollup and I'm confident I can
> handle that.
> If I ruled the world, every leg of every trip would be a single line
> item and I wouldn't have to deal with this rollup BS, but I don't make
> the policy, I just have to code it. <g>
> A trip is a round trip if the date, account number, and passenger name
> is the same and the origin street of record X equals the destination
> street of record X+1. The problem is that X+1 could be the start of a
> round trip and X+2 could be the completing leg of a round trip. So
> you could have a scenario of hospital -> home -> doctor -> home in
> which X is one-way and X+1 & X+2 form a round trip.
> BLERG! Any help is greatly appreciated, it has me stumped.
>
> /*
> select trip_id, acct_number, passenger, street, dest_street,
> flat_rate, screated, smeteroff, remark1, remark2
> from zvoucherstodbf order by cast(screated as smalldatetime),
> acct_number, passenger, smeteroff
> */
> declare @.roundtrip integer
> declare @.cmsg char(200)
> declare @.Trip_ID char(11)
> declare @.acct_number char(11)
> declare @.passenger char(12)
> declare @.created char(22)
> declare @.meter_off char(22)
> declare @.street char(32)
> declare @.dest_street char(32)
> declare @.remark1 char(32)
> declare @.remark2 char(32)
> declare @.flat_rate smallint
> declare @.prev_cmsg char(200)
> declare @.prev_Trip_ID char(11)
> declare @.prev_acct_number char(11)
> declare @.prev_passenger char(12)
> declare @.prev_created char(22)
> declare @.prev_meter_off char(22)
> declare @.prev_street char(32)
> declare @.prev_dest_street char(32)
> declare @.prev_remark1 char(32)
> declare @.prev_remark2 char(32)
> declare @.prev_flat_rate smallint
> declare cVoucher cursor scroll for
> select trip_id, acct_number, passenger, street, dest_street, screated,
> smeteroff, remark1, remark2, flat_rate
> from zVouchersToDBF
> --where screated = '12/03/03'
> order by screated, acct_number, passenger, smeteroff
> open cVoucher
> --Load the @.Prev_ (previous record) variables with the first record
> fetch from cVoucher into @.prev_trip_id, @.prev_acct_number,
> @.prev_passenger,
> @.prev_street, @.prev_dest_street, @.prev_created, @.prev_meter_off,
> @.prev_remark1, @.prev_remark2, @.prev_flat_rate
> --Initialize current variables
> select @.trip_id = @.prev_trip_id
> select @.acct_number = @.prev_acct_number
> select @.passenger = @.prev_passenger
> select @.street = @.prev_street
> select @.dest_street = @.prev_dest_street
> select @.created = @.prev_created
> select @.meter_off = @.prev_meter_off
> select @.remark1 = @.prev_remark1
> select @.remark2 = @.prev_remark2
> while @.@.fetch_status = 0 --not EOF
> begin
> select @.roundtrip = 0
> if (@.prev_created = @.created) and (@.prev_acct_number = @.acct_number)
> and (@.prev_passenger = @.passenger) and (@.prev_street =
> @.dest_street) -- MATCH! Apparent round trip
> begin
> select @.roundtrip = 1
> select @.prev_trip_id = @.trip_id
> select @.prev_acct_number = @.acct_number
> select @.prev_passenger = @.passenger
> select @.prev_street = @.street
> select @.prev_dest_street = @.dest_street
> select @.prev_created = @.created
> select @.prev_meter_off = @.meter_off
> select @.prev_remark1 = @.remark1
> select @.prev_remark2 = @.remark2
> end
> if (@.roundtrip = 0)
> begin
> fetch next from cVoucher into @.trip_id, @.acct_number, @.passenger,
> @.street, @.dest_street, @.created, @.meter_off, @.remark1, @.remark2,
> @.flat_rate
> if (@.prev_created = @.created) and (@.prev_acct_number = @.acct_number)
> and (@.prev_passenger = @.passenger) and (@.prev_street =
> @.dest_street) -- MATCH! Apparent round trip
> select @.roundtrip = 1
> else
> --definitely one-way trip
> select @.roundtrip = 0
> fetch prior from cVoucher into @.trip_id, @.acct_number, @.passenger,
> @.street, @.dest_street, @.created, @.meter_off, @.remark1, @.remark2,
> @.flat_rate
> end
>
> if (@.roundtrip = 1)
> begin
> select @.cMsg = 'Start: ' + rtrim(@.prev_created) + ' ' +
> rtrim(@.prev_trip_id) + ': ' + @.prev_acct_number + ' ' +
> rtrim(@.prev_meter_off) + ' ' + @.prev_passenger + ' ' +
> rtrim(@.prev_street) + ' to ' + @.prev_dest_street + ' ' + @.prev_remark1
> + ' ' + @.prev_remark2
> print @.cMsg
> select @.cMsg = 'End: ' + rtrim(@.created) + ' ' + rtrim(@.trip_id) +
> ': ' + @.acct_number + ' ' + rtrim(@.meter_off) + ' ' + @.passenger + ' '
> + rtrim(@.street) + ' to ' + @.dest_street + ' ' + @.remark1 + ' ' +
> @.remark2
> print @.cMsg
> print ''
> end
> else
> begin
> select @.cMsg = 'One-Way: ' + rtrim(@.created) + ' ' + rtrim(@.trip_id)
> + ': ' + @.acct_number + ' ' + rtrim(@.meter_off) + ' ' + @.passenger + '
> ' + rtrim(@.street) + ' to ' + @.dest_street + ' ' + @.remark1 + ' ' +
> @.remark2
> print @.cMsg
> print ''
> end
> select @.prev_trip_id = @.trip_id
> select @.prev_acct_number = @.acct_number
> select @.prev_passenger = @.passenger
> select @.prev_street = @.street
> select @.prev_dest_street = @.dest_street
> select @.prev_created = @.created
> select @.prev_meter_off = @.meter_off
> select @.prev_remark1 = @.remark1
> select @.prev_remark2 = @.remark2
> fetch next from cVoucher into @.trip_id, @.acct_number, @.passenger,
> @.street, @.dest_street, @.created, @.meter_off, @.remark1, @.remark2,
> @.flat_rate
> end
> close cVoucher
> --/*
> --This code works for displaying the data set as a whole
> -- so you can visually identify what constitutes a round trip.
> open cVoucher
> fetch from cVoucher into @.trip_id, @.acct_number, @.passenger,
> @.street, @.dest_street, @.created, @.meter_off, @.remark1, @.remark2,
> @.flat_rate
> while @.@.fetch_status = 0
> begin
> select @.cMsg = rtrim(@.created) + ' ' + rtrim(@.trip_id) + ': ' +
> @.acct_number + ' ' + @.passenger + ' ' + @.street + ' ' + @.dest_street +
> ' ' + @.meter_off + ' ' + @.remark1 + ' ' + @.remark2
> print @.cMsg
> fetch next from cVoucher into @.trip_id, @.acct_number, @.passenger,
> @.street, @.dest_street, @.created, @.meter_off, @.remark1, @.remark2,
> @.flat_rate
> end
> close cVoucher
> --*/
> deallocate cVoucher
>
> CREATE TABLE [zVouchersToDBF] (
> [house] [char] (5) NULL ,
> [street] [char] (32) NULL ,
> [district] [char] (8) NULL ,
> [passenger] [char] (12) NULL ,
> [remark1] [char] (32) NULL ,
> [remark2] [char] (32) NULL ,
> [dest_house] [char] (5) NULL ,
> [dest_street] [char] (32) NULL ,
> [dest_district] [char] (13) NULL ,
> [acct_number] [char] (11) NULL ,
> [sub_acct_number] [char] (15) NULL ,
> [flat_rate] [money] NULL ,
> [car] [char] (3) NULL ,
> [driver_id] [char] (9) NULL ,
> [meter_on] [char] (5) NULL ,
> [meter_off] [char] (5) NULL ,
> [fare] [char] (9) NULL ,
> [cancelled] [char] (21) NULL ,
> [no_trip] [char] (7) NULL ,
> [no_trip_reason] [int] NULL ,
> [auth_number] [char] (32) NULL ,
> [auth_name] [char] (32) NULL ,
> [trip_id] [char] (7) NULL ,
> [created] [char] (8) NULL ,
> [patient_birthday] [char] (16) NULL ,
> [waittime] [char] (3) NULL ,
> [sNoTrip] [char] (22) NULL ,
> [sMeterOn] [char] (22) NULL ,
> [sMeterOff] [char] (22) NULL ,
> [sCancelled] [char] (22) NULL ,
> [sCreated] [char] (22) NULL ,
> [sPatientBirthday] [char] (22) NULL ,
> [SystemRate] [money] NULL
> ) ON [PRIMARY]
> GO
> Insert zvoucherstodbf
> Values (null,'100 E 1st',null,'A','X','Y',null,'200 W
2nd',null,'1000',null,5.00,null,null,null,'13:20', '5',null,null,null,null,nu
ll,'1',null,null,null,null,null,'13:20',null,'12/8/2003',null,null)
> Insert zvoucherstodbf
> Values (null,'200 W 2nd',null,'A','X','Y',null,'100 E
1st',null,'1000',null,5.00,null,null,null,'14:20', '5',null,null,null,null,nu
ll,'2',null,null,null,null,null,'14:20',null,'12/8/2003',null,null)
> Insert zvoucherstodbf
> Values (null,'101 E 101',null,'B','X','Y',null,'202 W
202',null,'2000',null,10.00,null,null,null,'13:50' ,'10',null,null,null,null,
null,'3',null,null,null,null,null,'13:50',null,'12 /8/2003',null,null)
> Insert zvoucherstodbf
> Values (null,'123 N 456',null,'C','X','Y',null,'234 S
321',null,'2000',null,5.00,null,null,null,'13:51', '5',null,null,null,null,nu
ll,'4',null,null,null,null,null,'13:51',null,'12/8/2003',null,null)
> Insert zvoucherstodbf
> Values (null,'999 N 666',null,'D','X','Y',null,'666 S
999',null,'1000',null,7.50,null,null,null,'14:00', '7.5',null,null,null,null,
null,'5',null,null,null,null,null,'14:00',null,'12 /8/2003',null,null)
> Insert zvoucherstodbf
> Values (null,'666 S 999',null,'D','X','Y',null,'999 N
666',null,'1000',null,8.00,null,null,null,'14:30', '8',null,null,null,null,nu
ll,'6',null,null,null,null,null,'14:30',null,'12/8/2003',null,null)
> Insert zvoucherstodbf
> Values (null,'123 n 456',null,'E','X','Y',null,'456 s
789',null,'3000',null,5.00,null,null,null,'14:30', '5',null,null,null,null,nu
ll,'7',null,null,null,null,null,'14:30',null,'12/8/2003',null,null)|||> The application is for medical transport billing. We take people to
> the doctor and home again and the health plan pays us. A one-way
> trip, home -> doctor, is a single ?line item'. A round trip, home ->
> doctor -> home is rolled up, the charge summed, and billed as a single
> line item. A three-leg, home -> doctor -> pharmacy -> home, is billed
> as three line items.
Hi,
I would do something like this. Use the identity function to create a
col i with 1,2,3... Then use a join to link up leg X with leg X+1.
Unfortunately I don't have time to test. Hope this gives you an idea.
-- Louis
For brevity, I'm going to simplify things.
/*fill the i column with 1,2,3,... - you can also use Update .. set
@.i=i=@.i+1
and default each leg as a single leg*/
select origin=street, dest=dest_street, date, acct, pax,
i=identity(int,1,1), tripType='single leg'
into #T
from myTable
/*mark the first leg of a roundtrip*/
update #T
set tripType='roundtrip1stLeg'
from #T as a
join #T as b
on a.i=b.i+1 and a.origin=b.dest and a.date=b.date and a.acct=b.acct
and a.pax=b.pax
/*mark the second leg of a roundtrip*/
update #T
set tripType='roundtrip2dLeg'
from #T as a
join #T as b
on a.i=b.i-1 and a.dest=b.origin and a.date=b.date and a.acct=b.acct
and a.pax=b.pax|||"David Branch" <MOVING_ON_UP@.HOTMAIL.COM> wrote in message news:<3mcBb.328$T24.143624@.news4.srv.hcvlny.cv.net>...
> You need to re-design to db
> Tables
> Account <-- store user info
> Trip <-- Stores user info and date
> TripDetail <-- stores trip, where , from
> Triptype ,-subtable
Unfortunately I can't do that. The database schema comes from a
canned vertical app and is imported from Ingress, so it's an area over
which I have pretty much zero control. The big problem is that we
don't have a master database of patients from the variety of medical
plans that we service, if I had that it would be a much simpler
problem, and this has been a problem in many other areas also.|||[posted and mailed, please reply in news]
P.D.N. Tame (wwphx@.hotmail.com) writes:
> A trip is a round trip if the date, account number, and passenger name
> is the same and the origin street of record X equals the destination
> street of record X+1. The problem is that X+1 could be the start of a
> round trip and X+2 could be the completing leg of a round trip. So
> you could have a scenario of hospital -> home -> doctor -> home in
> which X is one-way and X+1 & X+2 form a round trip.
It wasn't clear from the post, but I am assuming that the column
trip_id is actually something that identifies the orders of the trips.
I composed this query. Not really sure whether it matches your needs,
but this is something you can use as a boilerplate for further refinement.
SELECT CASE WHEN b.trip_id IS NULL THEN 'Is one-way '
ELSE 'Is round-trip with trip ' + b.trip_id
END,
a.trip_id, a.acct_number, a.passenger, a.street, a.dest_street,
a.flat_rate, a.sCreated, a.sMeterOff, a.remark1, a.remark2, b.*
FROM zvoucherstodbf a
LEFT JOIN zvoucherstodbf b
ON (convert(int, a.trip_id) + 1 = convert(int, b.trip_id)
AND a.sCreated = b.sCreated
AND a.acct_number = b.acct_number
AND a.passenger = b.passenger
AND a.sMeterOff < b.sMeterOff
AND a.street = b.dest_street)
OR (convert(int, a.trip_id) - 1 = convert(int, b.trip_id)
AND a.sCreated = b.sCreated
AND a.acct_number = b.acct_number
AND a.passenger = b.passenger
AND a.sMeterOff > b.sMeterOff
AND a.dest_street = b.street)
ORDER BY a.trip_id
--
Erland Sommarskog, SQL Server MVP, sommar@.algonet.se
Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp
Cursor Help Please
I just need some help with cursors, a topic I don't profess to be an expert in.
I've got two tables with a 1-many relationship between them. Let's say they're "tblCustomers" and "tblOrders".
tblCustomers data:
CustomerID Name
1 Fred
2 Charlie
3 Lucy
tblOrders data:
OrderID CustomerId Qty
1 1 10
2 1 5
3 1 20
4 2 8
5 3 20
6 3 6
I need to return a result set that puts all the "many" records into a single row, like:
Name Qty
Fred 10, 15, 20
Charlie 8
Lucy 20, 6
THANKS IN ADVANCE!!!!!!!!!!Create this function
CREATE Function ListOfQuantity (@.ID Varchar(100))
RETURNS Varchar(2000)
As
Begin
Declare @.List Varchar(2000)
set @.List=''
Select @.List = @.List+RTrim(Qte) + ',' From Orders Where CustomerID =RTrim(@.ID)
Return(Left(@.List,Len(@.List)-1))
End|||then you can do
select name,dbo.ListOfQuantity(id)
from customer|||What is magical is the
Select @.List = @.List + Col1 From Tbl
For a result that should be
1
2
3
it returns
123|||I'll try it Karolyn, THANKS!|||Many thanks!
Cursor Help
'Cursorfetch: The number of variables declared in the INTO list must match
that of selected columns.' What am I a doing wrong. Below is my code.
Here's the code:
DECLARE @.Address_Line1 VARCHAR (100)
EXECUTE spGet_Statement_Rate '8', '2005'
--spGet_Statement_Rate looks like this:
--DECLARE RATE_CURSOR CURSOR GLOBAL FOR
--SELECT Address_Line1, Rate_ID FROM COMPANY
OPEN RATE_CURSOR
FETCH NEXT FROM RATE_CURSOR INTO @.Address_Line1
WHILE (@.@.FETCH_STATUS = 0) BEGIN
print @.Address_Line1--FROM RATE_CURSOR
FETCH NEXT FROM RATE_CURSOR INTO @.Address_Line1
END
--
CLOSE RATE_CURSOR
DEALLOCATE RATE_CURSORif u could post the ddl and sample data we could say whether u could do w/o
a cursor itself..
im not a fan of cursor based coding..
"Eric" <Eric@.discussions.microsoft.com> wrote in message
news:A75B44DC-DC6C-425D-B2BE-8B4F333F174C@.microsoft.com...
> Hi - Trying to work w/cursors but this is the error I receive:
> 'Cursorfetch: The number of variables declared in the INTO list must match
> that of selected columns.' What am I a doing wrong. Below is my code.
> Here's the code:
> DECLARE @.Address_Line1 VARCHAR (100)
> EXECUTE spGet_Statement_Rate '8', '2005'
> --spGet_Statement_Rate looks like this:
> --DECLARE RATE_CURSOR CURSOR GLOBAL FOR
> --SELECT Address_Line1, Rate_ID FROM COMPANY
> OPEN RATE_CURSOR
> FETCH NEXT FROM RATE_CURSOR INTO @.Address_Line1
> WHILE (@.@.FETCH_STATUS = 0) BEGIN
> print @.Address_Line1--FROM RATE_CURSOR
> FETCH NEXT FROM RATE_CURSOR INTO @.Address_Line1
> END
> --
> CLOSE RATE_CURSOR
> DEALLOCATE RATE_CURSOR
>|||> 'Cursorfetch: The number of variables declared in the INTO list must match
> that of selected columns.' What am I a doing wrong.
The message says it all. Your cursor select statement:
SELECT Address_Line1, Rate_ID FROM COMPANY
has 2 columns specified. However, your FETCH statements:
FETCH NEXT FROM RATE_CURSOR INTO @.Address_Line1
have only 1 column specified.
You can correct the issue either by omitting Rate_ID from the select list or
adding a variable for Rate_ID to your FETCH statements.
You might also revisit your code to see if you can accomplish the task
without a cursor. Set-based processing is often much more efficient than
cursor processing.
Hope this helps.
Dan Guzman
SQL Server MVP
"Eric" <Eric@.discussions.microsoft.com> wrote in message
news:A75B44DC-DC6C-425D-B2BE-8B4F333F174C@.microsoft.com...
> Hi - Trying to work w/cursors but this is the error I receive:
> 'Cursorfetch: The number of variables declared in the INTO list must match
> that of selected columns.' What am I a doing wrong. Below is my code.
> Here's the code:
> DECLARE @.Address_Line1 VARCHAR (100)
> EXECUTE spGet_Statement_Rate '8', '2005'
> --spGet_Statement_Rate looks like this:
> --DECLARE RATE_CURSOR CURSOR GLOBAL FOR
> --SELECT Address_Line1, Rate_ID FROM COMPANY
> OPEN RATE_CURSOR
> FETCH NEXT FROM RATE_CURSOR INTO @.Address_Line1
> WHILE (@.@.FETCH_STATUS = 0) BEGIN
> print @.Address_Line1--FROM RATE_CURSOR
> FETCH NEXT FROM RATE_CURSOR INTO @.Address_Line1
> END
> --
> CLOSE RATE_CURSOR
> DEALLOCATE RATE_CURSOR
>|||What do you mean by 'set based processing?' In a nutshell, I need to create
a result set of data. Then for each record returned, I need to execute a
bunch of stored procedures. I understand that cursors aren't the most
efficient, but this will run off hours and only once a month.
"Dan Guzman" wrote:
> The message says it all. Your cursor select statement:
> SELECT Address_Line1, Rate_ID FROM COMPANY
> has 2 columns specified. However, your FETCH statements:
> FETCH NEXT FROM RATE_CURSOR INTO @.Address_Line1
> have only 1 column specified.
> You can correct the issue either by omitting Rate_ID from the select list
or
> adding a variable for Rate_ID to your FETCH statements.
> You might also revisit your code to see if you can accomplish the task
> without a cursor. Set-based processing is often much more efficient than
> cursor processing.
>
> --
> Hope this helps.
> Dan Guzman
> SQL Server MVP
> "Eric" <Eric@.discussions.microsoft.com> wrote in message
> news:A75B44DC-DC6C-425D-B2BE-8B4F333F174C@.microsoft.com...
>
>|||> What do you mean by 'set based processing?'
Process the whole SET of rows at a time rather than one row at a time.
SQL Server is designed and optimized for set-based operations rather
than for cursor operations.
Aside from performance there are plenty of good reasons not to use
cursors. Set-based code is generally much more concise and easier to
develop, test, debug and maintain.
David Portas
SQL Server MVP
--|||> What do you mean by 'set based processing?' In a nutshell, I need to
> create
> a result set of data. Then for each record returned, I need to execute a
> bunch of stored procedures. I understand that cursors aren't the most
> efficient, but this will run off hours and only once a month.
You can't use set-based processing to execute procs for each row returned.
The point is that you can often use a set-based process instead of a looping
construct. Consider basic example:
DECLARE MyCursor CURSOR GLOBAL FOR
SELECT MyData FROM SomeTable
OPEN MyCursor
FETCH NEXT FROM MyCursor INTO @.MyData
WHILE (@.@.FETCH_STATUS = 0)
BEGIN
FETCH NEXT FROM MyCursor INTO @.MyData
INSERT INTO MyTable(MyData)
VALUES(@.MyData)
END
CLOSE MyCursor
DEALLOCATE MyCursor
The above can also be accomplished with the statement below and perform much
better:
INSERT INTO MyTable (MyData)
SELECT MyData FROM SomeTable
It's best to use inline SQL statements when possible. If you need to keep
code in different procs, you can pass data using temp table instead of a
cursor.
Hope this helps.
Dan Guzman
SQL Server MVP|||Okay, here's the cursor i was going to use (this would be in a stored
procedure):
DECLARE RATE_CURSOR CURSOR GLOBAL FOR
SELECT
S.Statement_ID,
S.Rate_ID,
C.Company_Name,
C.Address_Line1,
C.Address_Line2,
C.City,
C.State,
C.Zip,
C.Phone,
C.creditAllow,
R.Rate_Type,
R.Amount_Per_Transaction,
ISNULL (Amount_Per_Transaction_RCK, 0) AS Amount_Per_Transaction_RCK,
ISNULL (Amount_Per_Transaction_ARC, 0) AS Amount_Per_Transaction_ARC,
R.Percentage_Per_Transaction,
ISNULL (Percentage_Per_Transaction_RCK, 0) AS
Percentage_Per_Transaction_RCK,
ISNULL (Percentage_Per_Transaction_ARC, 0) AS
Percentage_Per_Transaction_ARC,
R.Monthly_Fee,
R.Monthly_minimum,
R.Rate_Per_Batch,
R.Discount_VPT,
R.Discount_Monthly_Fee,
R.Discount_RPB,
R.statement_fee,
R.service_fee,
R.ACHgateway_fee,
R.Reject_company_fee,
R.Reject_customer_fee,
R.ACHRefund_Fee,
R.ChargeBack_fee,
R.BadDE_fee,
R.NOC,
R.reserve_percentage,
R.GrossNet,
R.tranFeeCredit,
R.discountFeeCredit,
R.statementFeeCredit,
R.monthlyminCredit,
R.creditOutReturnFee,
RCK,
ARC,
C.RCKRebate,
C.CCDPPD_rebate_amount,
C.ARC_rebate_amount,
C.isRCK_rebate,
C.isARC_rebate,
C.isCCDPPD_rebate,
COMPANY_ID
FROM ST S, RT R, CO C
WHERE S.Rate_ID = R.Rate_ID and
S.Account_ID = C.Company_ID and
S.statement_Month = @.MONTH and
S.statement_Year = @.YEAR AND
C.ACCOUNT_STATUS = 1
Now, for earch record returned above, I will need to execute about 6 stored
procedures, passing in vaious parameters. I'm unfamilar as to how to loop
through a result set (as opposed to using a cursor) to achieve the same, so
if that's a better option, a code example would be appreciated.|||If you have to iterate through a result set for each row returned then
a cursor may well be the best way to do it. What you should generally
try to avoid is iteration in ANY form - other methods of doing so are
just a cursor in disguise. As you have a legacy proc designed to work
only with single rows you will have to decide whether it's worth a
re-write or if you can live with the cursor solution. The better
alternative in most cases is to avoid designing procs that impose any
single row limitations on your SQL code.
David Portas
SQL Server MVP
--|||To add on to David's response, I'd like to emphasize his point that the real
issue is your procs that operate on one record at a time. Ideally, you can
ditch both the cursor and the single-row procs and instead use set-based
processing. For example:
Instead of:
WHILE (@.@.FETCH_STATUS = 0)
BEGIN
FETCH NEXT FROM RATE_CURSOR INTO <variable list here>
EXEC MyInsertProc <variable list here>
END
Try:
INSERT INTO MyTable(<column list here> )
SELECT ...
I know that rewriting existing code can be painful and might not be worth
the effort in this case if your cursor performance is acceptable. However,
you should at least be familiar with set-based techniques so you can employ
them going forward as appropriate.
Hope this helps.
Dan Guzman
SQL Server MVP
"Eric" <Eric@.discussions.microsoft.com> wrote in message
news:D1E5E64E-3AA9-40C6-975D-C7A079AD20DF@.microsoft.com...
> Okay, here's the cursor i was going to use (this would be in a stored
> procedure):
> DECLARE RATE_CURSOR CURSOR GLOBAL FOR
> SELECT
> S.Statement_ID,
> S.Rate_ID,
> C.Company_Name,
> C.Address_Line1,
> C.Address_Line2,
> C.City,
> C.State,
> C.Zip,
> C.Phone,
> C.creditAllow,
> R.Rate_Type,
> R.Amount_Per_Transaction,
> ISNULL (Amount_Per_Transaction_RCK, 0) AS Amount_Per_Transaction_RCK,
> ISNULL (Amount_Per_Transaction_ARC, 0) AS Amount_Per_Transaction_ARC,
> R.Percentage_Per_Transaction,
> ISNULL (Percentage_Per_Transaction_RCK, 0) AS
> Percentage_Per_Transaction_RCK,
> ISNULL (Percentage_Per_Transaction_ARC, 0) AS
> Percentage_Per_Transaction_ARC,
> R.Monthly_Fee,
> R.Monthly_minimum,
> R.Rate_Per_Batch,
> R.Discount_VPT,
> R.Discount_Monthly_Fee,
> R.Discount_RPB,
> R.statement_fee,
> R.service_fee,
> R.ACHgateway_fee,
> R.Reject_company_fee,
> R.Reject_customer_fee,
> R.ACHRefund_Fee,
> R.ChargeBack_fee,
> R.BadDE_fee,
> R.NOC,
> R.reserve_percentage,
> R.GrossNet,
> R.tranFeeCredit,
> R.discountFeeCredit,
> R.statementFeeCredit,
> R.monthlyminCredit,
> R.creditOutReturnFee,
> RCK,
> ARC,
> C.RCKRebate,
> C.CCDPPD_rebate_amount,
> C.ARC_rebate_amount,
> C.isRCK_rebate,
> C.isARC_rebate,
> C.isCCDPPD_rebate,
> COMPANY_ID
> FROM ST S, RT R, CO C
> WHERE S.Rate_ID = R.Rate_ID and
> S.Account_ID = C.Company_ID and
> S.statement_Month = @.MONTH and
> S.statement_Year = @.YEAR AND
> C.ACCOUNT_STATUS = 1
> Now, for earch record returned above, I will need to execute about 6
> stored
> procedures, passing in vaious parameters. I'm unfamilar as to how to loop
> through a result set (as opposed to using a cursor) to achieve the same,
> so
> if that's a better option, a code example would be appreciated.
Thursday, March 22, 2012
Cursor
i am relatively new to cursors and have created a SP that uses a cursor to populate a table. here is the code
CREATE PROCEDURE sppa_invvoid
(
@.invno int
)
AS
DECLARE @.glTranKey int
DECLARE @.AcctRefKey int
DECLARE @.BatchKey int
DECLARE @.CreateDate datetime
DECLARE @.CreateType smallint
DECLARE @.CurrExchRate float
DECLARE @.CurrID varchar (3)
DECLARE @.ExtCmnt varchar (255)
DECLARE @.FiscPer smallint
DECLARE @.FiscYear varchar (5)
DECLARE @.GLAcctKey int
DECLARE @.JrnlKey int
DECLARE @.JrnlNo int
DECLARE @.PostAmt decimal(15, 3)
DECLARE @.PostAmtHC decimal(15, 3)
DECLARE @.PostCmnt varchar (50)
DECLARE @.PostDate datetime
DECLARE @.PostQty decimal(16, 8)
DECLARE @.SourceModuleNo smallint
DECLARE @.TranDate datetime
DECLARE @.TranKey int
DECLARE @.TranNo varchar (10)
DECLARE @.TranType int
DECLARE @.Companyid varchar(3)
DECLARE @.Batchtype int
DECLARE @.Userid varchar (30)
DECLARE @.Moduleno int
DECLARE @.NextBatchNo int
DECLARE @._oRetVal int
DECLARE @.iTableName varchar(50)
DECLARE @.iCommitFlag int
DECLARE @.NextJrnlNo int
Set @.CompanyID= 'EMA'
Set @.JrnlNo = 139
Set @.iCommitFlag = 1
Set @.JrnlKey = 193
Set @.iTableName='tgltransaction'
Set @.batchtype = 501
Set @.moduleNo = 5
Set @.Userid = 'Admin'
EXECUTE spGetNextBatchNo @.CompanyID, @.BatchType, @.UserId, @.ModuleNo, @.BatchKey OUTPUT, @.NextBatchNo OUTPUT, @._oRetVal OUTPUT
Execute spglGiveNextJrnlNo @.CompanyID, @.JrnlKey, @.iCommitFlag, @.JrnlNo, @.NextJrnlNo OUTPUT
DECLARE cursor_tran CURSOR FOR
select glTranKey, AcctRefKey,CreateDate,CreateType,CurrExchRate,Curr ID,ExtCmnt,FiscPer,FiscYear,GLAcctKey,JrnlKey,Jrnl No,PostAmt,PostAmtHC,PostCmnt,PostDate,PostQty,Sou rceModuleNo,TranDate,TranKey,TranNo,TranType
from tgltransaction where tranno = @.invno
OPEN cursor_tran
FETCH NEXT FROM cursor_tran INTO
@.glTranKey,
@.AcctRefKey,
@.CreateDate,
@.CreateType,
@.CurrExchRate,
@.CurrID,
@.ExtCmnt,
@.FiscPer,
@.FiscYear,
@.GLAcctKey,
@.JrnlKey,
@.JrnlNo,
@.PostAmt,
@.PostAmtHC,
@.PostCmnt,
@.PostDate,
@.PostQty,
@.SourceModuleNo,
@.TranDate,
@.TranKey,
@.TranNo,
@.TranType
WHILE (@.@.FETCH_STATUS <> -1)
BEGIN
Execute spgetnextSurrogateKey @.iTablename , @.glTranKey OUTPUT
/*Execute aaaa*/
INSERT INTO tgltransaction
(glTranKey,
AcctRefKey,
BatchKey,
CreateDate,
CreateType,
CurrExchRate,
CurrID,
ExtCmnt,
FiscPer,
FiscYear,
GLAcctKey,
JrnlKey,
JrnlNo,
PostAmt,
PostAmtHC,
PostCmnt,
PostDate,
PostQty,
SourceModuleNo,
TranDate,
TranKey,
TranNo,
TranType)
Values
(@.glTrankey,
@.AcctRefKey,
@.BatchKey,
@.CreateDate,
@.CreateType,
@.CurrExchRate,
@.CurrID,
@.ExtCmnt,
@.FiscPer,
@.FiscYear,
@.GLAcctKey,
@.JrnlKey,
@.JrnlNo,
@.PostAmt,
@.PostAmtHC,
@.PostCmnt,
@.PostDate,
@.PostQty,
@.SourceModuleNo,
@.TranDate,
@.TranKey,
@.TranNo,
@.TranType)
FETCH NEXT FROM cursor_tran INTO
@.glTranKey,
@.AcctRefKey,
@.CreateDate,
@.CreateType,
@.CurrExchRate,
@.CurrID,
@.ExtCmnt,
@.FiscPer,
@.FiscYear,
@.GLAcctKey,
@.JrnlKey,
@.JrnlNo,
@.PostAmt,
@.PostAmtHC,
@.PostCmnt,
@.PostDate,
@.PostQty,
@.SourceModuleNo,
@.TranDate,
@.TranKey,
@.TranNo,
@.TranType
END
CLOSE cursor_tran
DEALLOCATE cursor_tran
GO
the issue that i am having is after i do the insert, the cursor picks up on the inserted row and it ultimately becomes an infinate loop. what can i do to prevent it from picking up the newly inserted rows. thanks alot
tibornevermind, just saw my problem. of course it will loop if youre using the same table for insert and cursor, lol.|||Glad to see you've figured out how to use cursors. Now do yourself a favor and forget about them, and use set-based processing instead.
Your spglGiveNextJrnlNo procedure should be converted to a user-defined function, (or better yet, dumped altogether), and then you can write your code as a much shorter and much more efficient INSERT statement.|||Hey, a wiseman once said:
Cursors are useful if you don't know sql.
DTS can be used in a similar way.
Beer is not cold and it isn't fizzy.
http://www.sqlteam.com/forums/pop_profile.asp?mode=display&id=1578