Oracle 如果存在則修改,不存在則插入的實現方式

 在實際的開發過程中,我們經常會遇到數據的插入的需求,在數據的插入時排重是很關鍵的一步,下面介紹一個SQL實現存在則修改,不存在則插入的方法。

 

merge into T_WXOPENINFO t1
        USING (select #{userId} AS a, #{appId} AS b
               from dual) t2
        on (t1.userId = t2.a and t1.appid = t2.b)
        when matched then
            update
            set t1.openId = #{openId}
        when not matched then
            insert (id, userId, openId, appId, createtime)
            VALUES (SEQ_t_subuywxopen.nextval,  #{userId}, #{openId}, #{appId}, sysdate)

採用merge into的方法,  t1 指的是要插入的表的別名。    在Using中查出你想要唯一標識的主鍵或聯合主鍵。 我這裏通過userId和appId唯一作爲數據的唯一性校驗。當存在的時候執行update 方法,修改表中的openId, 如果不存在則執行insert操作.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章