简体   繁体   中英

Sql Stored Procedure to insert and update

I am new to Stored Procedures and SQL. Looking in to various articles, I found how to insert an record using stored procedure and it works.

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

I am not sure how to update an record using the same stprOrder stored procedure. Like the stored procedure should do inserting and updating depending on the OrderID .

Most likely you're looking for something like this

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

First it checks if order with given ID already exists - if it doesn't - a new entry is created, otherwise existing record is updated

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM