Thursday, March 29, 2012
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 problem
When I run this cursor I get the value 01042005 inserting into my table
twice when the cursor gets to the end of the recordset. How can i store just
one instance of this value? I thought coding WHILE @.@.FETCH_STATUS = 0 would
stop it from looping again when it got to the end of the recordset.
DECLARE @.name varchar(19)
DECLARE trans_names CURSOR FOR
select name from sysobjects where name like '%TRANS%' and
substring(name,12,6)= '042005'
order by convert(int,substring(name,14,4)) desc,substring(name,12,2)
desc,substring(name,10,2) desc
OPEN trans_names
FETCH NEXT FROM trans_names INTO @.name
INSERT #TABLES VALUES (blah blah)
WHILE @.@.FETCH_STATUS = 0
BEGIN
FETCH NEXT FROM trans_names INTO @.name
INSERT #TABLES VALUES (blah blah)
END
CLOSE trans_names
DEALLOCATE trans_names
GOWhy don't you use:
INSERT INTO #TABLES (<column list> )
select name from sysobjects where name like '%TRANS%' and
substring(name,12,6)= '042005'
But anyway, if you really need a cursor, I find writing the loop in the
following way the most convenient:
DECLARE <cursor name> CURSOR FAST_FORWARD FOR <select statement>
OPEN <cursor name>
WHILE 1 = 1
BEGIN
FETCH NEXT FROM <cursor name> INTO <variables>
IF @.@.FETCHSTATUS <> 0 BREAK -- ends loop
-- do stuff
END
Jacco Schalkwijk
SQL Server MVP
"Steve" <Steve@.discussions.microsoft.com> wrote in message
news:65D7FB7A-860C-4CDF-8419-4FC8ED96F93A@.microsoft.com...
> Hello
> When I run this cursor I get the value 01042005 inserting into my table
> twice when the cursor gets to the end of the recordset. How can i store
> just
> one instance of this value? I thought coding WHILE @.@.FETCH_STATUS = 0
> would
> stop it from looping again when it got to the end of the recordset.
> DECLARE @.name varchar(19)
> DECLARE trans_names CURSOR FOR
> select name from sysobjects where name like '%TRANS%' and
> substring(name,12,6)= '042005'
> order by convert(int,substring(name,14,4)) desc,substring(name,12,2)
> desc,substring(name,10,2) desc
>
> OPEN trans_names
> FETCH NEXT FROM trans_names INTO @.name
> INSERT #TABLES VALUES (blah blah)
> WHILE @.@.FETCH_STATUS = 0
> BEGIN
> FETCH NEXT FROM trans_names INTO @.name
> INSERT #TABLES VALUES (blah blah)
> END
> CLOSE trans_names
> DEALLOCATE trans_names
> GO|||I think the problem is that the insert executes after the fetch next, but
before the @.@.Fetch_status is evaluated. Try this as an alternative
FETCH NEXT FROM trans_names INTO @.name
WHILE @.@.FETCH_STATUS = 0
BEGIN
INSERT #TABLES VALUES (blah blah)
FETCH NEXT FROM trans_names INTO @.name
END
Gail Shaw (MCSD)
http://gail.rucus.net/
"Steve" wrote:
> Hello
> When I run this cursor I get the value 01042005 inserting into my table
> twice when the cursor gets to the end of the recordset. How can i store ju
st
> one instance of this value? I thought coding WHILE @.@.FETCH_STATUS = 0 woul
d
> stop it from looping again when it got to the end of the recordset.
> DECLARE @.name varchar(19)
> DECLARE trans_names CURSOR FOR
> select name from sysobjects where name like '%TRANS%' and
> substring(name,12,6)= '042005'
> order by convert(int,substring(name,14,4)) desc,substring(name,12,2)
> desc,substring(name,10,2) desc
>
> OPEN trans_names
> FETCH NEXT FROM trans_names INTO @.name
> INSERT #TABLES VALUES (blah blah)
> WHILE @.@.FETCH_STATUS = 0
> BEGIN
> FETCH NEXT FROM trans_names INTO @.name
> INSERT #TABLES VALUES (blah blah)
> END
> CLOSE trans_names
> DEALLOCATE trans_names
> GO|||Thanku very much. It's working now.
"GilaMonster" wrote:
> I think the problem is that the insert executes after the fetch next, but
> before the @.@.Fetch_status is evaluated. Try this as an alternative
> FETCH NEXT FROM trans_names INTO @.name
> WHILE @.@.FETCH_STATUS = 0
> BEGIN
> INSERT #TABLES VALUES (blah blah)
> FETCH NEXT FROM trans_names INTO @.name
> END
>
> --
> Gail Shaw (MCSD)
> http://gail.rucus.net/
>
> "Steve" wrote:
>
Tuesday, March 27, 2012
Cursor out of time
First of all sorry about poor english.
I have the next problem:
I have a store procedure which declares a cursor which is a select from some tables. Im surprised because the sp takes over 10 seconds on working and if i execute the select of the cursor as separate ways, it takes no more one second. Ive changed the select with another easier select and it works 0 seconds, so it seems that the problem is in the select, but only if i use a cursor to save the regs, why????
Thanks a lot.Use the "show execution plan" option to see how the server is executing the three queries. Check to see what it different between them. My guess is that there is something causing the optimizer to make a radically different choice for one or more of the queries, and that is what is making them take longer.
-PatP|||Just don't use cursors. :) What are you trying to do with the cursor?|||Thank you for answer.
I think that I meant wrong.
If I execute the select in the cursor it takes me over ten seconds but if I copy the select and paste in the query analyzer, it takes me 0 seconds. Besides this, if i change the select by other easier one, the cursor takes 0 seconds. I know the first select could be wrong but it works 0 seconds in the analyzer!!!! and inside the cursor there is not any operations.
Thanks a lot...
Cursor or Table For Stored Procedure ?
I have the following probleman :
I have a stored procedure that retrieve results of a select statement,
and i would like to store this results in a cursor or temporary table
or something like that.
Could u help me ? Tks...
Code that i tried :
create procedure ListOfProducts
@.categoryID int
as begin
select * from Product
end
declare c int
declare c cursor for ListOfProducts 1
open c
fetch next from c into @.idProduct
print @.idProduct
close c
deallocate cHi,
If you want to store a stored procedure result into a temporary table, use
INSERT/EXEC statement. Create a temporary table first using CREATE TABLE.
Tomasz B.
"Carlao" wrote:
> Hello,
> I have the following probleman :
> I have a stored procedure that retrieve results of a select statement,
> and i would like to store this results in a cursor or temporary table
> or something like that.
> Could u help me ? Tks...
> Code that i tried :
> create procedure ListOfProducts
> @.categoryID int
> as begin
> select * from Product
> end
> declare c int
> declare c cursor for ListOfProducts 1
> open c
> fetch next from c into @.idProduct
> print @.idProduct
> close c
> deallocate c
>|||If you want the instances of sql server, then you can use SQL-DMO API,
specifically the ListAvailableSQLServers Method of the Application object.
http://www.microsoft.com/resources/... />
c3561.mspx
AMB
"Carlao" wrote:
> Hello,
> I have the following probleman :
> I have a stored procedure that retrieve results of a select statement,
> and i would like to store this results in a cursor or temporary table
> or something like that.
> Could u help me ? Tks...
> Code that i tried :
> create procedure ListOfProducts
> @.categoryID int
> as begin
> select * from Product
> end
> declare c int
> declare c cursor for ListOfProducts 1
> open c
> fetch next from c into @.idProduct
> print @.idProduct
> close c
> deallocate c
>|||Sorry, wrong place.
AMB
"Alejandro Mesa" wrote:
> If you want the instances of sql server, then you can use SQL-DMO API,
> specifically the ListAvailableSQLServers Method of the Application object.
> http://www.microsoft.com/resources/...>
0/c3561.mspx
>
> AMB
> "Carlao" wrote:
>|||You can create a temporary table (local or global) or a permanent one to gra
b
the result of the sp. You can also return a cursor variable from your sp.
Example:
use northwind
go
create procedure proc1
@.sd datetime,
@.ed datetime
as
set nocount on
declare @.rv int
set @.rv = 1
execute @.rv = dbo.[Sales by Year] @.sd, @.ed
return coalesce(nullif(@.rv, 0), @.@.error)
go
create procedure proc2
@.sd datetime,
@.ed datetime
as
set nocount on
create table #t (
ShippedDate datetime,
OrderID int,
Subtotal money,
col_year int
)
insert into #t
exec proc1 @.sd, @.ed
select * from #t
where Subtotal between 2000.00 and 3000.00
order by ShippedDate
drop table #t
return
go
execute proc2 '19960101', '19981231'
go
drop procedure proc2, proc1
go
AMB
"Carlao" wrote:
> Hello,
> I have the following probleman :
> I have a stored procedure that retrieve results of a select statement,
> and i would like to store this results in a cursor or temporary table
> or something like that.
> Could u help me ? Tks...
> Code that i tried :
> create procedure ListOfProducts
> @.categoryID int
> as begin
> select * from Product
> end
> declare c int
> declare c cursor for ListOfProducts 1
> open c
> fetch next from c into @.idProduct
> print @.idProduct
> close c
> deallocate c
>
Cursor Issue - Order not correct
I am finding that this works for about 95% of the stores, but about 5% are getting fouled up, where the store's records are getting split in the sequencing, and so the store ends up with two zips ranked 1, two ranked 2, two ranked 3, etc.
In the DB structure, there is a constraint restricting one record per store (org_id) per zip code (postalcode).
Here's my code. Basically what I'm trying to have the cursor do is go through the table, ordered by org_id (store) asc, org_criteria_value (sales) desc, and rank the zip codes. When a new store is encountered, reset the counter to 1 and start ranking again. Do this until all the records are processed.
/*CREATE Sales_Table table */
CREATE TABLE [dbo].[Sales_Table] (
[count_id] [int] NULL ,
[org_id] [int] NULL ,
[postalcode] [varchar] (20) NULL,
[sales] [numeric](18,6) NULL ,
[sales_rank] [integer] NULL,
[org_criteria_input_date] [datetime] NULL
) ON [PRIMARY]
insert into Sales_Table
select 0 as count_id, omd.org_id, omd.postalcode, omd.org_criteria_value, 0 as cum_rank, org_criteria_input_date
from org_model_data omd
join org o on o.org_id = omd.org_id
where o.client_id = @.ClientID
and model_Criteria_id = 27
and org_criteria_value <> 0
order by omd.org_id asc, omd.org_criteria_value desc
-- DECLARE CURSOR for Sales_Table
declare SalesRankCursor CURSOR
SCROLL dynamic FOR
select org_id, sales, sales_rank
from Sales_Table
for update of sales_rank
-- CREATE LOOP TO UPDATE SALES RANK in Sales_Table with valid values
OPEN SalesRankCursor
while exists (Select * from Sales_Table where sales_rank = 0)
Begin
FETCH NEXT FROM SalesRankCursor
set @.StoreNext = @.StoreCurrent
set @.SalesRank = (@.SalesRank + 1)
update Sales_Table
set @.StoreCurrent = org_id
where current of SalesRankCursor
if @.StoreCurrent <> @.StoreNext
begin
set @.SalesRank = 1
end
update Sales_Table
set sales_rank = @.SalesRank
where current of SalesRankCursor
End
CLOSE SalesRankCursor
DEALLOCATE SalesRankCursor
Any ideas?You insert the data ordered, but since the order of the rows are irrelevant to SQL Server, you are not guaranteed to get the rows out in the same order. So, what you basically need is to have the order by in the cursor definition.|||That's what I thought, but how do you order within the cursor definition. When I try an 'order by' statement within the cursor definition, I get a message saying it can only be used in an 'read only' cursor, and my cursor needs to allow an update.|||What I've done for a solution is put a Clustered Index on my source table 'Test Table' on the fields org_id, and org_criteria_value. This appears to have resolved the issue.
I would have preferred to have solved the problem within the cursor, however, so if anyone has a suggestion I would appreciate it.
Thanks.|||What I've done for a solution is put a Clustered Index on my source table 'Test Table' on the fields org_id, and org_criteria_value. This appears to have resolved the issue.
You should be aware that just because it has a clustered index on it, you are not GUARANTEED that the results will be returned in the expected order.
I would have preferred to have solved the problem within the cursor, however, so if anyone has a suggestion I would appreciate it.
Thanks.
Maybe I missed something in the code, but how about something like:
DECLARE SalesRank CURSOR
READ_ONLY
FOR SELECT Store_ID
FROM Stores
ORDER BY Sales DESC
DECLARE @.Store_ID int, @.Counter int
SELECT @.Counter = 1
FETCH NEXT FROM SalesRank INTO @.Store_ID
WHILE (@.@.fetch_status <> -1)
BEGIN
IF (@.@.fetch_status <> -2)
BEGIN
UPDATE Stores
SET SalesRank = @.Counter
WHERE Store_ID = @.Store_ID
END
SELECT @.Counter = @.Counter + 1
FETCH NEXT FROM SalesRank INTO @.Store_ID
END
CLOSE SalesRank
DEALLOCATE SalesRank
This would not handle ties or other things, but it should work (with some modification).
Also, there is a RANK function in SQL 2005. That might be an option for you.
Regards,
hmscott|||HMScott,
Let me take a shot at that. I may have to play around with it because I can't have a tie... I'll have to figure out a tie breaker and work from there.
The Clustered IX appeared to solve my problem, but it wasn't the solution I wanted because of lack of certainty. Hopefully the approach you're recommending will work.
Thanks.
Thursday, March 22, 2012
Cursed with trailing whitespace or trailing 0's
I have a databound textbox that is used to store a decimal value.
If my sql table stores this column as a decimal(2,2), then all of the numbers entered into the field will automatically put decimal places in that I don't want. For example, 45 becomes 45.00... 34.5 becomes 34.50.
If I set the sql table to nchar(10) and the dataset to system.string (max length of -1), then the number looks the way I would like it, however after a datatable update I end up with trailing whitespace after the number - filling up the rest of the unused 10 characters. For example, "45" becomes "45 " (8 spaces afterwards).
Does anybody know how I can fix this? I would prefer to store the numbers in SQL as a string (nchar(10))... but I don't know how to get rid of that darned whitespace. I would like to remove it at the database level and not at the client level if at all possible.
Thanks!
Using char means that you want to have fixed length attributes. using Varchar would use only the space that is needed for storing the attribute. You have to keep in mind that the insert behaviour is determined by your inserting application. if the application do insert "45 " then you have to manuipulate the application ratehr than the database. But normally you should only switch to a variable character length field, e.g. in this case VARCHAR(10).HTH, Jens Suessmeyer.http://www.sqlserver2005.de