Showing posts with label cursor. Show all posts
Showing posts with label cursor. Show all posts

Friday, February 17, 2012

cursors problem

hi i am getting that message to update field value into table
Msg 16933, Level 16, State 1, Procedure RmDupValWSWCode, Line 39
The cursor does not include the table being modified or the table is not
updatable through the cursor.
I have two databases with same tables, in one database it work on that table
but in another database its not working on the same table with the same
data......
why cursor behave like thatHello!
Could you post your code?
Thanks!|||Since you haven't posted the code. I am guessing :)
are you using the two part name where ever you refer to the table.
I mean refer to all the table names as
dbo.table1
or whichever schema you are using.
Hope this helps.|||Also, make sure the user running the stored procedure has access to the
tables.
"Omnibuzz" <Omnibuzz@.discussions.microsoft.com> wrote in message
news:2919D9C0-492D-4582-89B0-BEDABA2B0E6E@.microsoft.com...
> Since you haven't posted the code. I am guessing :)
> are you using the two part name where ever you refer to the table.
> I mean refer to all the table names as
> dbo.table1
> or whichever schema you are using.
> Hope this helps.|||Hey Jim..
long time no clashes.. was missing you :)
"Jim Underwood" wrote:

> Also, make sure the user running the stored procedure has access to the
> tables.
> "Omnibuzz" <Omnibuzz@.discussions.microsoft.com> wrote in message
> news:2919D9C0-492D-4582-89B0-BEDABA2B0E6E@.microsoft.com...
>
>|||Lol. Yeah, you missed an entire day last w. All day long I was looking
for some posts from you. You usually have a few creative and thought
provoking solutions. I think today's is the negative flag * 2 +1 to get
either a positive or negative number. I had to get some caffeine before I
could figure it out.
Actually, I was hoping to see if you had a mathematical formula to solve the
matrix (Matriz) problem posted yesterday. The best I could come up with was
a mapping table. I couldn't seem to find a mathematical approach to the
problem, so I went with simple brute force.
"Omnibuzz" <Omnibuzz@.discussions.microsoft.com> wrote in message
news:6FEE9DDC-CEBC-46B8-8AE1-17E1CCEE47A1@.microsoft.com...
> Hey Jim..
> long time no clashes.. was missing you :)
> "Jim Underwood" wrote:
>|||Gee...Thanks for the complments..
Well network was down yesterday.. and didn't see the post on matrix.. will
look into it now :)
"Jim Underwood" wrote:

> Lol. Yeah, you missed an entire day last w. All day long I was lookin
g
> for some posts from you. You usually have a few creative and thought
> provoking solutions. I think today's is the negative flag * 2 +1 to get
> either a positive or negative number. I had to get some caffeine before I
> could figure it out.
> Actually, I was hoping to see if you had a mathematical formula to solve t
he
> matrix (Matriz) problem posted yesterday. The best I could come up with w
as
> a mapping table. I couldn't seem to find a mathematical approach to the
> problem, so I went with simple brute force.
> "Omnibuzz" <Omnibuzz@.discussions.microsoft.com> wrote in message
> news:6FEE9DDC-CEBC-46B8-8AE1-17E1CCEE47A1@.microsoft.com...
>
>

Cursors only fetching about 200 records?

