Not sure where your syntax error is...
This works for me:
create column table usersA as (select user_id, user_name from users where mod(user_id, 2) =1); create column table usersB as (select user_id, user_name from users where mod(user_id, 2) =0); select 'A', count(*) from usersA union all select 'B', count(*) from usersB;
| 'A' | COUNT(*) |
| A | 6 |
| B | 8 |
drop procedure pr_select11;
CREATE PROCEDURE pr_select11(IN v_in_id INTEGER)
LANGUAGE SQLSCRIPT AS
BEGIN
declare v_user_id integer;
declare v_user_name nvarchar(256);
DECLARE CURSOR c_cursor1 (v_in_id INTEGER) FOR SELECT user_id, user_name from usersA where user_id = :v_in_id ; OPEN c_cursor1(:v_in_id); FETCH c_cursor1 INTO v_user_id, v_user_name; IF c_cursor1::NOTFOUND then execute immediate 'SELECT user_id, user_name from usersB where user_id = (''' || :v_in_id || ''')'; ELSE execute immediate 'SELECT user_id, user_name from usersA where user_id = (''' || :v_in_id || ''')'; END IF; CLOSE c_cursor1;
END;call pr_select11 (131074)
| USER_ID | USER_NAME |
| 131074 | SYSTEM |
Not sure why you need to employ dynamic SQL here - you could e.g. simply use standard SQL or define additional cursors.
Anyhow, as mentioned before, you could also do something like this:
select * from usersA where user_id = 131074 union all select * from usersB where user_id = 131074 AND not exists (select 1 from usersA where user_id = 131074);
And still get the same result.
If there's really the requirement to explicitly weight the data sources against each other and only take the highest ranking one, this is also not too difficult:
select TOP 1 PRIO, USER_ID, USER_NAME FROM ( select 1 as PRIO, user_id, user_name from usersA union all select 2 as PRIO, user_id, user_name from usersB) WHERE user_id = 131074 order by PRIO ASC, USER_ID;
BTW: the record I select is only available in usersB in my case.
Whatever you go with, I highly recommend to perform some performance measurements with different approaches.
- Lars