Topic: Calling on SQL Experts

Not sure if an SQL statement can be created to do what I want to do or maybe some other way, but here is the scenario. I have a parent / child table relationship. I want to take a few fields from a single record in the parent table and insert a new record in another separate table. Along with that I want to bring over the child records of the first parent and insert them into a child table of the second parent table where I just inserted the parent record. Obviously the related Id in the child records need to be set to the newly created parent record Id.  Any help would be appreciated.

Re: Calling on SQL Experts

This does not look very complicated, do you have a project or a picture of your table structures?

Re: Calling on SQL Experts

I agree with Tcoton. It does not look that complicated.


Do you have a database and a bit more details so we can try ?

I'm a very good housekeeper !
Each time I get a divorce, I keep the house

Zaza Gabor

Re: Calling on SQL Experts

Yes you are both correct. It's definitely not complicated in theory. I just don't know how to structure it in an SQL statement. The parent copy I'm sure can be done using an Insert....select type statement, but bringing over the child records and assigning them to the newly inserted parent record is my hang-up.
.

Re: Calling on SQL Experts

Hello ehwagner,


I'm not completely sure I understood want you want to achieve, so here is what I think :


  • You have a MAIN table with data in it

  • You have a CHILD table with data in it AND reference to IDs in the main table

  • You want to SELECT some info in MAIN table, some related info in CHILD table and put them together in a third table we will call MIX table


I see two approches but :

  • beware of typos, I did not check this code, I just wrote it on the fly

  • this of course is usable only if I understood your question correctly smile


FIRST APPROACH :


If you query both tables at the same time, you can assign values to variables in one procedure and INSERT them in the MIX table in one go.


procedure Form1_Button1_OnClick (Sender: string; var Cancel: boolean);
var
    ResultMain: TDataSet; //Best way (I know...)to save multiple query results in one variable
    ResultChild : TDataSet; //Same thing but for the CHILD table

    id, name, phone, email, salary, bonus : String; //All the variables from both queries to save in MIX table
begin
    SQLQuery('SELECT id, name, phone, email FROM main', ResultMain);
    begin
        id := ResultMain.FieldByName('id').AsString;
        name := ResultMain.FieldByName('name').AsString;
        phone := ResultMain.FieldByName('phone').AsString;
        email := ResultMain.FieldByName('email').AsString;
    end;
    SQLQuery('SELECT salary, bonus FROM child WHERE id="'+id+'"', ResultChild); //The id is the key to your MAIN table
    begin
        salary := ResultChild.FieldByName('salary').AsString;
        bonus := ResultChild.FieldByName('bonus').AsString;
    end;

    SQLExecute('INSERT INTO mix(name, phone, email, salary, bonus) VALUES("'+name+'","'+phone+'","'+email+'","'+salary+'","'+bonus+'"');

    //Free the DataSets at the end
    ResultMain.Free;
    ResultChild.Free;
end;

SECOND APPROACH :


You do not query the MAIN and CHILD tables at the same time, so you can not INSERT in the MIX table in one GO.


The approach is the same, except that you will save data in two steps.


  • The first query will be an INSERT in the MIX tableand will automaticly generate an ID

  • The second query will be an UPDATE on the same record in the MIX table based on the same ID.

  • All you need for the UPDATE query is to find the ID of the INSERT query.