I have a cursor that is supposed to fetch all the records from a temporary
table, #temp, one at a time, do some manipulation on the data, insert the
results into another temporary table, #detailedTransRpt, then delete the
record from #temp. All of the records from #temp should be deleted before
@.@.fetch_status = -1; however, it seems that @.@.fetch_status = -1 always aroun
d
the time 200 records have been fetched, thereby leaving some data in #temp.
I have tried different data sets, and have compared the records on which the
fetch fails, but these records have nothing in common and I can't seem to
figure out why the fetch is failing. It seems to have more to do with the
number of records, than anything else. Has anyone come across a similar
problem? Any advice?Keith wrote:
> I have a cursor that is supposed to fetch all the records from a temporary
> table, #temp, one at a time, do some manipulation on the data, insert the
> results into another temporary table, #detailedTransRpt, then delete the
> record from #temp. All of the records from #temp should be deleted before
> @.@.fetch_status = -1; however, it seems that @.@.fetch_status = -1 always aro
und
> the time 200 records have been fetched, thereby leaving some data in #temp
.
> I have tried different data sets, and have compared the records on which t
he
> fetch fails, but these records have nothing in common and I can't seem to
> figure out why the fetch is failing. It seems to have more to do with the
> number of records, than anything else. Has anyone come across a similar
> problem? Any advice?
Without seeing the code it's anyone's guess. Based on your description
it's probably unlikely that you'll need a cursor at all. There are
usually better solutions so I suggest you post DDL, some sample data
and show what result you want if you need some help.
David Portas, SQL Server MVP
Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.
SQL Server Books Online:
http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
--|||Why are you deleting the rows within your cursor? I think you can loop
through all the rows and delete them only when you are done with the entire
set of data. I don't know if this has any effect on the cursor or not, but
it sounds a little odd and might be worth checking. Basically, I am
wondering if updating the temp table that you are reading from might cause
strange behavior, although I would expect an error rather than lost rows if
this were the case.
"Keith" <Keith@.discussions.microsoft.com> wrote in message
news:44450145-CBC9-4AC0-B08C-DAF3F992C4B9@.microsoft.com...
> I have a cursor that is supposed to fetch all the records from a temporary
> table, #temp, one at a time, do some manipulation on the data, insert the
> results into another temporary table, #detailedTransRpt, then delete the
> record from #temp. All of the records from #temp should be deleted before
> @.@.fetch_status = -1; however, it seems that @.@.fetch_status = -1 always
around
> the time 200 records have been fetched, thereby leaving some data in
#temp.
> I have tried different data sets, and have compared the records on which
the
> fetch fails, but these records have nothing in common and I can't seem to
> figure out why the fetch is failing. It seems to have more to do with the
> number of records, than anything else. Has anyone come across a similar
> problem? Any advice?|||by any chance, is rowcount set to 200?|||I'm posting all the variable declarations, and what I set the stored
procedure parameters to, for debugging purposes, as well as the two table
CREATE statements, and the single cursor that I know is failing. There is
too much code in the entire SP for me to paste here. A function splits the
string from @.strbankAccID into bank account IDs, and then the transactions
from a given bank account ID are put into #temp. The transactions from #tem
p
are manipulated then put into #detailedTransRpt, and then deleted from #temp
.
However, the cursor @.@.fetch_status = -1 before all the transactions are
removed from #temp, and the transactions end up being mixed up between the
bank accounts on the report that this produces. Why was it done this way,
you may ask? Because some other developer (who is long gone) did it this wa
y
and I am now responsible for fixing the report. Can you feel the
frustration? :) Thanks!
DECLARE @.Lodge_ID VARCHAR(9)
DECLARE @.begin VARCHAR(25)
DECLARE @.end VARCHAR(25)
DECLARE @.strbankAccID VARCHAR (8000)
DECLARE @.transTypeCD CHAR(3)
DECLARE @.transVersion CHAR(3)
DECLARE @.accountChosen VARCHAR(3)
DECLARE @.totalRecord INT
SET @.LODGE_ID = 'D60'
set @.begin = '12/21/2005'
set @.end = '12/31/2005'
set @.strbankAccID = '583,1373,1374,1380,1381,1384,1385,1397'
--D60
set @.transTypeCD = 'All'
set @.transVersion = 'All'
set @.accountChosen = 'All'
SET NOCOUNT ON
DECLARE @.beginDate DATETIME
DECLARE @.endDate DATETIME
DECLARE @.acctIDstring VARCHAR(1000)
DECLARE @.pos INT
DECLARE @.str1 VARCHAR (8)
DECLARE @.length INT
DECLARE @.strTransNum VARCHAR(50)
DECLARE @.transID INT
DECLARE @.bankAcctID BIGINT
DECLARE @.acctNameLabel VARCHAR(50)
DECLARE @.transTypeLabel VARCHAR(50)
DECLARE @.transVersionLabel VARCHAR(100)
DECLARE @.bankType AS CHAR(1)
DECLARE @.charBankType AS CHAR(1)
DECLARE @.flag BIT
DECLARE @.DepositTransID INT
DECLARE @.charDepositStatusCD CHAR(2)
DECLARE @.bankID INT
CREATE TABLE #temp (
tempDepTransID INT,
DepositID INT,
TransNumber VARCHAR(50),
TransAmt MONEY,
SplitInd CHAR(1) ,
CategoryID INT,
SubCategoryID INT,
TransStatusCD CHAR(1),
TransVersionCD CHAR(2),
PaymentType CHAR(2),
TransDate DATETIME,
TransType CHAR(2),
TransDesc VARCHAR(150),
class_cd varchar(50)
)
CREATE TABLE #detailedTransRpt (
BankAcctID BIGINT,
depTransID INT,
Header VARCHAR(255),
AcctNum VARCHAR(30),
BankName VARCHAR(50),
AcctType VARCHAR(50),
Status VARCHAR(20),
TransDate DATETIME,
Number VARCHAR (255),-- receipt # ... trans number in a string with ','
TransDesc VARCHAR(150),-- receipt number ...trans number in a string with
','
PaymentType VARCHAR(20),-- deposit for section 3
Receipt MONEY,
Reconciled VARCHAR(20),
Disbursement MONEY,
TransVersion VARCHAR(100),
Category VARCHAR (50),
SubCategory VARCHAR (50),
class_cd varchar(50)
)
declare @.classCd varchar(50)
declare @.depTransID INT
declare @.tempDepTransID INT
DECLARE @.bankName AS VARCHAR (50)
DECLARE @.acctNo AS VARCHAR(30)
DECLARE @.acctName AS VARCHAR(50)
DECLARE @.charStatus AS CHAR(1)
DECLARE @.strStatus AS VARCHAR(20)
DECLARE @.charAcctType AS CHAR(1)
DECLARE @.strAcctType AS VARCHAR(50)
DECLARE @.header AS VARCHAR(255)
DECLARE @.TempTransID INT
DECLARE @.depositID INT
DECLARE @.transactionNumber VARCHAR(50)
DECLARE @.transactionDesc VARCHAR(150)
DECLARE @.numberofreceipt INT
DECLARE @.transNum VARCHAR(50)
DECLARE @.transAmt MONEY
DECLARE @.transTotal MONEY
DECLARE @.Category INT
DECLARE @.subCategory INT
DECLARE @.categoryDesc VARCHAR(100)
DECLARE @.subCategoryDesc VARCHAR(100)
DECLARE @.SplitInd CHAR(1)
DECLARE @.charTransStatusCD CHAR(1)
DECLARE @.charTransVersionCD CHAR(1)
DECLARE @.charPaymentTypeCD CHAR(2)
DECLARE @.strPaymentType VARCHAR(20)
DECLARE @.strTransStatus VARCHAR(20)
DECLARE @.strTransVersion VARCHAR(100)
DECLARE @.transDate DATETIME
DECLARE @.TransType CHAR(2)
DECLARE @.TransDesc VARCHAR(150)
DECLARE @.DepositMemo VARCHAR(50)
DECLARE @.DepositNumber VARCHAR(20)
DECLARE @.intDeposit INT
SET @.transactionNumber = ''
DECLARE curTransNum CURSOR FOR
SELECT * FROM #temp WHERE (DepositID IS NULL) AND TransType <> 'TR'
OPEN curTransNum
FETCH NEXT FROM curTransNum INTO
@.depTransID,@.DepositID,@.transNum,@.transA
mt,@.splitInd,@.Category,
@.subCategory,@.charTransStatusCD,@.charTra
nsVersionCD,@.charPaymentTypeCD,
@.transDate,@.TransType,@.TransDesc,@.classC
D
WHILE @.@.FETCH_STATUS = 0
BEGIN
SET @.categoryDesc = NULL
SET @.subCategoryDesc = NULL
set @.classCDdesc = null
IF @.splitInd ='Y'
BEGIN
SET @.categoryDesc = 'SPLIT'
SET @.subCategoryDesc = 'SPLIT'
set @.classCDdesc = 'SPLIT'
END
ELSE
BEGIN
SELECT @.categoryDesc = Category_Description FROM Category WHERE
Category_ID = @.Category
SELECT @.subCategoryDesc = Sub_Category_description FROM Sub_Category
WHERE Sub_Category_id = @.subCategory
IF @.TransType = 'RT'
select @.classCDdesc = description from lookup where Category LIKE
'CLASS_SCHEDULE_CAT_CD' AND Code LIKE @.classCD
else
select @.classCDdesc = description from lookup where Category LIKE
'CLASS_FUNCTIONAL_CAT_CD' AND Code LIKE @.classCD
END
SELECT @.strPaymentType = [Description]
FROM Lookup
WHERE Category LIKE 'PAYMENT_TYPE_CD' AND Code LIKE @.charPaymentTypeCD
IF @.charTransStatusCD = 'U'
SET @.strTransStatus = ''
ELSE
SET @.strTransStatus = @.charTransStatusCD
IF @.charTransVersionCD = '0'
SET @.strTransVersion = ''
ELSE IF @.charTransVersionCD = '1'
SET @.strTransVersion = 'Edited'
ELSE IF @.charTransVersionCD = '2'
SET @.strTransVersion = 'Adjusted'
ELSE IF @.charTransVersionCD = '3' OR @.charTransVersionCD = '5'
SET @.strTransVersion = 'Voided'
ELSE IF @.charTransVersionCD = '4' OR @.charTransVersionCD = '6'
SET @.strTransVersion = 'Unvoided'
IF @.TransType = 'RT'--undeposited receipts
BEGIN
INSERT INTO #detailedTransRpt
(bankAcctID,depTransID,Header,AcctNum,Ba
nkName,
AcctType,Status,TransDate,Number,
TransDesc,PaymentType,Receipt,Reconciled
,Disbursement,TransVersion,Category,
SubCategory,class_cd)
VALUES
(@.bankAcctID,@.depTransID,@.header,@.acctNo
,@.bankName,@.strAcctType,@.strStatus,@.
transDate,'Receipt #'+@.transNum,
@.TransDesc,@.strPaymentType,--CAST(@.transAmt AS VARCHAR),
@.transAmt,@.strTransStatus,NULL,@.strTrans
Version,@.categoryDesc,@.subCategoryDe
sc,@.classCDdesc)
--DELETE #temp WHERE @.TransType = 'RT'
DELETE #temp WHERE tempDepTransID = @.depTransID
END
ELSE --this is disbursement
BEGIN
IF @.charPaymentTypeCD = 'EF'
SET @.transactionNumber = 'EFT#' + @.transNum
ELSE IF @.charPaymentTypeCD = 'CH'
SET @.transactionNumber = 'Chk#' + @.transNum -- 7/18/2005
INSERT INTO #detailedTransRpt
(bankAcctID,depTransID,Header,AcctNum,Ba
nkName,
AcctType,Status,TransDate,Number,
TransDesc,PaymentType,Receipt,Reconciled
,Disbursement,TransVersion,Category,
SubCategory,class_cd)
VALUES
(@.bankAcctID,@.depTransID,@.header,@.acctNo
,@.bankName,@.strAcctType,@.strStatus,@.
transDate,@.transactionNumber,
@.TransDesc,@.strPaymentType,NULL,@.strTran
sStatus,@.transAmt,
@.strTransVersion,@.categoryDesc,@.subCateg
oryDesc,@.classCDdesc)
DELETE #temp WHERE tempDepTransID = @.depTransID --@.TransType = 'DI'
END
FETCH NEXT FROM curTransNum INTO
@.depTransID,@.DepositID,@.transNum,@.transA
mt,@.splitInd,@.Category,
@.subCategory,@.charTransStatusCD,@.charTra
nsVersionCD,@.charPaymentTypeCD,
@.transDate,@.TransType, @.TransDesc,@.classCD
END
CLOSE curTransNum
DEALLOCATE curTransNum
"David Portas" wrote:

