简体   繁体   中英

Insert into parent-child tables in SQL Server

I have multiple level parent-child tables(GrandParent, Parent and Child, all many to one relation, one parent has multiple children, all children have one parent). Each has auto identity keys. Using C# and stored procedure, how to insert to them with foreign key constrains? For example, the data to be inserted include multiple grand parents, each grad parent has multiple parents and each parent multiple children.

Sample data:

campus <- building <- office

Adding a few campuses and associated buildings/offices.

You can use the SCOPE_IDENTITY() function to retrieve the last inserted auto-increment ID:

DECLARE @new_parent_id INT

INSERT INTO MyParent(...) VALUES(...) -- your new parent data

SELECT @new_parent_id = SCOPE_IDENTITY()

INSERT INTO MyChild(parent_id, ...) VALUES(@new_parent_id, ...)

Is this what you mean?

EDIT :

You can indeed pass in all your data at once with ADO.NET and SQL Server 2008 using Table Valued Parameters:

http://msdn.microsoft.com/en-us/library/bb675163.aspx

You could pass in your parent and child data as two tables to your stored procedure, then use a cursor to loop through your parents, inserting one, getting the generated ID, then inserting all its children before proceeding to the next parent.

This would probably be the most efficient solution, potentially requiring only a single call to the database, and if you have a large amount of data to insert, or if you think you can reuse this SP in other places in you solution, then this might be the way to go.

However, I think that inserting the records one-by-one from the client application is a cleaner and certainly a simpler way of achieving what you want.

I think what you really need here is a database trigger . You cannot enforce custom logic except for direct table referential integrity in a constraint. If you want custom logic (must have 2 parents, etc), then you will have to use a database trigger.

You can do something like this (pseudo code):

BEFORE INSERT
IF INSERT CAUSES MORE THAN 2 PARENTS
    DO NOT ALLOW INSERT
ELSE
    ALLOW INSERT

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM