반응형

cursor 문에 조건문을 넣고 싶은 경우가 있다.

그런데 아래 처럼 if 문을 사용하면 에러가 난다.

declare @cursor cursor

set @cursor = cursor for

if (@test <> '')
begin
      select * from table1
      where test = @test
end
else
begin
      select * from table1
end

open @cursor

...

 

꼭 if 문을 쓰고 싶다면 if 문 안으로 @cursor 정의를 넣어야 한다.

declare @cursor cursor

if (@test <> '')
begin

	set @cursor = cursor for
    
	select * from table1
	where test = @test
end
else
begin

	set @cursor = cursor for

	select * from table1
end

open @cursor

...

그런데 이렇게 하면 조건이 많아질 수록 비슷한 쿼리를 계속 반복해야 한다.

 

 

이런 경우 아래와 같이 처리하면 간단해진다.

declare @cursor cursor for

select * from table1
where (isnull(@test, '') = '' or test = @test)

open @cursor

...

이렇게 하면 된다.

 

 

반응형

+ Recent posts