[英]SQL-SERVER Procedure How do i insert row one table then insert row into another table link to another table as foreign key
For sql-server How can I insert a SKU row into table SKU_DATA
, then insert the SKU into INVENTORY
table with all branches and Quantity on hand=2 and Quantityonhand=0.对于 sql-server 如何将 SKU 行插入表
SKU_DATA
,然后将 SKU 插入到INVENTORY
表中,所有分支和 Quantity on hand=2 和 Quantityonhand=0。
I need to insert a SKU item into SKUDATA and correspond row in inventory table for all existing branches Quantityonhand=2 and Quantityonhand = 0.我需要在 SKUDATA 中插入一个 SKU 项目,并在库存表中为所有现有分支 Quantityonhand=2 和 Quantityonhand = 0 对应行。
Please help Thanks请帮忙谢谢
BRANCH分支
name varchar (30) not NULL,
managerNum INT NOT NULL,
SKU_DATA 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 ,
INVENTORY存货
SKU Int NOT NULL,
branch varchar (30) NOT NULL ,
quantityOnHand Int NOT NUll ,
quantityOnOrder Int NOT NUll ,
Procedure:程序:
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
There are two problems here: first, how to get the generated IDENTITY value for the newly inserted row into SKU_DATA table, and second, how to one row into INVENTORY table for each branch.这里有两个问题:第一,如何将新插入的行的生成 IDENTITY 值获取到 SKU_DATA 表中,第二,如何将每个分支的一行放入 INVENTORY 表中。
If you're inserting only a single row into SKU_DATA, then use the scope_identity() function (never use the @@IDENTITY!).如果您只向 SKU_DATA 中插入一行,则使用 scope_identity() 函数(切勿使用 @@IDENTITY!)。 Like this:
像这样:
INSERT INTO dbo.SKU_DATA (description, department, sellingPrice)
VALUES (@description, @department, @sellingPrice);
set @SKU = scope_identity()
Then you do insert into INVENTORY by selecting from BRANCH table:然后你通过从 BRANCH 表中选择插入到 INVENTORY 中:
insert dbo.INVENTORY (SKU, branch, quantityOnHand, quantityOnOrder)
select @SKU, b.name, 2, 0
from dbo.Branch b
Hope you can work the complete solution out from this.希望你能从中找到完整的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.