Question

SQL identity fields do not update after posting an ADO dataset (Delphi 2006 + SQL Server 2003)

Asked by: cbaron

I am using SQL Server 2005 linked to ADO datasets in Delphi 2006.

I have a table [FCTable] which contains a field [FC_FCRef] which is defined as an IDENTITY field in the sql (auto incremented by the server itself).

I have a piece of code which appends a record to FCTable, sets some fields in the record then posts it.  This works fine and when I look at the resultant record in SQL Server manager I can see that the identify field FC_FCRef has been set to a value by the server.  The problem is that the ADO data set doesn't see the true value of FC_FCRef and believes it still to be Zero as it's the server side that's set it not the code.  This means when the next lines of code try to save the FC_FCRef somewhere it's saving the wrong value.

If I close the open the table the values are re-read and are correct but obviously that's highly inefficient when I'm updating hundreds of records.  If I set the dataset CursorLocation to clUseServer then it also works correctly but using server side cursors is not recommended as it's (apparently) very inefficient.

Is there any simple way I can get the ADO dataset to get the correct value for the field?

For your reference the Delphi code is;

            { Create a blank claim record }
            FCTable.Append;
            { Complete the record fields }
            FCTableFC_Date.AsString := DateToStr(Now());
            .
            .
            .
            { Post the claim record }
            FCTable.Post;
            { Update the census record with the claim reference }
            CPTable.Edit;
            CPTableCP_FCRef.AsLargeInt := FCTableFC_FCRef.AsLargeInt;
            CPTable.Post;

Using this code the CP_FCRef simply gets set to zero every time even though the actual record in the FCTable is showing a unique number of FC_FCRef :-(

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
2006-08-09 at 07:58:35ID21948484
Tags

delphi

,

identity

,

sql

,

ado

,

update

Topics

Delphi Programming

,

Delphi Database

Participating Experts
5
Points
500
Comments
26

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. ADO and ODBC
    Why use ADO insted of ODBC? (ADO is available only from version 5 of Delphi?) Regards NTony.
  2. string truncated in ADO dataset
    I am using Delphi 6 ADO dataset to store the result of a SQL query from Oracle database. One of the field (senddate) return 20021030 and i need to convert to 30/10/2002 and then display the result set in a grid. Problem 1 : delphi return me a message that i cannot modify a r...
  3. need example (msaccess db with delphi by ado)??
    need example (msaccess db with delphi by ado)??
  4. A better component ADO for Delphi? Exist?
    Hello Guys, I am using ado connection for all my applications. But Ado that comes with Borland in delphi 5 is not so good due to some bugs. Is there any component better than component ado that comes with Delphi? It doesn't matter if it is free or paid component. Thanks ver...
  5. DELPHI - ADO Dataset to Excel
    I want to export the records of a table in MS Access to a excel file or a tab delimited text file in DELPHI. Here i have tried with ADOTable since i have no idea of exporting it with ADODataset. My code is, procedure TForm1.Button4Click(Sender: TObject); const adClipStrin...

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: mokulePosted on 2006-08-09 at 11:07:53ID: 17281505

Maybe try to set
CPTableCP_FCRef.AutoGenerateValue := arAutoInc;

 

by: LimbeckPosted on 2006-08-09 at 12:28:53ID: 17282141

maybe FCTable.Refresh after the post. be carefull by the way if the autoincrement field is the index you are using. it might be best to use a diff index

also see:
http://bdn.borland.com/article/16123

 

by: cbaronPosted on 2006-08-09 at 14:47:18ID: 17283297

Thanks Mokule, the arAutoInc looked very promising, especially after I read up on it, but sadly when I set the option it makes no difference :-((

Doing a fctable.refresh just returns and error saying I don't have a key.

 

by: kretzschmarPosted on 2006-08-09 at 22:21:07ID: 17285304

use the requery method (if provided)

meikl ;-)

 

by: LimbeckPosted on 2006-08-09 at 23:43:13ID: 17285630

can you use an sql command to insert then use table.refresh?

i take it it is single user since the refresh bit will cause other problems as well? (other users changing data)

 

by: calinutzPosted on 2006-08-10 at 00:10:57ID: 17285745

CPTable.Active:=false;
CPTable.Active:=true;

Regards

 

by: cbaronPosted on 2006-08-10 at 01:38:46ID: 17286105

Ok, the requery method suggested by kretzschmar works but reading the Borland documentation on it apparently its just the same as closing and opening the database except it maintains cursor location.

As I indicated in my original question "If I close the open the table the values are re-read and are correct but obviously that's highly inefficient when I'm updating hundreds of records" (not sure why calinutz re-suggested it) so if that the only way to do it or is there a more efficient way?

Thanks.

 

by: LimbeckPosted on 2006-08-10 at 01:54:30ID: 17286156

again,use a sql component to add, then refresh the table ;)

 

by: cbaronPosted on 2006-08-10 at 02:02:41ID: 17286191

Limbeck, thanks for the suggestion but as I've already said, if I call FCTable.refresh I just get a key error and if I update FCTable with an SQL and don't refresh then later on the app complains data has been updated by another method and errors.

 

by: LimbeckPosted on 2006-08-10 at 02:07:17ID: 17286206

hmm yes, but why not do the insert in an query component, and after you executed this statement refresh the table. do you still get an error then?

 

by: cbaronPosted on 2006-08-10 at 02:17:01ID: 17286246

Yes, I've tried it in a TADOQuery as that's the only way I would know how to do a direct SQL command.

Perhaps this is all because I'm using ADO rather than dbExpress?  If dbExpress is a better solution (more efficient) then I'm happy to consider moving to that instead of ADO as long as I can get record selection in grids to work properly as when I tried it before and set the RowCurrentColor of the grid to blue, ALL rows display blue regardless of what I do to the cursor!

Perhaps I should have stuck to good old BDE ... lol :-))

 

