473,765 Members | 2,010 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

I need a little cursor help

CK
Good Morning All,
Can use use a variable for the FOR clause in a cursor?

Example
I have
DECLARE @a varchar(50), @b varchar(50), @c varchar(50)
DECLARE @sql varchar(255)
DECLARE @x varchar(50), @y varchar(50), @z varchar(50)

DELCARE outer_cursor CURSOR FOR
SELECT this, that, other
FROM sometable

OPEN outer_cursor
FETCH NEXT FROM outer_cursor
INTO @a, @b, @c

WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @sql = 'SELECT ' + @a + ', ' + @b + ', ' + @c + ' FROM
someothertable'

--Here is the question. Can I do this? If not how would I do this?
DELCARE inner_cursor CURSOR FOR @sql -- <~~Is this legal?
OPEN inner_cursor
FETCH NEXT FROM inner_cursor
INTO @x, @y, @z

--etc..

Is it legal to do this in SQL? Is there a better way? I know everybody hates
cursors, but I am just curious if this would work.

TIA,
~ck
Sep 11 '08 #1
4 1620
CK (c_**********@h otmail.com) writes:
DELCARE outer_cursor CURSOR FOR
Before you go any furher, make it a habit to create your cursors STATIC:

DECLARE outer_cursor CURSOR STATIC FOR

This can considerably improve the performance of your cursor operations,
and it also avoid surprises if you update rows in the cursor.
--Here is the question. Can I do this? If not how would I do this?
DELCARE inner_cursor CURSOR FOR @sql -- <~~Is this legal?
No that is not legal, but you can use dynamic SQL for the task. I have
a longer article on dynamic SQL on my web site. This link goes directly
to the cursor section:
http://www.sommarskog.se/dynamic_sql.html#cursor.

--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se

Links for SQL Server Books Online:
SQL 2008: http://msdn.microsoft.com/en-us/sqlserver/cc514207.aspx
SQL 2005: http://msdn.microsoft.com/en-us/sqlserver/bb895970.aspx
SQL 2000: http://www.microsoft.com/sql/prodinf...ons/books.mspx

Sep 11 '08 #2
>Can you use a variable for the FOR clause in a cursor? <<

No. But a better question is why you are using a cursor at all.
Given OLAP functions, CASE expressions, etc. in current Standard SQL,
you should only use 1-2 in your entire career at most.
>Is there a better way? I know everybody hates cursors, but I am just curious if this would work. <<
Well, is there a WORSE way? Dynamic SQL declaring cursors is a
nightmare on soooo many levels. Saying SQL people hate cursors is a
mild understatement. What a cursor says is that either the product or
the programmer is so weak that we have to throw away 30 years of RDBMS
and revert to low-level procedural code. And 99.98% of the time when
you see dynamic SQL, it is an admission that the programmer never had
a basic software engineering course and does not know about cohesion.

What is the actual problem you are trying to solve? Or was this a "If
I poison my cattle, will they die?" kind of question?
Sep 11 '08 #3
CK wrote:
Can use use a variable for the FOR clause in a cursor?

Example
I have
DECLARE @a varchar(50), @b varchar(50), @c varchar(50)
DECLARE @sql varchar(255)
DECLARE @x varchar(50), @y varchar(50), @z varchar(50)

DELCARE outer_cursor CURSOR FOR
SELECT this, that, other
FROM sometable

OPEN outer_cursor
FETCH NEXT FROM outer_cursor
INTO @a, @b, @c

WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @sql = 'SELECT ' + @a + ', ' + @b + ', ' + @c + ' FROM
someothertable'

--Here is the question. Can I do this? If not how would I do this?
DELCARE inner_cursor CURSOR FOR @sql -- <~~Is this legal?
OPEN inner_cursor
FETCH NEXT FROM inner_cursor
INTO @x, @y, @z

--etc..

Is it legal to do this in SQL? Is there a better way? I know everybody hates
cursors, but I am just curious if this would work.
There's a reason everybody hates them; they're easy to screw up, and
slow even if you don't. Do you really need to process rows one at a
time? Even if you do, a simple workaround is to have the inner cursor
just pull all columns from someothertable, then dynamically copy the
relevant ones into your variables.

What is the real-world situation behind this example? Knowing that, we
may be able to give more specific suggestions on avoiding all this mess.
Sep 15 '08 #4
CK
How do I write a set based query? I have a groupSets table with fields
setId, idField, datasource, nameField, prefix, active
Data:
1,someIDfield, someTable, someField, pre1, 1
2,someotherIDfi eld, someTable, someotherField, pre2, 1
3,somethirdIDfi eld, someTable, somethirdField, pre3, 1
4,somefourthIDf ield, someotherTable, somefourthField , pre4, 1

I need to generate records in another table by constructing queries from the
data in groups sets. I need to insert a record for each distinct result of
the query.
Example:
SELECT DISTINCT someIDfield FROM someTable WHERE someIDfield IS NOT NULL

then I need to do an insert for each result of the above query

INSERT INTO groups(setId, groupName, active, groupingEntityI D)
VALUES (1, prefix + nameField, 1, result1)

INSERT INTO groups(setId, groupName, active, groupingEntityI D)
VALUES (1, prefix + nameField, 1, result2)

INSERT INTO groups(setId, groupName, active, groupingEntityI D)
VALUES (1, prefix + nameField, 1, result3)

INSERT INTO groups(setId, groupName, active, groupingEntityI D)
VALUES (1, prefix + nameField, 1, result4)

