请帮我弄清楚如何使用复合主键插入新记录,复合主键由来自不同表的两个外键组成。 如果重要的话,我在C#,WPF工作。
我有三个表:Sales,SaleItem,Item。
CREATE TABLE [dbo].[Sales] (
[saleID] INT IDENTITY (1, 1) NOT NULL,
[saleTime] DATETIME NOT NULL,
[customerID] INT NULL,
[TIN] INT NOT NULL,
CONSTRAINT [PK_Sales] PRIMARY KEY CLUSTERED ([saleID] ASC),
CONSTRAINT [FK_Sales_Customers] FOREIGN KEY ([customerID]) REFERENCES [dbo].[Customers] ([customerID]),
CONSTRAINT [FK_Sales_Company] FOREIGN KEY ([TIN]) REFERENCES [dbo].[Company] ([TIN])
);
CREATE TABLE [dbo].[Item] (
[ItemSKU] INT IDENTITY (1, 1) NOT NULL,
[itemName] NVARCHAR (50) NOT NULL,
[volume] FLOAT (53) NOT NULL,
[measureUnit] NVARCHAR (50) NOT NULL,
[producer] NVARCHAR (50) NOT NULL,
[supplierID] INT NOT NULL,
[retailPrice] NUMERIC (18) NOT NULL,
CONSTRAINT [PK_Item] PRIMARY KEY CLUSTERED ([ItemSKU] ASC),
CONSTRAINT [FK_Item_Suppliers] FOREIGN KEY ([supplierID]) REFERENCES [dbo].[Suppliers] ([supplierID])
);
CREATE TABLE [dbo].[SaleItem] (
[saleID] INT IDENTITY (1, 1) NOT NULL,
[itemSKU] INT NOT NULL,
[quantity] INT NOT NULL,
CONSTRAINT [PK_SaleItem] PRIMARY KEY CLUSTERED ([saleID] ASC, [itemSKU] ASC),
CONSTRAINT [FK_SaleItem_Sales] FOREIGN KEY ([saleID]) REFERENCES [dbo].[Sales] ([saleID]),
CONSTRAINT [FK_SaleItem_Item] FOREIGN KEY ([itemSKU]) REFERENCES [dbo].[Item] ([ItemSKU])
);
我想在SaleItem表(第三个)中插入一条新记录,其中saleID是Sales表中记录的最后一个ID,ItemSKU等于我从另一个窗口得到的值。
我想要这些值:
SaleID = SELECT TOP 1 saleID FROM Sales ORDER BY saleID DESC";
ItemSKU = "SELECT itemName FROM Item WHERE ItemSKU = @sku";
我想我必须在一个查询中完成它,但我不知道如何。 你能给我一个提示吗?我
答案 0 :(得分:0)
首先,您需要从dbo.SaleItem表中删除IDENTITY属性。只有父表dbo.Sales。
才需要IDENTITY属性你可以像这样做一个INSERT语句。它使用两个子查询(括号中的SELECT语句)来从其他两个表中获取值。
INSERT INTO dbo.SaleItem (saleID, itemSKU, quantity)
VALUES ((SELECT MAX(saleID) FROM dbo.Sales),
(SELECT ItemSKU FROM dbo.Item WHERE itemName = N'Widget'),
50);
您可能希望将其转换为存储过程,如下所示:
CREATE PROCEDURE dbo.up_InsertSaleItem
(
@itemName nvarchar(50),
@quantity int
)
AS
INSERT INTO dbo.SaleItem (saleID, itemSKU, quantity)
VALUES ((SELECT MAX(saleID) FROM dbo.Sales),
(SELECT ItemSKU FROM dbo.Item WHERE itemName = @itemName),
@quantity);
然后使用存储过程:
-- Test the stored procedure
EXEC dbo.up_InsertSaleItem @itemName=N'Widget', @quantity=50;
SELECT *
FROM dbo.SaleItem;
要阅读有关子查询的更多信息,请参阅Itzik Ben-Gan的Microsoft SQL Server 2012 T-SQL基础知识,第4章:子查询。