If it was the last operation (I don't know how your application is structured), then you can use either last_Insert_id('mix') or find the MAX(id) on the MIX table and do your update on that record id.


If the record is updated long after (with potentialy other records beeing done before), then you'll have to find the corresponding id based on other criteria before you can update.


Hope it helps.


This is only my approach of course, let's wait to see if others do it differently.


Cheers


Mathias

I'm a very good housekeeper !
Each time I get a divorce, I keep the house

Zaza Gabor

Re: Calling on SQL Experts

No, that's not what I'm looking to do. It's actually much easier than that. I thought I attached a picture of the DB schema, but it didn't come through. I'll try again.

Post's attachments

Attachment icon DB_Schema.JPG 127.25 kb, 456 downloads since 2015-12-11 

Re: Calling on SQL Experts

Just a question, what do you call a "single record"?

Re: Calling on SQL Experts

Hello EHWagner,

I found your problem far more interesting that what I'm supposed to be doing right now - LOL!  So......a couple of questions.

1.  Will the second parent table ALWAYS be populated (so it can be automatic) or just occasionally (so it would be a manual request)? 
In other words, if the first parent table has 1000 rows, will the second parent table also have 1000 rows or only a subset?
2.  Will this also be true between the first and second child tables?
The reason for the questions is that I can see a scenario where you don't always want the parent record to be copied but when you DO copy a parent record, you would ALWAYS want the child record(s) to be copied.
3.  Is this mainly to avoid having to enter data twice? 

I've mocked up a couple of quick solutions but would just like to know the answers to 1. 2. and 3. above before I see which is most suitable.

More generally, I'm intrigued as to why you need to create the additional parent / child tables in the first place.

Derek.

Re: Calling on SQL Experts

Tcoton question: single record means one table row.

Derek:
Question 1: Just occasionally (yes a manual request on a form button). Second parent will not have the same number of rows.

Question 2: Yes this is true for the child tables. And yes your scenario is correct. Don't always want a parent row copied, but when I do I always want the child records to be copied.

Question 3: Yes

Re: Calling on SQL Experts

ehwagner
Please download an example:

Post's attachments

Attachment icon Move records.zip 6.63 kb, 738 downloads since 2015-12-12 

Dmitry.

Re: Calling on SQL Experts

Hi EHWagner, Hi Dmitry,
I was having a look at your problem (which I think is actually more awkward than it initially appears!).
Creating inserts into the parent-copy and child-copy tables is relatively straightforward.  However, I believe Dmitry's example encounters the same two basic problems that I was concerned about.  They are:
1.  DELETIONS - if you delete a parent record and any child records, presumably you want to check if there are any associated parent and child records in the parent-copy and child-copy tables and have them also deleted.  Awkward because both pairs of tables are essentially 'stand-alone' and there is no record-id to relate them, so you are relying on users to also make the same deletions in the copy tables (which they all say they will do but we know they won't !!).
2.  CHANGES - if you change a parent record and any child records, presumably you want to check if there are any associated parent and child records  in the parent-copy and child-copy tables and have them also changed.  Again, awkward.  In Dmitry's example, a change to the parent and / or child record creates an INSERT in the parent copy table.  But to be fair, I think Dmitry's example is only currently intended to perform inserts. 
Taking the two problems together, you could find that, rather than the copies being sub-sets of the original tables, they will quickly start to hold completely different records.
Still, it's an interesting problem and I'm sure there's a way of doing it.  I'll let you know if I come up with anything.
Derek.

Re: Calling on SQL Experts

Sorry guys, I had family obligations over the weekend and couldn't reply sooner.

Dimitry - You got it. That's what I was looking for. Thank you. The key to it was Last_Insert_id(''). I was not aware of that function and couldn't find it anywhere. A question I have is what are the double quotes for inside the parentheses?  Also I noticed that you use Form1.GridParent1.sqlValue to get the Id field. I thought dbItemID was used to get the Id. So can they be used interchangeably?

Derek - Very astute on your part. Essentially the two sets do become more or less independent sets. Changes/Deletions on the "copied" version is quite alright. I will have controls on the original parent/child set to restrict changes/deletions once a set is copied. The original becomes a sort of historical record at that point.  Thank you for your observations and advice.

Re: Calling on SQL Experts

ehwagner wrote:

Dimitry - You got it. That's what I was looking for. Thank you. The key to it was Last_Insert_id(''). I was not aware of that function and couldn't find it anywhere. A question I have is what are the double quotes for inside the parentheses?

Do not pay attention, it's my fault, when I created this function


ehwagner wrote:

Also I noticed that you use Form1.GridParent1.sqlValue to get the Id field. I thought dbItemID was used to get the Id. So can they be used interchangeably?

sqlValue - returns the ID value (string) of the component for use in SQL statements.
dbItemID - returns the ID (integer) of the selected record in a table.


It is almost the same, but sqlValue useful for SQL queries.


Here you can find more details:
http://myvisualdatabase.com/help_en/scr … egrid.html

Dmitry.

Re: Calling on SQL Experts

Thank you Dimitry. That clears it up. I appreciate your quick response.

Re: Calling on SQL Experts

Evening EHWagner, Dmitry,
If you are going to keep changes and deletions in sync between the main tables and the copy tables manually, then most of the complications that I foresaw go away (thank goodness!).
To help keep things in sync, I think I'd perhaps use something like auto-generated 'counters' on the parent and child master tables that would then get copied across to the sub-set parent and child copy tables.   Matching on the 'counters', you could then use a simple tablegrid to highlight any inconsistencies between master and copy records (where one had been changed but the other hadn't, or where the number of child records belonging to a parent record was different between the master and the copy etc etc). 
It's quite unusual to purposely duplicate actual data in a database.  Can I ask what your requirement is to hold a PHYSICAL subset of the parent and child tables rather than just creating a VIRTUAL subset by using something like tablegrid filters?  Then all of the issues of inserts, duplicate data and keeping records in sync would disappear. 
Derek.

Re: Calling on SQL Experts

Derek,
I'll try to explain my reasoning for the separation.  It's a Lead/Client type scenario where the first table are sales leads and the data points are all around the sales process and the various stages of the process. The second table is just clients with a whole different set of data points. Yes you are right in that I could have stored everything in one table with some sort of status field to identify the lead versus a client. But I elected to separate them because the lead record basically becomes an historical record never to be changed or manipulated. It's used for statistical reporting around marketing and sales campaigns, etc. Also, not all leads become clients. The client table is a separate entity with a whole different structure. Quite frankly the only thing that is duplicated is the name, address, phone number and email and if those fields get changed on the client record, it's alright and preferred that the Lead record does not get updated. Everything else in the client record is completely different. Think of it this way, the Lead record basically is a snapshot of the client at the time they became a client. The Lead Id is being stored on the client record so a user could take a look at the lead information if desired, but usually is not necessary. There will be controls in place to disallow changes and deletions of the Lead record once the lead becomes a client. So there is really no synchronization necessary between the two tables. They are separate entities. I hope this clears up any confusion and my reasoning for the separate tables. It's all good. It's workable. :-)