by: kretzschmarPosted on 2006-08-10 at 02:43:48ID: 17286341

>I'm updating hundreds of records
in case on such amount (sounds like a batch)
what for an interest is then to get back the autogenerated value?

a requery is fast enough for a dialog-app

meikl ;-)

 

by: cbaronPosted on 2006-08-10 at 09:43:25ID: 17289269

Meikl, the interest in getting back the autogenerated value is for auditing.  The FCTable records are finance claims generated from census records in the CPTable so for traceability once the FCTable record is generated I write back the number to the CPTable.

It is done on a "Batch" basis with each batch containing 50 to 100 records however this is a national web based system and we could have up to fifty people at once doing this batch process and potentially thousands of other people updating other records so I need to be very efficient when I'm hitting the SQL server.

 

by: kretzschmarPosted on 2006-08-10 at 10:54:35ID: 17289867

well, ok, currenlty i have never used d2006,
so i don't know what is changed there.
my last release i have coded with was d7

i see two possibilities (if possible)
- use a trigger on your targettable to perform the auditing
- use a stored procedure which returns the id so that you can supply it for your insert
(don't know if this is possible with SQLServer, my focus is more on oracle)

meikl ;-)

 

by: cbaronPosted on 2006-08-10 at 13:42:31ID: 17291129

I'm not an SQL server expert.  I know you can have both triggers and stored procedures on SQL server but I would not know how to make them properly or how to use them to link back to Delphi.

I have made a stored procedure once in my life, so do a complex calculation for returning to another column not to Delphi.  I've never used triggers and know nothing about them.

It looks like there is no easy solution for this problem :-(

 

by: LimbeckPosted on 2006-08-10 at 22:12:39ID: 17293764

maybe you should consider a workaround like using a tquery (with the wehre clause) instead of a ttable so your datasets wont be as large and the requery wont affect performance all that much.

 

by: LimbeckPosted on 2006-08-10 at 22:16:01ID: 17293781

i use Firebird myself mostly, and instead of an autoincrement field i usually use a generator on the server that returns an unique id, i read that in my program and use it to save the record

 

by: kretzschmarPosted on 2006-08-10 at 22:22:21ID: 17293810

>instead of an autoincrement field i usually use a generator
because Firebird has no autoincrement field  . . .

 

by: LimbeckPosted on 2006-08-10 at 22:23:50ID: 17293818

;)

well and it avoids those nasty key problems since my id is usually my prim. key.

 

by: cbaronPosted on 2006-08-11 at 02:16:28ID: 17294656

I don't have an alternative; I must use SQL server as it's our company standard.

It looks like there is no simple solution to this problem so I have decided to change the way my app works and instead of using an autoincrement field I'll just store a number elsewhere and increment manually in the app each time I write a record.  It's not as elegant as getting the server to do it but it will solve the problem.

 

by: LimbeckPosted on 2006-08-11 at 02:22:34ID: 17294681

well use a generator on the server if you can, that way you are sure that the id's you use are unique

 

by: geobulPosted on 2006-08-11 at 14:22:47ID: 17299457

Hi,

Read %%IDENTITY variable from your MS SQL server just after the insert/append using a SP or query (select) in the same session. It gives you the last autoincrement value generated by the server (in the terms of your session, of course).

Regards, Geo

 

by: geobulPosted on 2006-08-11 at 14:25:18ID: 17299471

It should be @@IDENTITY, sorry for the mistake.

 

by: cbaronPosted on 2006-08-14 at 02:16:28ID: 17308786

As a test I filled out my tables to the size we expect in a year's time ... and now I know what they mean about Serverside cursors being inefficient!  I gave up waiting after my app spent 5 minutes flogging the SQL server just starting up with a few Serverside cursors!  I changed to clientside cursors and although it took a while to start (10 to 15 seconds) it was then useable.

I've used the requery method on these large tables and although it's not fast it's just about acceptable, so I'm giving the points to kretzschmar.

It's not the simple solution I was looking for but it looks like the best I'm going to get and I need to move on with the app now.  Thanks for all your suggestiong guys.

Chris

 

by: geobulPosted on 2006-08-14 at 07:43:07ID: 17310494

Hi,

You haven't even tried to read the value of @@IDENTITY variable, right? Just try and you'll see how useful it is.

Regards, Geo

 

by: cbaronPosted on 2006-08-16 at 02:47:46ID: 17324765

Geo,

I have tried reading the @@IDENTITY and it doesn't work!  It always returns nothing.  I've tried it by setting up a TADOQuery linked to the same TADOConnection. the queries SQL reads "select @@identity as ident".  The query is set active immediately after the connection is enabled.  I've then created the following function;

Function TIWUserSession.IdentityQuery() : String;
begin
  { Query server for latest ID }
  IdentQuery.Requery();
  IdentityQuery := IdentQueryident.AsString;
end;

One would then expect after a TADOTable.post a call to IdentityQuery() would return the identity from the table.  It actually returns null.

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...