繁体   English   中英

SQL-SERVER 程序如何在一个表中插入行,然后将行插入到另一个表中作为外键链接到另一个表

[英]SQL-SERVER Procedure How do i insert row one table then insert row into another table link to another table as foreign key

数据库图

对于 sql-server 如何将 SKU 行插入表SKU_DATA ,然后将 SKU 插入到INVENTORY表中,所有分支和 Quantity on hand=2 和 Quantityonhand=0。

我需要在 SKUDATA 中插入一个 SKU 项目,并在库存表中为所有现有分支 Quantityonhand=2 和 Quantityonhand = 0 对应行。

请帮忙谢谢

分支

name varchar (30) not NULL,
managerNum INT NOT NULL,

SKU_DATA

SKU Int NOT NULL  IDENTITY (1000,1),
description varchar (40) NOT NULL  UNIQUE,
department varchar(30) NOT NULL default 'Home Entertainment',
sellingPrice numeric (7,2) NOT NULL ,

存货

SKU Int NOT NULL,
branch varchar (30) NOT NULL ,
quantityOnHand Int NOT NUll ,
quantityOnOrder Int NOT NUll ,

程序:

Create procedure InsertNewSkuWithInventory
    @description varchar (40),
    @department varchar(30),
    @sellingPrice numeric (7,2),
AS
    Declare @rowcount as int
    Declare @SKU as int
    Declare @branch as varchar(30)

    Select @rowcount = COUNT(*)
    from dbo.SKU_DATA
    Where description = @description 
      And department = @department 
      And sellingPrice = @sellingPrice; 

BEGIN
    INSERT INTO  dbo.SKU_DATA (description, department, sellingPrice)
    VALUES (@description, @department, @sellingPrice);

    Select @SKU =SKU
    From dbo.SKU_DATA
    Where description = @description 
      And department = @department 
      And sellingPrice = @sellingPrice;

    DECLARE SKUCursor CURSOR FOR
       SET @branch = @@IDENTITY

       Select SKU
       From dbo.inventory
       Where 

   CLOSE SKUCursor
   DEALLOCATE SKUCursor
END

这里有两个问题:第一,如何将新插入的行的生成 IDENTITY 值获取到 SKU_DATA 表中,第二,如何将每个分支的一行放入 INVENTORY 表中。

如果您只向 SKU_DATA 中插入一行,则使用 scope_identity() 函数(切勿使用 @@IDENTITY!)。 像这样:

INSERT INTO  dbo.SKU_DATA (description, department, sellingPrice)
VALUES (@description, @department, @sellingPrice);
set @SKU = scope_identity()

然后你通过从 BRANCH 表中选择插入到 INVENTORY 中:

insert dbo.INVENTORY (SKU, branch, quantityOnHand, quantityOnOrder)
select @SKU, b.name, 2, 0
from dbo.Branch b

希望你能从中找到完整的解决方案。

暂无
暂无

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

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