我遇到了问题。我有两个表FreshStock
和PurchaseInvoiceDetails
。
收到新产品时,它会进入PurchaseInvoiceDetails
,我也希望它也进入第二个表。
我有代码,该代码首先检查是否未在FreshStock
中添加产品,然后首先添加它,但是如果它已经添加了产品,那么它将通过ProductName对其进行更新。更新时出现错误:
信息512,级别16,状态1,第13行
子查询返回的值超过1。当子查询遵循=,!=,<,<=,>,> =或将子查询用作表达式时,不允许这样做。 该声明已终止。
我的代码:
IF NOT EXISTS(SELECT * FROM [dbo].[FreshStock] WHERE [ProductName] = 'Makki Rusk')
BEGIN
INSERT INTO [dbo].[FreshStock] ([ProductCode], [ProductName], [Stock],[IsAvailable])
SELECT [ProductCode], [ProductName], SUM([Box]), 1
FROM [dbo].[PurchaseInvoiceDetails]
WHERE ProductName = 'Makki Rusk'
GROUP BY [ProductCode],[ProductName]
RETURN
END
IF EXISTS(SELECT * FROM [dbo].[FreshStock] WHERE [ProductName] = 'Makki Rusk')
BEGIN
UPDATE [dbo].[FreshStock]
SET [ProductCode] = (SELECT [ProductCode]
FROM [dbo].[PurchaseInvoiceDetails]
WHERE [ProductName] = 'Makki Rusk'),
[ProductName] = (SELECT [ProductName]
FROM [dbo].[PurchaseInvoiceDetails]
WHERE [ProductName] = 'Makki Rusk'),
[Stock] = (SELECT SUM([Box])
FROM [dbo].[PurchaseInvoiceDetails]
WHERE [ProductName] = 'Makki Rusk')
WHERE ProductName = 'Makki Rusk'
END
答案 0 :(得分:2)
您收到的错误表明以下子查询之一正在返回多行,需要修改以仅返回单行:
[ProductName] = SELECT [ProductCode] FROM [dbo].[PurchaseInvoiceDetails] WHERE [ProductName] = 'Makki Rusk'
[ProductName] = (SELECT [ProductName] FROM [dbo].[PurchaseInvoiceDetails] WHERE [ProductName] = 'Makki Rusk')
答案 1 :(得分:1)
您可能不需要重新设置代码和名称,因此只需设置一列:
UPDATE [dbo].[FreshStock]
SET [Stock] = (SELECT SUM([Box])
FROM [dbo].[PurchaseInvoiceDetails]
WHERE [ProductName] = 'Makki Rusk'
)
WHERE ProductName = 'Makki Rusk';