Saturday, February 25, 2012

Master-Details Insert

Master table (tlbProduct) having productID as Primary key and
which acts as reference key for table (tlbCategory).
Fields for tlbProduct are productID,productName
Fields for tlbCategort are productID,CategoryID(primary key),CategoryName,Prize
both productID,CategoryID are autoincrementing.
but when i write two inserts simultaneously as follows
insert into tlbProduct(productName)values(@.productName)
insert into tlbCategory(CategoryName,Prize) using sqldatasource
I get the error that ProductID value is null which is not provided
But (productId in both is autoincremented) and relationship is there in both tables
How to resolve this problem without adding ProductID in second Insert
?
SWati

Hello,

to create a relationship between two tables in sql, you need to match the primary key and the foreign key. So after the first insert, you would need to find out the id that was inserted by the database for the product (you can do this with SELECT SCOPE_IDENTITY()), and then you need to use this id in the second insert statement. If the keys don't match and the database is trying to enforce a relationship between the tables, you will get an error.

Good luck

No comments:

Post a Comment