存储过程基于条件更新单行

x759pob2  于 2022-10-22  发布在  其他
关注(0)|答案(1)|浏览(134)

我正在尝试在SQLServer中创建一个存储过程,它将在给定条件的情况下更新表。
假设我有一张有订单的table
|订单ID |产品ID |数量|
| ------------ | ------------ | ------------ |
|1000|BEA10|2|
|1000 |等级25|5|
|1001|等级50|3|
|1001|等级25|1|
|1001|等级60|4|
|1002|BEA10|1|
我们要插入的表称为InsertOrder
|ID|代码|订单ID|
| ------------ | ------------ | ------------ |
|1|ABC1|空|
|2|ABC2|空|
|3|ABC3|空|
|4|ABC4|空|
|5|ABC5|空|
|6|ABC6|空|
我想做的是查看产品ID=“BEA10”的订单表,并更新InsertOrder表中的一行,并将其设置为订单ID,只要InsertOrder信息表中的订单ID为NULL
我想这意味着,如果我们再次运行存储过程,它应该忽略已经插入的订单ID。
我对SQL相当陌生,所以我尝试构建某种形式的代码,但这似乎很遥远

ALTER PROCEDURE [dbo].[InsertOrder] 

AS

-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

DECLARE @ORDERS_PRODUCTID nvarchar(50);
DECLARE @ORDERS_ORDERID int;

SELECT @ORDERS_PRODUCTID = ProductID from ORDERS
SELECT @ORDERS_ORDERID = OrderID from ORDERS

IF(@ORDERS_PRODUCTID = 'BEA10' and @ORDERS_ORDERID not in (SELECT OrderID from InsertOrder)) 

BEGIN

    UPDATE InsertOrder SET OrderID = @ORDERS_ORDERID where OrderID is null

END
GO
ie3xauqp

ie3xauqp1#

希望它能起作用

DECLARE @ORDERS_PRODUCTID nvarchar(50);
DECLARE @ORDERS_ORDERID int;

SET @ORDERS_ORDERID = (SELECT OrderID 
                        FROM ORDERS O 
                        WHERE ProductID='BEA10' 
                            AND NOT EXISTS (SELECT 1 FROM InsertOrder WHERE OrderID=O.OrderID));

UPDATE InsertOrder 
SET OrderID = @ORDERS_ORDERID 
WHERE Code=(SELECT TOP 1 Code FROM InsertOrder WHERE OrderID is null);

相关问题