블로그 이미지
010-9967-0955 보미아빠

카테고리

보미아빠, 석이 (500)
밥벌이 (16)
싸이클 (1)
일상 (1)
Total
Today
Yesterday

달력

« » 2024.4
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30

공지사항

최근에 올라온 글

--dynamic 쿼리가 몹시 귀찮은 경우
--다른 컬럼으로 index 를 타고, 필터조건만 처리 할 경우 유용한 쿼리 로직

if object_id ('tblx') is not null
drop table tblx
go

create table tblx
(idx int
,c1 int
,c2 int
)
go

insert into tblx values(1,1,null),(2,null,2),(3,3,3), (4, null,null)

-- @c1 의 값이 null 이면 필터하지 않고, 값이 있으면 값으로 뿌린다.
-- 보통 다음과 같은 쿼리를 짜는데, 이는 null 값에 문제를 일으킨다.
-- 아래 문제를 해결하는 것이 미션 1 이다.

declare @c1 int = null

select *
  from tblx
 where c1 = case when @c1 is null then c1 else @c1 end
go

-- 해결방안

declare @c1 int = null

select *
  from tblx
 where (c1 = @c1 or 1=case when @c1 is null  then 1 else 0 end)
go

-- @c1 의 값이 9999 이면 필터하지 않고, 값이 있으면 값으로 출력하며, null 이면 null 만 출력한다. 
-- 이것이 미션 2 이다.

declare @c1 int = 9999

select *
  from tblx
 where (c1 = @c1 or 1=case when @c1 = 9999  then 1 else 0 end) or (c1 is null and 1=case when @c1 is null then 1 else 0 end)
go

-- 복합 필터 조건
declare @c1 int = null
declare @c2 int = null

select *
  from tblx
 where ((c1 = @c1 or 1=case when @c1 = 9999  then 1 else 0 end) or (c1 is null and 1=case when @c1 is null then 1 else 0 end))
   and ((c2 = @c2 or 1=case when @c2 = 9999  then 1 else 0 end) or (c2 is null and 1=case when @c2 is null then 1 else 0 end))
go

 select *
  from tbly
 where (a = @col1 or @col1 is null)

Posted by 보미아빠
, |

최근에 달린 댓글

최근에 받은 트랙백

글 보관함