> Keith wrote:
> Without seeing the code it's anyone's guess. Based on your description
> it's probably unlikely that you'll need a cursor at all. There are
> usually better solutions so I suggest you post DDL, some sample data
> and show what result you want if you need some help.
> --
> David Portas, SQL Server MVP
> Whenever possible please post enough code to reproduce your problem.
> Including CREATE TABLE and INSERT statements usually helps.
> State what version of SQL Server you are using and specify the content
> of any error messages.
> SQL Server Books Online:
> http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
> --
>|||I'm a fairly new developer, so I'm not familiar with the ROWCOUNT setting.
How and where would I check and set this? Incidentally, I am working with
SQL Server 2000.
"Alexander Kuznetsov" wrote:

> by any chance, is rowcount set to 200?
>|||Watch where you are deleting records in the cursor...delete after the fetch
next..
We don't use cursors here, but table variables, with an indentity
column..and then use a while loop.
Instead of deleting on the fly, just set a flag. Then delete all at once at
the end, based on the flag.
Jeff
"Keith" <Keith@.discussions.microsoft.com> wrote in message
news:44450145-CBC9-4AC0-B08C-DAF3F992C4B9@.microsoft.com...
>I have a cursor that is supposed to fetch all the records from a temporary
> table, #temp, one at a time, do some manipulation on the data, insert the
> results into another temporary table, #detailedTransRpt, then delete the
> record from #temp. All of the records from #temp should be deleted before
> @.@.fetch_status = -1; however, it seems that @.@.fetch_status = -1 always
> around
> the time 200 records have been fetched, thereby leaving some data in
> #temp.
> I have tried different data sets, and have compared the records on which
> the
> fetch fails, but these records have nothing in common and I can't seem to
> figure out why the fetch is failing. It seems to have more to do with the
> number of records, than anything else. Has anyone come across a similar
> problem? Any advice?|||The short answer is that it is being done this way because another developer
did it this way, and I am trying not to rewrite the stored procedure and
possibly create more bugs in the process of fixing this one. All the record
s
in #temp are transactions for a single bank account, so the records are
deleted from here as they are inserted into #detailedTransRpt, because later
a different cursor (this SP contains a billion nested cursors!) changes the
bank account that will appear in a different section of the report. If ther
e
are records still left in #temp, then all the bank account transactions get
mixed up. Like I said, this just seems to happen when there are more than
200 transactions in the report, so I was wondering if there was some
significance between the number 200 and something to do with cursors.
"Jim Underwood" wrote:

