Can a constraint check two different tables for the existence of a parent item?

My database has a table Message, and a table MessageReply.
Each MessageReply has a ParentID and a MessageReplyType (Message, or Reply).
When the MessageReplyType is a message, I would like to ensure the MessageReply.ParentID (MessageID) exists in the Message table.
And when the MessageReplyType is a reply, I need to ensure the MessageReply.ParentID (MessageID) exists in the MessageReply table. 
I am doing this through client code, but I would like the database to enforce this to protect the database from well intentioned programmers like me.
Can it be done?
Thank you

There is a problem with your function and the whole idea of using a check constraint and a function to simulate a foreign key constraint is problematic.
The problem with your function is when you do a statement like
Set @ReturnValue = (Select MessageID From MessageReply Where MessageID = @ParentID);
then if that row does not exist in MessageReply, @ReturnValue is set to NULL.  Then you are returning that NULL from the function and using the check constraint to test whether or not that returned NULL is > 0.  Comparing NULL to a value does
not give you TRUE and it does not give you FALSE, instead you get a logical value called UNKNOWN.  Check constraints only reject a row if the resulting value is FALSE.  It allows the Insert or Update if the logical value is either TRUE or UNKNOWN. 
So even if the parent row does not exist, that check constraint will allow the new row to be inserted.
Second, using a function and check constraint to simulate a foreign key constraint always has a problem.  If you go with that (and you have written the function and constraint correctly) and you attempt to insert a row with a bad ParentID so that the
ParentID does not exist in the appropriate table, you will get a check constraint error and the insert will be rejected.  That is good.  However, suppose you successfully insert a row in MessageReply. For example you insert a row in Message with
MessageID = 1 and then insert a row in MessageReply with ParentID = 1 and ReplyType = 1.  That will work fine as it should.  But now suppose someone deletes the row in Message with MessageID = 1.  That delete won't fire the check constraint. 
So it will allow the delete of the row in Message and now you have a row in MessageReply which doesn't have a parent.
If you want a method that will work completely, you could do that by 1) doing all of your updates to those tables thought stored procedure(s) that check the data to be sure it is valid before inserting/updating/deleting, or 2) writing trigger(s) on both
Message and MessageReply to make sure that any changes are valid, or 3) add computed columns to the MessageReply table so that you can write foreign key constraints. 
I would go with method 3.  That would look something like changing your MessageReply table to look something like
Create Table Message(MessageID int Primary Key
-- other columns as needed
Create Table MessageReply(MessageID int Primary Key
,ParentID int Not Null
,MessageReplyType int Not Null Check (MessageReplyType In (1,2))
,ParentMessageID As Case When MessageReplyType = 1 Then ParentID Else Null End Persisted
,ParentMessageReplyID As Case When MessageReplyType = 2 Then ParentID Else Null End Persisted
-- other columns as needed
Alter Table MessageReply
add constraint chk_MessageParentExists Foreign Key(ParentMessageID) References Message;
Alter Table MessageReply
add constraint chk_MessageReplyParentExists Foreign Key(ParentMessageReplyID) References MessageReply;
Tom

Similar Messages

  • HT4993 on my computer there are two different accounts for the itunes store but my brothers account keeps syncing in on my iphone instead of my own account how do i get his account off of my phone and add my own back?

    on my computer there are two different accounts for the itunes store but my brothers account keeps syncing in on my iphone instead of my own account how do i get his account off of my phone and add my own back?

    Not a good idead to share IDs
    Read http://macmost.com/setting-up-multiple-ios-devices-for-messages-and-facetime.htm l
    Read Sharing an Apple ID with your Family
    Does your father have a recent backup of his phone?  If so restore his phone from that.  Please not that everythign created on th ephone since the backup was made will be lost

  • How can I interact between two different frames in the same indesign template as well as from one template to another.

    I am looking for the best way (or any way) to interact between two different frames in the same indesign template as well as from one template to another. It's for a DPS app which needs to carry some button initiated data from one page to another and then present it in a table.

    There is no simple way to do it, as itunes wont let you use it on another computer without wiping the contents first.
    However if you really want to transfer songs to another computer then you could try this;
    * make sure that your ipod is accessible as a disk drive (ipod options)
    * when you plug your ipod into the computer you want to transfer to make sure you select "no" or "cancel" when it asks to wipe the contents. Leave the ipod connected and quit from itunes.
    * go to "my computer" and access the ipod directly. You probably have to select "view hidden files" from windows. You will see a lot of folders with odd names like ZX838aff with similar named files inside.
    * copy these files to a folder on your computers hardrive. Now remove the ipod and start itunes.
    * import the files from the folder you made in the last step.
    * Now your music is on itunes, but with unrecogisable names.
    This is the only way I have found to do it, but there may be another way, say with an application to do the hard work for you.
    Generic homebuild PC Windows XP
    Generic homebuild PC   Windows XP  

  • Can Time Machine do two different backups for me?

    I've got Time Machine nicely backing up my main HD to a 1TB external ESATA drive. It does it's thing. That backup on the external drive shares space with my main iTunes library which is now about 280 GB and growing. Would Time Machine also be able to make a backup of that iTunes library to another HD that I would buy for the purpose?
    TM was so easy to set up and use I don't remember the choices. That wonderful bonus from Apple brings me here to ask this question.
    Thanks all.

    You could do it, but it would take some work. First, as I think you currently have things set up, TM backs the main HD to the 1TB drive.
    To perform an independent backup of the itunes folder on the 1Tb drive, you must exclude the main HD, and the TM folder that holds the main HD backup. Then "change disk" (TM preferences) to the new HD you will buy. Do a manual backup.
    When done, undo all these settings and go back to the setting of backing up the main HD to the 1TB disk (undo the excludes I mention earlier). Now you can go back to "normal" backups of the system drive.
    When you are ready to do another backup of the itunes folder, repeat my second paragraph. Like I said - it's a bit of work. You can't have TM do both sets of backups automatically, you must do the manual stuff each time.

  • Two different Resultsets for the same query (running at the same time)

    I am using the Thin Driver for Oracle 8.1.6. I am invoking queries in multithreading mode (each thread has his own connection to the oracle DB). If i am invoking the same SQL-Statement in two different threads nearly at the same time, only the ResultSet of the first query is complete. The ResultSet of the second query is not complete (the number of tuples differs each time I run the program). Principally the two ResultSets should be the same (no changes are done at the same time in the DB), but they are not.
    Anybody knows this problem and knows how to solve it? Principally read accesses on DBs should not make such trouble ...
    I hope anybody can help me.

    Pranav,
    As this BADI is having option checked 'Multiple use'. You can implement multiple implementations.
    You need not to deactivate the existing implementation.
    Reddy

  • How can I log into two differant accounts at the same time in two windows without the second window affecting the first.

    I'm trying to log into two facebook accounts at the same time in differant windows. When ever I log into the second account in the second window it changes the login in the first window. When I hit home or any other link the first window account has been logged out and logged into the second window account. I tried installing a second copy of firefox in a differant folder that the first but it seems to use all the files of the first installation. If I can get 2 toatally seperated instalations that don't rely on the same history, cookies, cache, etc I belive that will solve my problem. Please help.
    == User Agent ==
    Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; OfficeLiveConnector.1.4; OfficeLivePatch.1.3)

    Nah, that won't work. Facebook has a feature that gets your IP Address, so as soon as you sign into one on the same computer, it changes the other login for safety purposes (say, someone was on a public library PC. They forgot to log out. Someone else logs in, and it automatically logs them out). You'll need 2 computers to do that.

  • Time Capsule--can I back up Two different Laptops on the Time Capsule?

    It's just about that easy. I just got the Time Capsule. I backed up my MacBook Pro. Now I'd like to use the same Time Capsule to back up my wife's MacBook. Can this be done? If so, how? I keep getting the failed message from the Time Machine Backup.
    Thanks for the help.
    Dave

    No question that it can be done. I just got a new MacBook a couple of weeks ago and I am backing it up to our TC alongside my son who has been using it since last Sept. with his MacBook. There was no problem setting it up. I just clicked on TimeMachine in the Dock and it asked me where I wanted to back my files up to. The only choice was the existing Time Capsule. I clicked and away it went. I took the advice of others and connected my Mac directly to the TC for the initial backup instead of relying on the wireless. It only took a couple of hours.
    What specific error do you get?

  • Creating Two Different Designs for the same site

    I already have a website (www.ernestbuckley) but would like to design an alternate site with the same name and from time to time, just switch between the two for variety. Can this be done? Will I lose any data when I switch back and forth?

    Apnewbie's suggestion is right on track! You already have your domain name ( http://www.ernestbuckley.com ) that you forward to:
    http://web.mac.com/ernestbuckley/iWeb/ernestbuckley/Welcome.html
    If you made another parallel site with the different design and called it "ernest2", all you would have to do is to switch your forwarding to:
    http://web.mac.com/ernestbuckley/iWeb/ernest2/
    You can continue to edit both sites and when you want to switch sites, just change your forwarding again to the other address.
    BTW, if you want to start another site, you might consider using a program called "iWebSites" to help you manage your sites in separate Domain files. That way you keep them completely separate from one another and maintain the ability to edit and publish them independently of one another. Here is the URL for more info...
    http://mistergregg.com/cocoadrillosoftware/
    Let me know if you any other questions...

  • HT2534 How can i download from two different store with the same account?

    I live in both countries but my credit card is registered in a french bank, therefore it is not recognised by the Aussie store on itunes. There are apps or music i want to get form the Aussie store as well as music and other apps from the french one...
    Is it possible to have two stores under the same account????? I wish apple could fix this, which could result in more spending as you can buy from different store!

    Wait 90 days
    Why would you start a new account?  Why not just correct the original account?

  • HT201272 How can i download from two different accounts without the 90 day rule?

    I have two Apple IDs because I had lost the other one and made a new one. I recently bought a new computer and went I also found my old password for my first ID. I downloaded my purchased from the first one and now it is telling me I have to wait 90 days to download from a different account. What do I do?

    Wait 90 days
    Why would you start a new account?  Why not just correct the original account?

  • Is there a way to set two different settings for the backlight?

    I was wondering if there is a way for me to set the backlight to always on when watching videos on my 5G 30 gig iPod and off when doing anything else?
    Or do I have to manually go in and change the setting everytime?

    The backlight will always be on when watching videos. This is automatic, regardless of the setting.
    btabz

  • [JAXB] Several different prefixes for the same namespace

    Hi!
    I have generated some code from 2 schemas using JAXB. One of them (the main) defines some elements and the other one defines values for those elements. Then, when runring my code, I get an XML document with elements from the main schema an elements from the other one. However, elements from the second schema are qualified with different names. That is:
    <party>
    <ns3:uid xmlns:ns3="http:/schema1.com/schema1">CN=User1 - RSA/RSA,OU=IAIK,O=TU Graz,C=AT</ns3:uid>
    <ns4:role xmlns:ns4="http:/schema1.com/schema1">client</ns4:role>
    </party>
    As you can see, I get two different prefixes for the same namespace.
    Could you be so kind as to tell me if there is a way of getting only one prefix for each namespace, please? Do I have to modify JAXB compiler's properties???
    Thanks a lot in advance.

    No, I don't know how to do that. I also don't think it should matter. Are these multiple prefixes causing you any problems other than offending against Occam's Razor?

  • How can I link specific cells in two different speadsheets so the data from a specific cell in spreadsheet A automatically updates in a specific cell in spreadsheet B. It works in Xcel- Any ideas?

    How can I link specific cells in two different tables so the data from a specific cell in table A automatically updates in a specific cell in table B? It works in Xcel- Any ideas?

    (1) your title ask the way to link different spreadsheets.
    In Numberland, a spreadsheet is an entire document.
    There is no way to link different documents.
    (2) in the message, you ask the way to link different tables.
    This feature is available and is described in iWork Formulas and Functions User Guide (which is available for free from the Help menu).
    Getting the info just requires a simple search in this available resource !
    Yvan KOENIG (VALLAURIS, France) 14 mai 2011 10:37:50

  • Sum two different columns from two different tables

    Can you select and sum two different columns, from two different tables in the same sql statement?
    i.e.
    table1
    Item----OnHand_Qty
    A--------10
    A--------15
    B--------10
    B--------10
    C--------20
    table2
    Item----Trx_Qty
    A--------2
    A--------4
    A--------6
    B--------1
    B--------1
    C--------4
    I'm looking for the following results from a query
    Item----Sum(Onhand_Qty)---Sum(Trx_Qty)
    A--------25

    Like this?
    SQL> create table table1 (item,onhand_qty)
      2  as
      3  select 'A', 10 from dual union all
      4  select 'A', 15 from dual union all
      5  select 'B', 10 from dual union all
      6  select 'B', 10 from dual union all
      7  select 'C', 20 from dual union all
      8  select 'D', 30 from dual
      9  /
    Tabel is aangemaakt.
    SQL> create table table2 (item, trx_qty)
      2  as
      3  select 'A', 2 from dual union all
      4  select 'A', 4 from dual union all
      5  select 'A', 6 from dual union all
      6  select 'B', 1 from dual union all
      7  select 'B', 1 from dual union all
      8  select 'C', 4 from dual union all
      9  select 'E', 3 from dual
    10  /
    Tabel is aangemaakt.
    SQL> select nvl(t1.item,t2.item) item
      2       , t1.sum_onhand_qty
      3       , t2.sum_trx_qty
      4    from ( select item, sum(onhand_qty) sum_onhand_qty
      5             from table1
      6            group by item
      7         ) t1
      8         full outer join
      9         ( select item, sum(trx_qty) sum_trx_qty
    10             from table2
    11            group by item
    12         ) t2
    13         on (t1.item = t2.item)
    14  /
    I SUM_ONHAND_QTY SUM_TRX_QTY
    A             25          12
    B             20           2
    C             20           4
    E                          3
    D             30
    5 rijen zijn geselecteerd.Regards,
    Rob.

  • Is it possible to have  2 different account for the developer program?

    Dear All,
    I would like to Know if I can have two different account for the Developer program?
    I am signed in as developer for my company, but I would also like to have my private account to pubblish my private stuff.
    DO you Know if it's possible?

    Those should be considered two separate/different accounts, so yes, you can do that. It's just money at that point

Maybe you are looking for