Thanks for your input Derek and trying to lookout for me and keep me out of trouble.

Re: Calling on SQL Experts

Hi EHW,
That all makes perfect sense now.
I actually wrote something not too dissimilar many years ago and the concept of the 'leads' table is bizarre - it's virtually stand-alone with only a very loose relationship to any of the other tables in the database.
In the end, I think I 'cheated' by having just a 'clients' table but one of the rows in the 'clients' table was for a client called 'Leads' and if any of the queries against the 'Leads' client got firmed up, I then created it as a proper client and copied the data over.
It sounds like quite a large project you're undertaking.  Best of luck and keep us updated with how it's going - it looks pretty interesting.
Derek.

Re: Calling on SQL Experts

Derek,
At this point I'm only evaluating MVD. During the trial period I'm just building a rudimentary system to make sure I can do everything the design calls for. So far the software seems pretty strong.  I've been able to do most everything. The only drawback I see in the software so far is that too many properties need to be set using scripts. All properties should be done on the component design and scripts should only be needed to override those properties during run time. I understand that the new beta version has more properties which may take care of my issue. I have not tried it during the trial. I didn't want to mix my testing and evaluation on a beta version. The only other thing that bothers me is that the documentation is weak. The new help system is a huge step in the right direction. I believe it can be improved upon by defining ALL the functions available in MVD, ie String manipulations, date functions, etc, etc. I tried using things from Delphi Basics, but apparently there are discrepancies between Delphi and MVD. I'm definitely not a Pascal expert, but I've learned other languages fairly easily in the past if I have a good reference manual. I've learned some things from this forum, but if Dimitry ever got hit by a beer truck we might be in trouble. And it sounds like he is the author and developer of MVD. That scares me if something happened to him or he decides not to keep the software up-to-date any longer. Other than that, I think the software is pretty decent and easy to use.

Re: Calling on SQL Experts

+1 for all you said in your last message ehwagner! Most companies are reluctant in adopting a solution with weak/missing documentation especially in pharma industry where an audit can close your site...

Re: Calling on SQL Experts

Hi EHW,
Fully agree with your comments about MVD - good product, pretty robust but with so-so documentation, an over-reliance on scripts to do some pretty basic things and an over-reliance on Dmitry (which is not a criticism whatsoever - I think he's pretty amazing the way he helps people with so many questions in so many languages, as well as developing the product).
I had a quick look at the latest version (7 day trial) and a lot of the functions you previously had to script now seem available as object attributes but some areas are still a bit light (eg, certain tablegrid attributes, particularly when you consider how 'core' the tablegrids are to the way MVD works).
Having said all that, I've not found any software that comes close to it for it's balance of power, price, rapid development and relative ease of use.
Derek.

Re: Calling on SQL Experts

What is your problem addisonadolf00?