My IF condition is always executing ELSE statement. I could not find reason why it's returning "No". It should return "Yes".
It looks like parameter XPARAM is getting NULL value but why?
Note: I have to return a table from that function because variable sql_statement will be dynamic.
Below is the code and the output:
create or replace function traudit04011 (
XPARAM IN VARCHAR2)
return VARCHAR2 sql_macro as
sql_statement varchar2(5000);
vc_condition varchar(1000);
p_search_by1 varchar(100) := '';
begin
IF XPARAM is not NULL THEN
vc_condition:='yes';
ELSE
vc_condition:='No';
END IF;
sql_statement := 'select ''' || vc_condition || ''' d1 from dual'; -- In real world, instead of XPARAM there will be a variable storing dynamic query
return sql_statement;
end;
I tried replacing parameter with local variable but the output is the same:
create or replace function traudit04011 (
XPARAM VARCHAR2)
return VARCHAR2 sql_macro as
sql_statement varchar2(5000);
vc_condition varchar(1000);
p_search_by1 varchar(100) := '';
begin
p_search_by1:= XPARAM;
IF p_search_by1 is not NULL THEN
vc_condition:='yes';
ELSE
vc_condition:='No';
END IF;
sql_statement := 'select ''' || vc_condition || ''' d1 from dual'; -- In real world, instead of XPARAM there will be a variable storing dynamic query
return sql_statement;
end;
I am executing the above function from the below statement :
select * from traudit04011('service_date')
Any help is deeply appreciated. I am completely blocked here.
SQlFiddle --- > https://dbfiddle.uk/j537Ye0K

The parameter in a SQL Macro needs to be directly referenced in the returned string.
For example, the below function processes the parameter with a CASE statement returned by the string. The output is correct: "Yes" when the input is not null, and "No" when the input is null.
But this below function processes the parameter in PL/SQL, stores the result in a variable, and then returns that variable. But the code does not work and returns the wrong result "No" for both cases:
Fiddles: https://dbfiddle.uk/GZI3xzob, https://dbfiddle.uk/Xb5KL4SC
But why?
I'm not entirely sure why SQL Macros behave this way and I can't find this behavior explained in the documentation.
What I think is happening is that SQL Macros are trying to ensure that not every execution is dynamic, because that kind of behavior would lead to lots of hard parsing and poor performance. So each statement is checked to see if the output depends on the input, and if there is no relationship than the same static text is returned. But that checking isn't working correctly here and is fooled by a simple indirect variable.
I'm not sure if this behavior is a bug or an unavoidable consequence of this kind of pseudo-dynamic code.
Workarounds
There's always a dynamic SQL solution, but you may need to use a different type of dynamic SQL.