gauravghodnadikar
gauravghodnadikar

Reputation: 336

cursor with if statement

How can i write cursor when table is not fix. E.g

DECLARE cursor_1 CURSOR
FOR 
 IF BEGIN @i=1 SELECT col1,col2 FROM table_1 END
 ELSE BEGIN SELECT col1,col2 FROM table_2 END

...

This gives syntax error please suggest ?

Upvotes: 1

Views: 8662

Answers (2)

Paddy
Paddy

Reputation: 33867

his is an ugly hack, and you'd possibly be better with dynamic SQL, or re-writing this in a more sensible way, but:

DECLARE cursor_1 CURSOR
FOR 
  SELECT col1, col2 FROM table_1
  WHERE @i = 1
  UNION
  SELECT col1, col2 FROM table_2
  WHERE @i = 2 

Upvotes: 1

RichardTheKiwi
RichardTheKiwi

Reputation: 107786

This actually works, if you write it correctly!

IF @i=1
 declare cur cursor for
  SELECT col1,col2 FROM table_1
ELSE
 declare cur cursor for
  SELECT col1,col2 FROM table_2

Upvotes: 3

Related Questions