简体   繁体   中英

inserting records in Oracle SQL

I have a table with following columns

USER_ID,LINK_NAME,LINK_URL,DESCRIPTION,LINK_ID. 

USER_ID can have duplicate values. I need to add a specific data containing LINK_NAME,LINK_URL,DESCRIPTION,LINK_ID for those USER_ID which does not already contain it. Any solution is welcomed.

Here is an easy way to do this.

INSERT INTO your_table (user_id,
                    link_name,
                    link_url,
                    description,
                    link_id) 
SELECT a.user_id,
      a.link_name,
      a.link_url,
      a.description,
      a.link_id
 FROM (SELECT DISTINCT user_id,
                       :1 link_name,
                       :2 link_url,
                       :3 description,
                       :4 link_id
         FROM your_table yt) a
WHERE NOT EXISTS
             (SELECT 'X'
                FROM your_table b
               WHERE     b.user_id = a.user_id
                     AND NVL (b.link_name, 'IMPOSSIBLE_VALUE') = a.link_name
                     AND NVL (b.link_url, 'IMPOSSIBLE_VALUE') = a.link_url
                     AND NVL (b.description, 'IMPOSSIBLE_VALUE') = a.description
                     AND NVL (TO_CHAR(b.link_id), 'IMPOSSIBLE_VALUE') = a.link_id)

I have assumed that link_id will be a NUMBER so in order to use NVL on this I transformed this to CHAR. Also another assumption I have taken is that USER_ID has index. If you don't have index on this column you will have performance issues (depending on the size of the table). In case this is a huge table, you might want to use PARALLEL hint before DISTINCT since you must full table scan in order to get the distinct user ids (and not make multiple inserts for a user_id).

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