INSERT INTO groups(setId, groupName, active, groupingEntityI D)
VALUES (1, prefix + nameField, 1, resultN)

--next reord from groupSets
SELECT DISTINCT someotherIDfiel d FROM someTable WHERE someotherIDfiel d IS
NOT NULL
INSERT INTO groups(setId, groupName, active, groupingEntityI D)
VALUES (2, prefix + nameField, 1, result1)

INSERT INTO groups(setId, groupName, active, groupingEntityI D)
VALUES (2, prefix + nameField, 1, result2)

INSERT INTO groups(setId, groupName, active, groupingEntityI D)
VALUES (2, prefix + nameField, 1, result3)

INSERT INTO groups(setId, groupName, active, groupingEntityI D)
VALUES (2, prefix + nameField, 1, result4)

INSERT INTO groups(setId, groupName, active, groupingEntityI D)
VALUES (2, prefix + nameField, 1, resultN)
I basically want to do the same operation on each record in the groupSets
table. How can I accomplish this without a cursor? Any ideas?
Thanks for your help,
~ck

"--CELKO--" <jc*******@eart hlink.netwrote in message
news:32******** *************** ***********@m3g 2000hsc.googleg roups.com...
>>Can you use a variable for the FOR clause in a cursor? <<

No. But a better question is why you are using a cursor at all.
Given OLAP functions, CASE expressions, etc. in current Standard SQL,
you should only use 1-2 in your entire career at most.
>>Is there a better way? I know everybody hates cursors, but I am just
curious if this would work. <<

Well, is there a WORSE way? Dynamic SQL declaring cursors is a
nightmare on soooo many levels. Saying SQL people hate cursors is a
mild understatement. What a cursor says is that either the product or
the programmer is so weak that we have to throw away 30 years of RDBMS
and revert to low-level procedural code. And 99.98% of the time when
you see dynamic SQL, it is an admission that the programmer never had
a basic software engineering course and does not know about cohesion.

What is the actual problem you are trying to solve? Or was this a "If
I poison my cattle, will they die?" kind of question?

Sep 23 '08 #5

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

Similar topics

1
2113
by: Antonio | last post by:
Hope that some perl guru will help me: I've implemented an inverted index using PERL + DB_File (using hash, and b-tree). Therefore, i have my indexer and my searcher (a little search engine, indead). Given a word in the lexicon i stored in B-tree the corrispondent inverted list, using gap coding. For istance i have:
3
2377
by: Fabri | last post by:
Do you know please why in Firefox there is this strange behavior? This work: --> <img src="mickey.jpg" width="200" height="150" onMouseOver="document.body.style.cursor ='move';"> But if I try to add usemap="#map" the cursor doesn't transform itself in
30
4168
by: nephish | last post by:
Hey there, i have tried about every graphing package for python i can get to work on my system. gnuplot, pychart, biggles, gdchart, etc.. (cant get matplot to work) so far, they all are working ok. I need to make an x y chart for some data that comes in from sensors at different times durring the day. i need it to show the value in the y and the time in the x . no problem so far. But what i cannot get to happen is to scale x (time of the...
1
4242
by: Rohit Raghuwanshi | last post by:
Hello all, we are running a delphi application with DB2 V8.01 which is causing deadlocks when rows are being inserted into a table. Attaching the Event Monitor Log (DEADLOCKS WITH DETAILS) here. From the log it looks like the problem happens when 2 threads insert 1 record each in the same table and then try to aquire a NS (Next Key Share) lock on the record inserterd by the other thread. Thanks Rohit
3
3162
by: ssb | last post by:
Hello, This may be very elementary, but, need help because I am new to access programming. (1) Say, I have a column EMPLOYEE_NAME. How do I fetch (maybe, cursor ?) the values one by one and populate a combo box with these names. (this way, I can display all the EMPLOYEE_NAME values) (2) In general, can I do additional processing on column values from
2
1555
by: Alex | last post by:
In the code below, clicking on the button ButtonChangeCursor changes the form's cursor to a WaitCursor. Clicking the button ButtonRestoreCursor changes the form's cursor back to its original cursor. For the reasons I explain below I wouldn't expect this code to behave as it does, so why does it work? Public Class Form1 Dim OldCursor As Cursor Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
33
2392
by: STILL LEARNING | last post by:
I'm not sure if this can even be done, but what prompts the question is my desire to be able to create an "Uber Link" script/code of some sort, such that even if the html page contains nothing but a background image -or- a background color -- in other words, the page has neither content nor placed images -- any click, ANYWHERE, will launch the URL in your browser. I realize I can make traditional text links and graphics links; what I'm...
19
3314
by: Ganesh J. Acharya | last post by:
Hi there, I want to redesign my website and make that look professional. I made this about 6 years ago with very little knowledge of internet. Today I am getting about 4000 visitors a day for the same. What are the things I need to keep in my mind when doing this process.
22
4025
by: Chuck Connors | last post by:
Hey guys. I'm working on a little program to help my wife catalog her/ our coupons. I found a good resource but need help formatting the text data so that I can import it into a mysql database. Here's the data format: 409220000003 Life Fitness Products $1 (12-13-08) (CVS) 546500181141 Oust Air Sanitizer, any B1G1F up to $3.49 (1-17-09) .35 each 518000159258 Pillsbury Crescent Dinner Rolls, any .25 (2-14-09) 518000550406 Pillsbury...
0
10164
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10007
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9835
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8833
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7379
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6649
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5277
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5423
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2806
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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

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