> Why are you deleting the rows within your cursor? I think you can loop
> through all the rows and delete them only when you are done with the entir
e
> set of data. I don't know if this has any effect on the cursor or not, bu
t
> it sounds a little odd and might be worth checking. Basically, I am
> wondering if updating the temp table that you are reading from might cause
> strange behavior, although I would expect an error rather than lost rows i
f
> this were the case.
> "Keith" <Keith@.discussions.microsoft.com> wrote in message
> news:44450145-CBC9-4AC0-B08C-DAF3F992C4B9@.microsoft.com...
> around
> #temp.
> the
>
>|||Now that would be an incredibly simple solution...
"Alexander Kuznetsov" <AK_TIREDOFSPAM@.hotmail.COM> wrote in message
news:1146590107.762359.308020@.y43g2000cwc.googlegroups.com...
> by any chance, is rowcount set to 200?
>|||"Keith" <Keith@.discussions.microsoft.com> wrote in message
news:F26CC2DD-B066-48E7-BB41-0A6E0F88EB97@.microsoft.com...
> I'm posting all the variable declarations, and what I set the stored
> procedure parameters to, for debugging purposes, as well as the two table
> CREATE statements, and the single cursor that I know is failing. There is
> too much code in the entire SP for me to paste here. A function splits
> the
> string from @.strbankAccID into bank account IDs, and then the
> transactions
> from a given bank account ID are put into #temp. The transactions from
> #temp
> are manipulated then put into #detailedTransRpt, and then deleted from
> #temp.
> However, the cursor @.@.fetch_status = -1 before all the transactions are
> removed from #temp, and the transactions end up being mixed up between the
> bank accounts on the report that this produces. Why was it done this way,
> you may ask? Because some other developer (who is long gone) did it this
> way
> and I am now responsible for fixing the report. Can you feel the
> frustration? :) Thanks!
I would replace the whole cursor with two INSERTs and a DELETE. Here's my
effort at the first INSERT (untested and therefore not necessarily complete
or totally accurate).
INSERT INTO #detailedTransRpt
(bankAcctID, depTransID, Header, AcctNum, BankName, AcctType, Status,
TransDate, Number, TransDesc, PaymentType, Receipt, Reconciled,
Disbursement, TransVersion, Category, SubCategory, class_cd)
SELECT NULL, T.tempDepTransID, NULL, NULL, NULL, NULL, NULL,
T.TransDate, 'Receipt #'+T.TransNumber, T.TransDesc, L.Description,
NULL,
CASE WHEN TransStatusCD = 'U' THEN '' ELSE TransStatusCD END,NULL,
CASE TransVersionCD
WHEN '0' THEN ''
WHEN '1' THEN 'Edited'
WHEN '2' THEN 'Adjusted'
WHEN '3' THEN 'Voided'
WHEN '4' THEN 'Unvoided'
WHEN '5' THEN 'Voided'
WHEN '6' THEN 'Unvoided'
END, C.Category_description, S.Sub_Category_description, M.Description
FROM #Temp AS T
JOIN Lookup AS L
ON L.Category LIKE 'PAYMENT_TYPE_CD'
AND L.Code LIKE T.PaymentType
JOIN Lookup AS M
ON M.Category LIKE 'CLASS_SCHEDULE_CAT_CD'
AND L.Code LIKE T.PaymentType
JOIN Category AS C
ON T.CategoryID = C.Category_id
JOIN Sub_Category AS S
ON T.SubCategoryID = S.Sub_Category_id
WHERE TransType = 'RT' ;
DELETE #temp WHERE TransType = 'RT' ;
David Portas, SQL Server MVP
Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.
SQL Server Books Online:
http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
--

