Solved

Integrity: How can I enforce at least one child record

Posted on 2006-10-26
19
354 Views
Last Modified: 2008-02-01
That question has probably been asked before, but I haven't found a trace.

I have the following:

    create table parent (
        code varchar(100) not null primary key);

    create table child (
        parentCode varchar(100) not null foreign key references parent(code),
        code varchar(100) not null);

How can I make sure a record in 'parent' can't exist without at least one record in 'child' ? I can put a trigger for the deletion of 'child', that's easy, but what about insertions ?
I.e.
    insert into parent values ('a')

should fail, but

    begin tran;
    insert into parent values ('a');
    insert into child values ('a', 'a');
    commit tran;

should work.

This seems like such a standard issue, I'm surprised it's not built in FOREIGN KEY constraints already (or I haven't found it !!).
I'm using SQL Server 2005.
One solution I can think of is postponing the 'real' validation until commit-time (à la Oracle's 'deferred'), but I don't know how !

Thanks a lot.
0
Comment
Question by:dbman666
  • 5
  • 4
  • 3
  • +2
19 Comments
 
LVL 69

Expert Comment

by:Scott Pletcher
ID: 17814853
You can create a FK constraint that will prevent a child from being inserted w/o a parent, but not vice versa.

In particular, there is *NO* way to do this in SQL Server:
>> I.e.
    insert into parent values ('a')
should fail, but
    begin tran;
    insert into parent values ('a');
    insert into child values ('a', 'a');
    commit tran;
should work. <<

There is no deferred resolution in SQL Server, so this cannot be done.
0
 
LVL 11

Expert Comment

by:rw3admin
ID: 17815102
I am sure you can write a 'for insert' and 'for delete' triggers on parent that will do the job for you

rw3admin
0
 
LVL 69

Expert Comment

by:Scott Pletcher
ID: 17815149
I'd love to see a sample, because I don't see how it could possibly be done.
0
Comprehensive Backup Solutions for Microsoft

Acronis protects the complete Microsoft technology stack: Windows Server, Windows PC, laptop and Surface data; Microsoft business applications; Microsoft Hyper-V; Azure VMs; Microsoft Windows Server 2016; Microsoft Exchange 2016 and SQL Server 2016.

 
LVL 143

Expert Comment

by:Guy Hengel [angelIII / a3]
ID: 17815226
I have to agree basically with scottpletcher that you cannot really do that.

actually, the FOREIGN KEY constraint is to ensure that there is a parent row for the child record, it's not about a parent row to fail when there is no child record.

however, just as an idea, you could solve your requirement like this:

INSERT TRIGGER on the parent table, which would automatically insert a "dummy" child record on the child table
INSERT TRIGGER on the child table, that would automatically delete the "dummy" record for the related parent record
DELETE TRIGGER on the child table, that would rollback (+RAISERROR) the delete if the delete was deleting the last child record for that parent

0
 
LVL 69

Expert Comment

by:Scott Pletcher
ID: 17815262
But what if no insert on the child table ever came?  You would have allowed an insert on the parent w/o an insert on the child.
0
 
LVL 11

Expert Comment

by:rw3admin
ID: 17815273
yes AngelIII thats what I am saying, a for insert will automatically insert a record in a child and in for delete user can write a code to first query 'deleted' table and delete records from child before deleting from parent, a for delete can also be a instead of delete but with same logic

rw3admin
0
 
LVL 11

Expert Comment

by:rw3admin
ID: 17815306
oh and yea angelIII is right we would need a 'instead of delete' on child table as well.

rw3admin
0
 

Author Comment

by:dbman666
ID: 17815376
I wanted to avoid writing stored procs for that, but it seems I am doomed !

Is there any way, using the new C# triggers in SQL Server 2005, to trap the 'commit' and actually do some work there ??
0
 
LVL 69

Expert Comment

by:Scott Pletcher
ID: 17815395
But then you're not enforcing a rule you're just dodging around it.  Inserting a dummy row yourself is NOT the same as insuring that an actual data row already exists in the table **or has been inserted in the same batch** -- that part I don't see *ANY WAY* to do.
0
 
LVL 39

Expert Comment

by:appari
ID: 17815476

how about creating a view joining parent and child tables disable insert permission on parent and child tables and allow inserting data in to the view instead of tables directly. Write an instead of insert trigger on the view to insert data in to parent and child tables.
0
 
LVL 11

Accepted Solution

by:
rw3admin earned 84 total points
ID: 17815482
ok if we step back and take a look at it, its basically a classic case of chicken and egg, what came first... ofcourse we all know a dirty joke around the same theme but thats outside the scope of discussion here, and I will be kicked out of EE by Scott.
according to dbman666
>>insert into parent values ('a')
    should fail, but

    begin tran;
    insert into parent values ('a');
    insert into child values ('a', 'a');
    commit tran;
    should work.<<


then I would suggest allow data manipulation in these tables ONLY through application, and write your logic in that application, ofcourse you WILL end up writing some sort of triggers on parent and child tables to only allow your application... :)
0
 
LVL 39

Expert Comment

by:appari
ID: 17815502

i think you should allow insert on child table and disable inserts on parent table.
0
 

Author Comment

by:dbman666
ID: 17815541
appari: That's a new approach. Interesting.

rw3admin: Chicken and egg in a way, yes. But if you delay validation until commit-time, it becomes trivial. That's why I'm looking at a way to trap the start and end of the commit ! I know traces do it, but it's asynchronous, so it doesn't cut it.
0
 
LVL 69

Assisted Solution

by:Scott Pletcher
Scott Pletcher earned 83 total points
ID: 17815558
>> But if you delay validation until commit-time <<

"Ay, there's the rub" as Shakespeare might say -- there's no way to do that in SQL Server.
0
 
LVL 39

Assisted Solution

by:appari
appari earned 83 total points
ID: 17815566
>>appari: That's a new approach. Interesting.
why dont you give it a try?
do you want sample code? I am leaving for work now. i can respond may be  after 1.5 hours. someone else can provide sample based on my idea or after 1.5 hours i will post sample code.
0
 

Author Comment

by:dbman666
ID: 17815578
No that's fine. I just want to think of the pros and cons. Thanks.
0

Featured Post

U.S. Department of Agriculture and Acronis Access

With the new era of mobile computing, smartphones and tablets, wireless communications and cloud services, the USDA sought to take advantage of a mobilized workforce and the blurring lines between personal and corporate computing resources.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

When you hear the word proxy, you may become apprehensive. This article will help you to understand Proxy and when it is useful. Let's talk Proxy for SQL Server. (Not in terms of Internet access.) Typically, you'll run into this type of problem w…
Introduction SQL Server Integration Services can read XML files, that’s known by every BI developer.  (If you didn’t, don’t worry, I’m aiming this article at newcomers as well.) But how far can you go?  When does the XML Source component become …
This video shows how to set up a shell script to accept a positional parameter when called, pass that to a SQL script, accept the output from the statement back and then manipulate it in the Shell.
Via a live example, show how to setup several different housekeeping processes for a SQL Server.

839 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question