如何在更多表相关时执行插入

时间:2014-11-04 13:18:33

标签: sql-server database database-design

我在数据库中创建了3个表 tbProducts,tbLineOfAuthority,tbProductLineOfAuthority

tbProducts包含以下领域

  • ProductId(PK)身份
  • 产品名称
  • 产品描述

tbLineOfAuthority包含以下领域

  • LineOfAuthorityId(PK)身份
  • LineOfAuthorityName

tbProductLineOfAuthority包含以下领域

  • ProductLineOfAuthorityId(PK)
  • ProductId(FK)
  • LineOfAuthority(FK)

现在tbLineOfAuthority包含以下数据

  • 1 - 电子保险
  • 2 - Credit
  • 3 - Casuality
  • 4 - 借记

在前端,我有以下场地的表格

  • 产品名称(文本框)
  • 产品说明(MultiLine Textbox)
  • 权力线(所有权力机构的复选框)

如果用户使用以下数据填写上述表格

  • “手机”作为产品名称
  • “我们提供优质手机......”作为产品说明
  • “临时性”作为权限(用户将选中“临时性”复选框)

现在我的问题如何根据上述要求在ms sql server中执行插入操作,如果有两个以上的表与外键相关。

我已将存储过程编写为

        Insert into tbProduct(ProductName, ProductDescription)
        Values(@ProductName, @ProductDescription)

我很困惑,我将如何编写一个自动更新tbProductLineOfAuthority(ProductId和LineOfAuthorityId)的存储过程

当用户从复选框中选择多个权限时,会发生什么 在表格中,我的意思是如果用户将选择临时性,信用卡和借记卡。

请帮帮我!!!

1 个答案:

答案 0 :(得分:0)

为此,您必须为tbProductstbLineOfAuthority表传递3个参数,如下所示。插入记录后,使用SCOPE_IDENTITY()获取新生成的IDENTITY值[考虑到这两个表中的PK列均为IDENTITY列]。

create procedure sp_insert_ops (@ProductName, 
@ProductDescription,
@tbLineOfAuthority)
as
begin

declare @tbProduct_ID INT;

Insert into tbProduct(ProductName, ProductDescription)
Values(@ProductName, @ProductDescription);

SELECT @tbProduct_ID = SCOPE_IDENTITY();    

INSERT INTO tbProductLineOfAuthority(ProductId, LineOfAuthority)   
VALUES(@tbProduct_ID, NULL);

end