sql

dynamic qyery

카리스마유 2017. 2. 3. 11:03

select 같은 query를 수행하다보면 문자열을 비교 하거나 java 에서처럼 if else 같은 조건문을 사용해야 할때가 있다.이때 사용하는 쿼리를 말하며 몇가지가 있는데 아래는 직접 사용해본 쿼리를 기록하였다.


1. if 문 사용법


    <select id="isAdminId" resultMap="Member_map">

        select * from [table name]


<if test="id_ != null and id_ == 'admin'">

where id=#{id_}  

</if>

                  

   </select>


select 문안에서 if  문을 사용할수 있는데 else 기능이 없어서 조건에 맞지 않는 값이 들어오면 error가 날수 있다.




2. choose 문 사용법


    <select id="isAdminId" resultMap="Member_map">

        select * from [table name]


       <where> 

 <choose> 

 <when test="id_ == 'admin'">

 phone=#{id_} 

 </when>

 <when test="id_ != 'admin'">

 phone='test' 

 </when> 

 </choose> 

 </where> 

                  

   </select>


select 문안에서 choose 문을 사용할수 있는데 if문과 차이점은 else의 기능을 사용할수 있다는 점이다.

when 절이 하나가 수행되면 다른 when 절은 수행되지 않는다