[Oracle] merge문 = 있으면 업데이트 없으면 insert하고싶을때

2024. 7. 17. 18:00DataBase

A라는 테이블에 이미 데이터가 생성된 상태라면 

굳이 insert 할필요가 없기때문에 update 가 필요하다.

 

update 쿼리와 insert 쿼리를 각각 1개씩 사용하여 조건문 처리도 가능하지만

이를 xml 단에서 merge 문을 사용하여 1개의 쿼리로 A라는 테이블에 데이터가 있으면 업데이트하고,

없으면 insert 할수있다.

 

아래 예시는 작성한 merge 문 쿼리입니다.

merge into project_mro_info 
    	using dual
    		on (project_cd = #{project_cd})
    	when matched then
    	update 
    	set
    		user_id = #{user_id}
    		,mro_type = #{mro_type}
    		,mro_day = #{mro_day}
    		,noti_user_list = #{noti_user_list}
    		,mro_start_dt = #{mro_start_dt}
    		,mro_end_dt = #{mro_end_dt}
    		,mro_auto_yn = #{mro_auto_yn}
    	where
    		project_cd = #{project_cd}

			when not matched then
    		insert 
    		(
	    		project_cd, 
	    		user_id, 
	    		mro_type, 
	    		mro_day,
	    		noti_user_list, 
	    	  mro_start_dt,
	    	  mro_end_dt,
	    	  mro_auto_yn,
	    	  mro_o_dt
    		)
    		values 
    		(
	    		#{project_cd}, 
	    		#{user_id},
				  #{mro_type},
				  #{mro_day},
			    #{noti_user_list}, 
			    #{mro_start_dt},
			    #{mro_end_dt},
	    	  #{mro_auto_yn},
	    	  #{mro_start_dt}
    		)