Question

How to update a sql table from a foxpro cursor

Asked by: marknicks

I've  created a cursor from a sql select statement.  

rc=sqlexec(nHandleTMD, "select * from DEDUP where SESSION_ID = '" + sSession_ID + "' ORDER BY MAILING_DPBC, MAILING_ADDR_LINE1 into sqlResult")

I can scan through the cursor and insert selected rows into a sql table.

scan
      strSql = "insert into DEDUP (SESSION_ID, TABLE_NAME, DUMMY) values ('" + strSession_ID + "', '" + strTable + "', " + ALLTRIM(STR(sqlresult.dummy)) + ")"
      rc=sqlexec(nHandleTMD, strSql)
endscan

However, this process is slow and I'd like to do something like this:

strSql = "insert into DEDUP (SESSION_ID, TABLE_NAME, DUMMY) select session_id, table_name, dummy from sqlResult"  
rc=sqlexec(nHandleTMD, strSql)

That statement gives me an Invalid Object error.  
I would appreciate any suggestions.

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-04-29 at 20:26:31ID24367897
Tags

vfp

,

foxpro

,

sql

Topic

FoxPro Database

Participating Experts
3
Points
500
Comments
14

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. SQLExec
    Can I call another SQLExec if the first SQLExec return 0(still executing SQL) ? If yes, how can I know the result of the first SQLExec ? Andrew
  2. Scan endScan
    I'm not to familiar with FoxPro and I'm having a problem with Scan. Here is the code: Sele currentmaars scan if currentmaars.dodic = gc_dodic NewNSN = currentmaars.nsn sele currentmaars scan SUM CURRENTMAARS.QUANTITY TO L_QTYA FOR DODIC = GC_DODIC; AND (nsn = ...
  3. sqlexec
    Can anyone tell me what is wrong with this line of code... = SQLEXEC(gnConnHandle, "UPDATE webtransact (itowengrav, itname, itbrand, itmodel, itdescrip, itdescrip2, farmtype, farmaction, farmgauge, farmfinish, farmbarrel, jewtype, jewmetal, jewkarat, jewweight, jewgende...
  4. sqlexec help
    can someone condence this down to a proper statment ( two lines) cUpdate = "update users set userspdname = '" + alltrim(passuserspdname) + "' where localID = " + passcontactid = sqlexec(gnConnHandle, cUpdate) cUpdate = "update users set foruser = '&...
  5. Recursive functions and Cursors
    I have only been using FoxPro for a month and am not sure how to make a cursor local. The following function is called recursively to load categories stored in a database into a TreeView control. The problem is that the cursor in the recursive function is not remembered (tre...
  6. SQLEXEC() cursor
    I have a reporting app that creates output in DBF format. I am switching the source data from DBF to SQL Sever. When I use the SQLEXEC() function my result set goes into the "cursor" which I then copy out (copy to) to the output DBF file. For performance reason...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: Olaf_DoschkePosted on 2009-04-30 at 00:10:56ID: 24267555

Well, you can't access VFP cursors from within SQL Server. SQLEXEC just sends the SQL string to SQL Server, you can embed parameters with ?varname and SQLExec also sends variable values in these places, but you can't send a VFP cursor, not even with ?aliasname.

There are ways to make an SPT result cursor updatable, you need to adress and set several properties of the cursor via SQLSetprop(). The much easier way is to use the Cursoradapter class of VFP, which generates such updatable Cursors with much more ease. The native Builder for the cursoradapter is ratherhelpful for that.

You can then do any changes in the cursor and simply commit them to SQL by a normal Tableupdate(), as you would do with local or remote view.

Bye, Olaf.

 

by: pcelbaPosted on 2009-04-30 at 03:35:21ID: 24268436

First of all you first select cannot work:
rc=sqlexec(nHandleTMD, "select * from DEDUP where SESSION_ID = '" + sSession_ID + "' ORDER BY MAILING_DPBC, MAILING_ADDR_LINE1 into sqlResult")

It should probably be:
rc=sqlexec(nHandleTMD, "select * from DEDUP where SESSION_ID = '" + sSession_ID + "' ORDER BY MAILING_DPBC, MAILING_ADDR_LINE1", "sqlResult")

OR it could be:
rc=sqlexec(nHandleTMD, "select * into sqlResult from DEDUP where SESSION_ID = '" + sSession_ID + "' ORDER BY MAILING_DPBC, MAILING_ADDR_LINE1")


The rest needs some explanations because it seems you are trying to insert previously selected records to the same table with diffrent SESSION_ID and TABLE_NAME . Am I right? Please correct me.

So, if you really need it then you may create the temporary table on the server. Suppose "sSession_ID", "strSession_ID", and "strTable" are memory variables.  The ORDER BY part of the select is not necessary, it does not ensure the right row order in the target table and it just slows down the SELECT. Of course, you may use it.

strSql = "select '" + strSession_ID + "' SESSION_ID, '" + strTable + "' TABLE_NAME, DUMMY into #sqlResult from DEDUP where SESSION_ID = '" + sSession_ID + "'")
rc=sqlexec(nHandleTMD, strSql)
IF rc > 0
  strSql = "insert into DEDUP (SESSION_ID, TABLE_NAME, DUMMY) select session_id, table_name, dummy from #sqlResult DROP TABLE #sqlResult"
  rc=sqlexec(nHandleTMD, strSql)
ELSE 
  *-- Error creating the temp. table
ENDIF
                                              
1:
2:
3:
4:
5:
6:
7:
8:

Select allOpen in new window

 

by: marknicksPosted on 2009-04-30 at 05:09:37ID: 24268988

PCElba you are correct.  I transposed the first select.  It is actually as you suggest.  
And I left out some of the code to shorten the post.  After the select creates the cursor, duplicates are deleted - hence the order by.  Then a delete is performed on the original table and the remaining rows in the cursor are reinserted into the original table.

The point of all this is that foxpro is faster at removing the duplicate rows.  But I'm hitting a bottleneck when re-inserting the rows back into the table.

I'm going to run some tests using Olaf's suggestion to see if that will be the best approach.

Mark

 

by: pcelbaPosted on 2009-04-30 at 05:54:36ID: 24269366

So, if it is all done to remove duplicities then you could do it in ONE DELETE command at SQL Server. I would just need to know what rules are used to remove duplicities in VFP.

If the deletion needs some manual overview at VFP side you may delete records based on the final status of the VFP cursor. In such case the cursor adapter is good choice. To delete and insert everything does not make sense namely in case the number of rows in DEDUP does not change so much.

 

by: dportasPosted on 2009-04-30 at 13:26:43ID: 24274086

>> The point of all this is that foxpro is faster at removing the duplicate rows.

I doubt it, since you'll have to retrieve all the data and then put it back or delete the duplicates. You can do that with a single statement in SQL. Please post the SQL that you tried and maybe we can improve on it.

 

by: dportasPosted on 2009-04-30 at 13:27:48ID: 24274093

PS. Tell us what version of SQL Server you are using.

 

by: Olaf_DoschkePosted on 2009-04-30 at 13:42:45ID: 24274228

Yes, in case you do all this to remove duplicates a delete statement to SQL should be the fastest, without data first being retrieved just to be deleted.

DELETE FROM theTABLE t1 FULL JOIN theTABLE t2 where t1.ID # t2.ID and t1.field = t2.field and t1.field2=t2.field2...

Where ID would be somthing that isn't double in any row and would ensure you're not matching a record with itself. Otherwise all rows would be deleted because each row matches itself of course. If you don't have an ID field and so are lacking a primary key, then you would need to ensure different rownums.

Bye, Olaf.

 

by: Olaf_DoschkePosted on 2009-04-30 at 13:44:00ID: 24274236

sorry, # is of course Foxpro Syntax for <>, take <> at SQL Server, or NOT t1.ID = t2.ID and ...

Bye, Olaf.

 

by: pcelbaPosted on 2009-04-30 at 14:06:26ID: 24274428

And if you have neither unique IDs nor rownums, you may simply

SELECT DISTINCT * INTO #NODUP FROM DEDUP
TRUNCATE TABLE DEDUP
INSERT INTO DEDUP SELECT * FROM #NODUP
DROP TABLE #NODUP

Olaf, the FULL JOIN should probably be CROSS JOIN.

 

by: Olaf_DoschkePosted on 2009-04-30 at 14:14:05ID: 24274497

Yes, pcelba, but even that lacks a little good logic, if you do that delete you delete both of the dup rows, because each one is matching another. Depens a little in how SQL optimises that join. If the first row matching a second is deleted and therefore that deleted row isn't found anymore as a match, then you only delete one of the dups, but if the matching is done in advance you may delete both dups with my DELETE. DISTINCT is of course a much easier way.

Bye, Olaf.

 

by: marknicksPosted on 2009-05-07 at 05:26:31ID: 24324806

Olaf, I like the idea of eliminating foxpro completely and remaining in SQL (which I should have done from the beginning) and I have been testing your solution.  I'm assuming from your example that you can create a cross join of the same table, which eliminates writing to a temp table and then reading back the distinct rows.  I tested this:

Delete FROM TEMP_PROP t1 CROSS JOIN TEMP_PROP t2 where t1.RowID <> t2.RowID
 and t1.situs_dpbc = t2.situs_dpbc

I received this error:
Line 1: Incorrect syntax near 't1'.

 

by: dportasPosted on 2009-05-08 at 14:37:18ID: 24340497

You need to specify something other than <> for the RowID comparison, otherwise you'll delete EVERY row where the situs_dpbc has more than one RowID. I'm assuming that RowID is a unique column in the table. Try the following (be sure you have a good backup and test it out before you try it on data that matters!):

DELETE t1
FROM TEMP_PROP t1, TEMP_PROP t2
WHERE t1.RowID > t2.RowID
AND t1.situs_dpbc = t2.situs_dpbc ;

That's the Microsoft proprietary syntax for DELETE. I would prefer to use the standard ISO syntax to do the same thing:

DELETE FROM TEMP_PROP
WHERE EXISTS
(SELECT 1
 FROM TEMP_PROP t2
 WHERE TEMP_PROP.situs_dpbc = t2.situs_dpbc
 AND TEMP_PROP.RowID > t2.RowID);

 

by: marknicksPosted on 2009-05-13 at 13:44:03ID: 24379460

This series of queries turned out to be the best approach, elminating the FoxPro routines.

"select * into #Temp_Dups from Temp_Prop
      where (rowid in (select MIN(rowid) as min_id from temp_prop
            group by mailing_zip, mailing_addr_line1
              having count(*) > 1)) AND (Session_ID = '" & strSession_ID & "')"

"Delete temp_prop from TEMP_PROP t1
      WHERE (EXISTS ( SELECT NULL FROM TEMP_PROP t2 where(t1.rowid <> t2.rowid)
        and t1.mailing_zip + t1.mailing_addr_line1 = t2.mailing_zip + t2.mailing_addr_line1))
        AND (Session_ID = '" & strSession_ID & "')"

"alter table #Temp_Dups drop column rowid"

"insert Temp_Prop select * from #Temp_Dups"

I appreciate all your comments as they pointed me in the right direction!

 

by: marknicksPosted on 2009-05-13 at 13:46:05ID: 31576276

Thanks to all.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...