Reputation: 276
I'm writing a program using C#.net,winforms and sql server 2012, one of my forms is used to add a new product to database product information is stored into two tables.'prodcutName' and 'id' which is an identity column is stored in this table:
create table productType (
id int,
productName nvarchar(100),
constraint PK_productTpye_id_productName primary key (id),
constraint UQ_productType_productName unique (productName))
other product info stored in this table:
create table ingredients(
id int,
material nvarchar(100),
_weight float,
_percent float,
constraint PK_id_material_ingredients primary key (id,material),
constraint FK_id_ingredients foreign key (id) references productType (id)
on update cascade on delete cascade,
constraint FK_material_ingredients foreign key (material) references material (materialName)
on update cascade on delete cascade,
)
in my form i have three texboxes that let the user to add material name, weight and precent which is used in the product. regard to identity column first i should get the id of the product and then insert the rest of data to second table according to id. this is the diagram of my tables :
please help me to figure out how to insert data into both tables simultaneously using T-SQL according to identity column.
Upvotes: 0
Views: 255
Reputation:
You can't do this with a single query, but you can wrap multiple queries inside a transaction to simulate it. With a transaction, you can roll back the changes if the second query fails, so you either get both tables updated or none - you don't get a partial update that causes problems.
You can do that either with hard-coded queries directly in your code, or within a stored procedure, which would probably be the better idea.
Upvotes: 1