Tuesday, February 14, 2012

Cursors....How to get away from using?

Hey guys

I have heard cursors are not the way to go. But I am wondering if/how to get out of a situation that I am using a cursor in...in order to make my stored proc run more effieciently.

I am quite novice in my abilities and I am completely stumped on how to get around using them.

As far as INSERTs go, I think I can work around that, but how would I write UPDATE statements for all lines of a table to say pull a key from another table to reference them together?

I usually make my SELECT statement in the cursor, then update against the criteria from the SELECT statement. Now this is quite a slow process when I am updating 100K records.

Any help or pointers or a link to a good tutorial would be woderful.

Thanks
tiborcursors are on the rare occassion the right way to go. incrementing totals for example. or if the situation requires row by row processing like you need to fire an extended stored procedure.

what you want to read about though is set based processing.

tell me, can you take your select statement and move the from and where clause to the update statement to create an UPDATE FROM statement? Bye bye cursor.|||You might want to take a look at the documentation (http://technet.microsoft.com/en-us/library/ms177523.aspx). Take a look at examples C and F. Example C (from clause) works in both SQL Server 2000 and SQL Server 2005, although not very well documented for SQL Server 2000. Example F (Common Table Expression) works only in SQL Server 2005, but I think it will potentially perform better in some cases. I have not verified this though.|||Great, thanks guys!

The "Using UPDATE with the FROM Clause" in the documentation was exactly what i needed...it took 30 seconds vs 1.5 hours, haha.

I appreciate the help very much.

tibor|||I always love some of the subject titles

Like my response for this one (and don't get offended) would have been..

"Leave the IT Business"

But i'm glad you got what you needed.

Now, post the code so we can make it really fly|||Well, no offense taken...but dont assume that because I asked a SQL question that I am in the IT business. :)|||Well, since your query used quite some amount of time, I DO assume that you have quite a bit of data as well, and you appears to work on some data in or from some kind of business. If that is correct, well... I'm glad I could help, but I would be concerned about what you can end up doing. Databases are not to play with, and as you have noticed, a badly written query may cause the server working for hours, or even days. Please keep that in mind.

Cursors with UNION in select doesn't work?

Hi,
I'm trying to open a cursor by selecting datas from an UNION of two tables.
I keep getting the error "incorrect syntax near the keyword 'UNION'".
Here my code...
DECLARE cArticles CURSOR FAST_FORWARD
FOR
select id from vw_articles where isFrontPage = 1 and categoryId = @.cId order
by frontPageDate desc
UNION
select id from vw_articles where isFrontPage = 1 and categoryId in (select
fk_tbl_category_child_id from tbl_subCategories where
fk_tbl_category_parent_id = @.cId) order by frontPageDate desc
OPEN cArticles
...
I tried with parenthesis, temp table... didn't work as well.
Any idea of how I can open a cursor with a select in two tables?
Thanks
StephaneThe problem is not the cursor. The problem is that you have order by within
your union. You can only apply order by on the whole set, not on individual
elements of the union.
"Stephane" <Stephane@.discussions.microsoft.com> wrote in message
news:2847989A-9ECA-4500-84F2-82BE1CA089DC@.microsoft.com...
> Hi,
> I'm trying to open a cursor by selecting datas from an UNION of two
> tables.
> I keep getting the error "incorrect syntax near the keyword 'UNION'".
> Here my code...
> DECLARE cArticles CURSOR FAST_FORWARD
> FOR
> select id from vw_articles where isFrontPage = 1 and categoryId = @.cId
> order
> by frontPageDate desc
> UNION
> select id from vw_articles where isFrontPage = 1 and categoryId in (select
> fk_tbl_category_child_id from tbl_subCategories where
> fk_tbl_category_parent_id = @.cId) order by frontPageDate desc
> OPEN cArticles
> ...
> I tried with parenthesis, temp table... didn't work as well.
> Any idea of how I can open a cursor with a select in two tables?
> Thanks
> Stephane
>|||Great! It works!
Thanks a lot
Stephane
"Aaron Bertrand [SQL Server MVP]" wrote:

> The problem is not the cursor. The problem is that you have order by with
in
> your union. You can only apply order by on the whole set, not on individu
al
> elements of the union.
>
>
> "Stephane" <Stephane@.discussions.microsoft.com> wrote in message
> news:2847989A-9ECA-4500-84F2-82BE1CA089DC@.microsoft.com...
>
>|||What about:
DECLARE cArticles CURSOR FAST_FORWARD
FOR
SELECT * FROM
(
select id from vw_articles where isFrontPage = 1 and categoryId = @.cId
order
by frontPageDate desc
UNION
select id from vw_articles where isFrontPage = 1 and categoryId in
(select
fk_tbl_category_child_id from tbl_subCategories where
fk_tbl_category_parent_id = @.cId) order by frontPageDate desc
) SubQuery
OPEN cArticles
HTH, Jens Suessmeyer.

Cursors vs. Queries

Can someone give me an example of when I would use a cursor instead of a que
ryIf you can use a query to get what you want you should never use a cursor.
Cursors are best for maintenance type tasks where you need to loop thru say
a collection of tables and do something such as reindexing. As for data use
they should be used as a last resort only. Sometimes it is just not
practical or even feasible to issue strictly set based commands and get what
you want so a cursor might be necessary. For instance if you have to do
some work on each row that can only be done thru calling a stored
procedure(s) you might create a cursor and loop thru calling it for each
row. Otherwise try to use standard set based commands.
Andrew J. Kelly SQL MVP
"Vincent Jones" <vncntj@.hotmail.com> wrote in message
news:ba2a2d30.0401140615.581598f2@.posting.google.com...
quote:

> Can someone give me an example of when I would use a cursor instead of a

query|||In a properly designed database the occassions when a cursor is a good and
efficient solution to a problem are rare.
Sometimes cursors are useful for certain administrative functions or for
processes such as Andrew described.
Very occassionally you find a data manipulation problem which doesn't have a
feasible set-based solution. If you think you've encountered one of those
situations then post your problem here and see if someone else can suggest
an alternative.
In reality, many examples of cursor code are written by programmers who
aren't familiar with SQL and are more comfortable with row-by-row sequential
processing than with set-based SELECT statements. So for data manipulation
problems my general rule would be: If you think you need a cursor - think
again. If you're sure you need a cursor - get a second opinion.
David Portas
--
Please reply only to the newsgroup
--

Cursors vs. Queries

Can someone give me an example of when I would use a cursor instead of a queryIf you can use a query to get what you want you should never use a cursor.
Cursors are best for maintenance type tasks where you need to loop thru say
a collection of tables and do something such as reindexing. As for data use
they should be used as a last resort only. Sometimes it is just not
practical or even feasible to issue strictly set based commands and get what
you want so a cursor might be necessary. For instance if you have to do
some work on each row that can only be done thru calling a stored
procedure(s) you might create a cursor and loop thru calling it for each
row. Otherwise try to use standard set based commands.
--
Andrew J. Kelly SQL MVP
"Vincent Jones" <vncntj@.hotmail.com> wrote in message
news:ba2a2d30.0401140615.581598f2@.posting.google.com...
> Can someone give me an example of when I would use a cursor instead of a
query|||One query statement is much faster than the equivalent
Cursor query.
If I am correct (and please tell me if I'm wrong) its
about 20 times faster than putting the same statement in a
cursor.
However cursors are more controllable, and better for
error checking and error recovery.
My rule of thumb.
If you can get a way with using a query then use it,
however you will need cursors to do anything complex.
J
>--Original Message--
>Can someone give me an example of when I would use a
cursor instead of a query
>.
>|||In a properly designed database the occassions when a cursor is a good and
efficient solution to a problem are rare.
Sometimes cursors are useful for certain administrative functions or for
processes such as Andrew described.
Very occassionally you find a data manipulation problem which doesn't have a
feasible set-based solution. If you think you've encountered one of those
situations then post your problem here and see if someone else can suggest
an alternative.
In reality, many examples of cursor code are written by programmers who
aren't familiar with SQL and are more comfortable with row-by-row sequential
processing than with set-based SELECT statements. So for data manipulation
problems my general rule would be: If you think you need a cursor - think
again. If you're sure you need a cursor - get a second opinion.
--
David Portas
--
Please reply only to the newsgroup
--|||> however you will need cursors to do anything complex.
Could you give an example of a problem that is too complex for a query
solution?
--
David Portas
--
Please reply only to the newsgroup
--

Cursors and Temp Table : in SQL Server

1. Can I pass Parameter to a Cursor ?
2. Is it must to declare the Holding variable for a Cursor above it
before opening ?
3. Can a temp table be update ?1) Yes (see example below)
2) No (see example below)
Cursor example:
use pubs
DECLARE @.State char(2)
set @.State = 'UT'
PRINT '-- Utah Authors report --'
DECLARE authors_cursor CURSOR FOR
SELECT au_id, au_fname, au_lname
FROM authors
WHERE state = @.State
ORDER BY au_id
OPEN authors_cursor
DECLARE @.au_id varchar(11), @.au_fname varchar(20), @.au_lname varchar(40),
@.message varchar(80), @.title varchar(80)
FETCH NEXT FROM authors_cursor
INTO @.au_id, @.au_fname, @.au_lname
print @.au_id
CLOSE authors_cursor
DEALLOCATE authors_cursor
3) Yes (see example below)
Create table #test (a char(1))
insert into #test values ('a')
select * from #test
update #test
set a = 'b'
select * from #test
drop table #test
"akpatelrs@.googlemail.com" wrote:

> 1. Can I pass Parameter to a Cursor ?
> 2. Is it must to declare the Holding variable for a Cursor above it
> before opening ?
> 3. Can a temp table be update ?
>