Sql存储过程插入和更新

时间:2014-11-12 16:43:56

标签: sql sql-server stored-procedures

我是Stored Procedures和SQL的新手。查看各种文章,我找到了如何使用存储过程插入记录,并且它可以工作。

CREATE PROCEDURE  [dbo].[stprOrder]
    @OrderDate date,
    @OrderID nchar(50),
    @ShipToID nchar(50),
    @TotalAmt  decimal(18,2),
AS
BEGIN

    SET NOCOUNT ON;
    INSERT INTO ORDER(OrderDate,OrderID,ShipToID,TotalAmt)
    Values(@OrderDate,@OrderID,@ShipToID,@TotalAmt)
END

我不确定如何使用相同的stprOrder存储过程更新记录。与存储过程一样,应根据OrderID进行插入和更新。

2 个答案:

答案 0 :(得分:0)

很可能你正在寻找类似这样的东西

CREATE PROCEDURE  [dbo].[stprOrder]

 @OrderDate date,
 @OrderID nchar(50),
 @ShipToID nchar(50),
 @TotalAmt  decimal(18,2),
AS
BEGIN
  SET NOCOUNT ON;

  IF (SELECT TOP (1) 1 FROM ORDER WHERE OrderID = @OrderID) IS NULL
     INSERT INTO ORDER(OrderDate,OrderID,ShipToID,TotalAmt)
     Values(@OrderDate,@OrderID,@ShipToID,@TotalAmt)
  ELSE
    UPDATE ORDER SET OrderDate = @OrderDate, ShipToID = @ShipToID, TotalAmt = @TotalAmt
    WHERE OrderID = @OrderID
END

首先检查具有给定ID的订单是否已经存在 - 如果它没有 - 创建新条目,否则更新现有记录

答案 1 :(得分:0)

CREATE PROCEDURE  [dbo].[stprOrder]

 @OrderDate date,
 @OrderID nchar(50),
 @ShipToID nchar(50),
 @TotalAmt  decimal(18,2),
AS
BEGIN

  SET NOCOUNT ON;

  IF EXISTS (SELECT null FROM ORDER WHERE id = @orderID)
   BEGIN
       UPDATE ORDER SET ..... WHERE id = @orderID
   END
ELSE
BEGIN
   INSERT INTO ORDER(OrderDate,OrderID,ShipToID,TotalAmt)
   VALUES(@OrderDate,@OrderID,@ShipToID,@TotalAmt)
END