简体   繁体   English

无法在SQL Server中同时将数据插入到两个相关表中

[英]Unable to Insert data into two related tables simultaneously in sql server

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: 我正在使用C#.net,winforms和sql server 2012编写程序,我的表单之一用于向数据库中添加新产品,产品信息存储在两个表中.'prodcutName'和'id'是一个标识列存储在此表中:

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. 在我的表单中,我有三个texbox,可让用户添加产品中使用的材料名称,重量和色度。 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. 关于身份列,首先我应该获取产品的ID,然后根据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. 请帮助我弄清楚如何根据身份列使用T-SQL将数据同时插入两个表中。

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. 您可以直接在代码中或在存储过程中使用硬编码查询来执行此操作,这可能是更好的主意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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