oracle 在使用存储过程将数据插入表中并将值作为参数传递时,如何添加数据已经存在的检查

tsm1rwdh  于 2023-05-06  发布在  Oracle
关注(0)|答案(1)|浏览(167)
CREATE OR REPLACE PROCEDURE AddNewReview(
  RESTAURANTNAME IN VARCHAR2 (100)
, USERNAME IN VARCHAR2 (100)
, Stars IN Int
, RATINGDATE IN DATE 
) AS 
BEGIN
  INSERT INTO newReview VALUES (RestaurantName, UserName, Stars, RatingDate);
END AddNewReview;
;

如何添加一个检查,使其仅在数据不存在时插入?

svgewumm

svgewumm1#

您可以使用select ... where not exist (...)来确保不复制数据。假设列RestaurantNameUserNameRatingDate可以用作(伪)主键:

CREATE OR REPLACE PROCEDURE AddNewReview(
    pRestaurantName IN VARCHAR2 (100),
    pUserName IN VARCHAR2(100),
    pStars IN INT,
    pRatingDate IN DATE 
) AS 
BEGIN
    INSERT INTO newReview (RestaurantName, UserName, Stars, RatingDate)
    SELECT p.*
    FROM (
        SELECT pRestaurantName RestaurantName, 
            pUserName UserName, 
            pStars Stars, 
            pRatingDate RatingDate
        FROM DUAL
    ) p
    WHERE NOT EXISTS (
        SELECT 1
        FROM newReview r
        WHERE r.RestaurantName = p.RestaurantName 
          AND r.UserName = p.UserName 
          AND r.RatingDate = p.RatingDate
    )
END AddNewReview;

请注意,我重命名了IN参数,这样它们就不会与列名冲突。我还列出了插入的目标列。这两种变化都是好的做法。

相关问题