如何正确写这个?
我正在编写一个将采用(StockName, NewOpenPrice, NewClosePrice
)的存储过程,并向表中添加一条新记录(如图所示),如果stockname不存在则。如果库存名称为EXIST,则OpenPrice和ClosePrice将使用新插入的价格进行更新。最后我想调用存储过程
这就是现在的样子
CREATE PROCEDURE p_updatestock
(
@StockName VARCHAR(50),
@OpenPrice MONEY,
@ClosePrice MONEY)
AS
Declare @NewOpenPrice MONEY
Declare @NewClosePrice MONEY
UPDATE Stocks
SET StockName = @StockName
SET @StockName = @rowcount
UPDATE Stocks
SET NewOpenPrice = @NewOpenPrice
WHERE OpenPrice = @NewOpenPrice
SET @NewOpenPrice = @rowcount
IF (@StockName EXIST THEN OpenPrice)
UPDATE Stocks
SET NewClosePrice = @NewClosePrice
WHERE ClosePrice = @NewClosePrice
SET @NewClosePrice = @rowcount
IF (@StockName EXIST THEN ClosePrice)
答案 0 :(得分:2)
我认为这就是你需要的
CREATE PROCEDURE P_updatestock (@StockName VARCHAR(50),
@OpenPrice MONEY,
@ClosePrice MONEY)
AS
BEGIN
IF EXISTS (SELECT 1
FROM Stocks
WHERE StockName = @StockName)
UPDATE Stocks
SET ClosePrice = @ClosePrice,
Openprice = @Openprice
WHERE StockName = @StockName
ELSE
INSERT INTO stocks
(StockName,
Openprice,
ClosePrice)
VALUES (@StockName,
@Openprice,
@ClosePrice)
END
或使用Merge
代替If-Else
MERGE Stocks AS target
USING (SELECT @StockName,
@OpenPrice,
@ClosePrice) AS source (StockName, OpenPrice, ClosePrice)
ON ( target.StockName = source.StockName )
WHEN MATCHED THEN
UPDATE SET ClosePrice = source.ClosePrice,
Openprice = source.Openprice
WHEN NOT MATCHED THEN
INSERT (StockName,
Openprice,
ClosePrice)
VALUES (source.StockName,
source.Openprice,
source.closeprice)
执行
exec P_updatestock 'PFE',22.34,32.45