Turn a case statement into a function
I have a case statement (from an earlier post - thank you) that works. I was wondering if it could be edited and change into a function instead. I think it would be cleaner. The variable is set in the Form Properties (pCounterA).
switch (pCounterA.value)
case "1":
profileA__1image.rawValue = profileA_1image.value.image.value;
pCounterA.value = "2";
break;
case "2":
profileA__1image.rawValue = profileA_2image.value.image.value;
pCounterA.value = "3";
break;
case "3":
profileA__1image.rawValue = profileA_3image.value.image.value;
pCounterA.value = "4";
break;
case "4":
profileA__1image.rawValue = profileA_4image.value.image.value;
pCounterA.value = "5";
break;
case "5":
profileA__1image.rawValue = profileA_5image.value.image.value;
pCounterA.value = "1"; // loops back to the first image
break;
Hi,
If you insert a script object by right clicking on the root container (often "form1"). It will appear unnamed in the root / variables in the hierarchy.
First of all you should name the script object, staying away from reserved names, eg "this". Say "myScripts"
Script objects can only contain Javascript, so you would need to convert FormCalc scripts (not an issue in your case).
When you go into the script object, you start off a function with "function" followed by its name and inputs in brackets. The extent of the function is given by curly brackets:
function changeImage(vCounter)
switch (vCounter)
case "1":
profileA__1image.rawValue = profileA_1image.value.image.value;
pCounterA.value = "2";
break;
} // close switch statement
} // close function
Back in the form you can call the function by referencing the name of the script object and the name of the function.
myScripts.changeImage(pCounterA.value);
A couple of things to note:
The input in the script can refer to an objects value or a global variable, but in the function you can assign it s different name. So above the input pCounterA.value is EQUAL to vCounter in the function;
You can have several inputs in the call for the function separated by commas;
Don't have the same name for the script object AND the function
Hope that helps,
Niall
Similar Messages
-
Case statement and Decode function both are not working in Select cursor.
I have tried both the Case statement and Decode function in Select cursor, but both the things are not working. On the other hand both the things work in just select statement.
See the first column in select (PAR_FLAG), I need to have this evaluated along with other fields. Can you please suggest some thing to make this work. And also I would like to
know the reason why decode is not working, I heard some where Case statement do not work with 8i.
Author : Amit Juneja
Date : 06/20/2011
Description:
Updates the Diamond MEMBER_MASTER table with the values from
INC.MEM_NJ_HN_MEMBER_XREF table.
declare
rec_cnt number(12) := 0;
commit_cnt number(4) := 0;
cursor select_cur is
Select DECODE(1,
(Select 1
from hsd_prov_contract R
where R.seq_prov_id = PM.seq_prov_id
and R.line_of_business = H.line_of_business
and R.PCP_FLAG = 'Y'
and R.participation_flag = 'P'
and SYSDATE between R.EFFECTIVE_DATE AND
NVL(R.TERM_DATE,
TO_DATE('31-DEC-9999', 'DD-MON-YYYY'))),
'Y',
'N') PAR_FLAG,
H.SEQ_ELIG_HIST,
H.SEQ_MEMB_ID,
H.SEQ_SUBS_ID,
H.SUBSCRIBER_ID,
H.PERSON_NUMBER,
H.EFFECTIVE_DATE,
H.TERM_DATE,
H.TERM_REASON,
H.RELATIONSHIP_CODE,
H.SEQ_GROUP_ID,
H.PLAN_CODE,
H.LINE_OF_BUSINESS,
H.RIDER_CODE_1,
H.RIDER_CODE_2,
H.RIDER_CODE_3,
H.RIDER_CODE_4,
H.RIDER_CODE_5,
H.RIDER_CODE_6,
H.RIDER_CODE_7,
H.RIDER_CODE_8,
H.MEDICARE_STATUS_FLG,
H.OTHER_STATUS_FLAG,
H.HIRE_DATE,
H.ELIG_STATUS,
H.PREM_OVERRIDE_STEP,
H.PREM_OVERRIDE_AMT,
H.PREM_OVERRIDE_CODE,
H.SEQ_PROV_ID,
H.IPA_ID,
H.PANEL_ID,
H.SEQ_PROV_2_ID,
H.SECURITY_CODE,
H.INSERT_DATETIME,
H.INSERT_USER,
H.INSERT_PROCESS,
H.UPDATE_DATETIME,
H.UPDATE_USER,
H.UPDATE_PROCESS,
H.USER_DEFINED_1,
H.SALARY,
H.PEC_END_DATE,
H.REASON_CODE,
H.PEC_WAIVED,
H.BILL_EFFECTIVE_FROM_DATE,
H.BILLED_THRU_DATE,
H.PAID_THRU_DATE,
H.SUBSC_DEPT,
H.SUBSC_LOCATION,
H.USE_EFT_FLG,
H.BENEFIT_START_DATE,
H.SEQ_ENROLLMENT_RULE,
H.MCARE_RISK_ACCRETION_DATE,
H.MCARE_RISK_DELETION_DATE,
H.MCARE_RISK_REFUSED_DATE,
H.COMMENTS,
H.USER_DEFINED_2,
H.USER_DEFINED_3,
H.RATE_TYPE,
H.PCPAA_OCCURRED,
H.PRIVACY_ON,
H.PCP_CHANGE_REASON,
H.SITE_CODE,
H.SEQ_SITE_ADDRESS_ID,
PM.seq_prov_id rendered_prov
from hsd_member_elig_history H,
INC.PCP_REASSIGN_RPRT_DATA P,
hsd_prov_master PM
where P.subscriber_id = H.subscriber_id
and P.rendered_pcp = PM.provider_ID
and H.elig_status = 'Y'
and (H.term_date is NULL or H.term_date >= last_day(sysdate))
order by H.Seq_memb_id;
begin
for C in select_cur loop
rec_cnt := rec_cnt + 1;
update hsd_member_elig_history
set term_date = TRUNC(SYSDATE - 1),
term_reason = 'PCPTR',
update_datetime = SYSDATE,
update_user = USER,
update_process = 'TD33615'
where seq_elig_hist = C.seq_elig_hist
and seq_memb_id = C.seq_memb_id;
INSERT INTO HSD_MEMBER_ELIG_HISTORY
(SEQ_ELIG_HIST,
SEQ_MEMB_ID,
SEQ_SUBS_ID,
SUBSCRIBER_ID,
PERSON_NUMBER,
EFFECTIVE_DATE,
TERM_DATE,
TERM_REASON,
RELATIONSHIP_CODE,
SEQ_GROUP_ID,
PLAN_CODE,
LINE_OF_BUSINESS,
RIDER_CODE_1,
RIDER_CODE_2,
RIDER_CODE_3,
RIDER_CODE_4,
RIDER_CODE_5,
RIDER_CODE_6,
RIDER_CODE_7,
RIDER_CODE_8,
MEDICARE_STATUS_FLG,
OTHER_STATUS_FLAG,
HIRE_DATE,
ELIG_STATUS,
PREM_OVERRIDE_STEP,
PREM_OVERRIDE_AMT,
PREM_OVERRIDE_CODE,
SEQ_PROV_ID,
IPA_ID,
PANEL_ID,
SEQ_PROV_2_ID,
SECURITY_CODE,
INSERT_DATETIME,
INSERT_USER,
INSERT_PROCESS,
UPDATE_DATETIME,
UPDATE_USER,
UPDATE_PROCESS,
USER_DEFINED_1,
SALARY,
PEC_END_DATE,
REASON_CODE,
PEC_WAIVED,
BILL_EFFECTIVE_FROM_DATE,
BILLED_THRU_DATE,
PAID_THRU_DATE,
SUBSC_DEPT,
SUBSC_LOCATION,
USE_EFT_FLG,
BENEFIT_START_DATE,
SEQ_ENROLLMENT_RULE,
MCARE_RISK_ACCRETION_DATE,
MCARE_RISK_DELETION_DATE,
MCARE_RISK_REFUSED_DATE,
COMMENTS,
USER_DEFINED_2,
USER_DEFINED_3,
RATE_TYPE,
PCPAA_OCCURRED,
PRIVACY_ON,
PCP_CHANGE_REASON,
SITE_CODE,
SEQ_SITE_ADDRESS_ID)
values
(hsd_seq_elig_hist.nextval,
C.SEQ_MEMB_ID,
C.SEQ_SUBS_ID,
C.SUBSCRIBER_ID,
C.PERSON_NUMBER,
trunc(SYSDATE),
C.TERM_DATE,
C.TERM_REASON,
C.RELATIONSHIP_CODE,
C.SEQ_GROUP_ID,
C.PLAN_CODE,
C.LINE_OF_BUSINESS,
C.RIDER_CODE_1,
C.RIDER_CODE_2,
C.RIDER_CODE_3,
C.RIDER_CODE_4,
C.RIDER_CODE_5,
C.RIDER_CODE_6,
C.RIDER_CODE_7,
C.RIDER_CODE_8,
C.MEDICARE_STATUS_FLG,
C.OTHER_STATUS_FLAG,
C.HIRE_DATE,
C.ELIG_STATUS,
C.PREM_OVERRIDE_STEP,
C.PREM_OVERRIDE_AMT,
C.PREM_OVERRIDE_CODE,
C.SEQ_PROV_ID,
C.IPA_ID,
C.PANEL_ID,
C.SEQ_PROV_2_ID,
C.SECURITY_CODE,
SYSDATE,
USER,
'TD33615',
SYSDATE,
USER,
'TD33615',
C.USER_DEFINED_1,
C.SALARY,
C.PEC_END_DATE,
C.REASON_CODE,
C.PEC_WAIVED,
C.BILL_EFFECTIVE_FROM_DATE,
C.BILLED_THRU_DATE,
C.PAID_THRU_DATE,
C.SUBSC_DEPT,
C.SUBSC_LOCATION,
C.USE_EFT_FLG,
C.BENEFIT_START_DATE,
C.SEQ_ENROLLMENT_RULE,
C.MCARE_RISK_ACCRETION_DATE,
C.MCARE_RISK_DELETION_DATE,
C.MCARE_RISK_REFUSED_DATE,
C.COMMENTS,
C.USER_DEFINED_2,
C.USER_DEFINED_3,
C.RATE_TYPE,
C.PCPAA_OCCURRED,
C.PRIVACY_ON,
C.PCP_CHANGE_REASON,
C.SITE_CODE,
C.SEQ_SITE_ADDRESS_ID);
commit_cnt := commit_cnt + 1;
if (commit_cnt = 1000) then
dbms_output.put_line('Committed updates for 1000 records.');
commit;
commit_cnt := 0;
end if;
end loop;
commit;
dbms_output.put_line('Total number of MEMBER_ELIG_HISTROY records inserted : ' ||
rec_cnt);
exception
when others then
raise_application_error(-20001,
'An error was encountered - ' || sqlcode ||
' -error- ' || sqlerrm);
end;user10305724 wrote:
I have tried both the Case statement and Decode function in Select cursor, but both the things are not working. Please define what you mean by not working even if your computer screen is near the internet we can't see it.
You should also look at the FAQ about how to ask a question
SQL and PL/SQL FAQ
Particularly *9) Formatting with {noformat}{noformat} Tags* and posting your version.
know the reason why decode is not working, I heard some where Case statement do not work with 8i.
Does this mean you are using 8i? Then scalar sub queries - selects within the select list, are not supported, along with CASE in PL/SQL.
Select DECODE(1,
* (Select 1
from hsd_prov_contract R
where R.seq_prov_id = PM.seq_prov_id
and R.line_of_business = H.line_of_business
and R.PCP_FLAG = 'Y'
and R.participation_flag = 'P'
and SYSDATE between R.EFFECTIVE_DATE AND
NVL(R.TERM_DATE,
TO_DATE('31-DEC-9999', 'DD-MON-YYYY')))*,
'Y',
'N') PAR_FLAG,
>
exception
when others then
raise_application_error(-20001,
'An error was encountered - ' || sqlcode ||
' -error- ' || sqlerrm);
http://tkyte.blogspot.com/2008/01/why-do-people-do-this.html -
Case Statement in Analytic Function SUM(n) OVER(PARTITION BY x)
Hi Guys,
I have the following SQL that doesn't seem to consider the When clause I am using in the case staement inside the analytic function(SUM). Could somebody let me know why? and suggest the solution?
Select SUM(Case When (A.Flag = 'B' and B.Status != 'C') Then (NVL(A.Amount_Cr, 0) - (NVL(A.Amount_Dr,0))) Else 0 End) OVER (PARTITION BY A.Period_Year) Annual_amount
, A.period_year
, B.status
, A.Flag
from A, B, C
where A.period_year = 2006
and C.Account = '301010'
--and B.STATUS != 'C'
--and A.Flag = 'B'
and A.Col_x = B.Col_x
and A.Col_y = C.Col_y
When I use this SQL, I get
Annual_Amount Period_Year Status Flag
5721017.5 --------- 2006 ---------- C -------- B
5721017.5 --------- 2006 ---------- O -------- B
5721017.5 --------- 2006 ---------- NULL ----- A
And when I put the conditions in the where clause, I get
Annual_Amount Period_Year Status Flag
5721017.5 ---------- 2006 ---------- O -------- BHere are some scripts,
create table testtable1 ( ColxID number(10), ColyID number(10) , Periodname varchar2(15), Flag varchar2(1), Periodyear number(15), debit number, credit number)
insert into testtable1 values(1, 1000, 'JAN-06', 'A', 2006, 7555523.71, 7647668)
insert into testtable1 values(2, 1001, 'FEB-06', 'B', 2006, 112710, 156047)
insert into testtable1 values(3, 1002, 'MAR-06', 'A', 2006, 200.57, 22376.43)
insert into testtable1 values(4, 1003, 'APR-06', 'B', 2006, 0, 53846)
insert into testtable1 values(5, 1004, 'MAY-06', 'A', 2006, 6349227.19, 6650278.03)
create table testtable2 ( ColxID number(10), Account number(10))
insert into testtable2 values(1, 300100)
insert into testtable2 values(2, 300200)
insert into testtable2 values(3, 300300)
insert into testtable2 values(4, 300400)
insert into testtable2 values(5, 300500)
create table apps.testtable3 ( ColyID number(10), Status varchar2(1))
insert into testtable3 values(1000, 'C')
insert into testtable3 values(1001, 'O')
insert into testtable3 values(1002, 'C')
My SQL:
select t1.periodyear
, SUM(Case When (t1.Flag = 'B' and t3.Status != 'C') Then (NVL(t1.credit, 0) - (NVL(t1.debit,0))) Else 0 End) OVER (PARTITION BY t1.PeriodYear)
Annual_amount
, t1.flag
, t3.status
, t2.account
from testtable1 t1, testtable2 t2, testtable3 t3
where t1.colxid = t2.colxid
and t1.colyid = t3.colyid(+)
--and t1.Flag = 'B' and t3.Status != 'C'
Result:
PeriodYear ----- AnnualAmount ----- Flag ----- Status ----- Account
2006 ------------------ 43337 --------------- A ----------- C ---------- 300100
2006 ------------------ 43337 --------------- B ----------- O ---------- 300200
2006 ------------------ 43337 --------------- A ----------- C ---------- 300300
2006 ------------------ 43337 --------------- B ------------ ----------- 300400
2006 ------------------ 43337 --------------- A ------------ ----------- 300500
With condition "t1.Flag = 'B' and t3.Status != 'C'" in where clause instead of in Case statement, Result is (which is desired)
PeriodYear ----- AnnualAmount ----- Flag ----- Status ----- Account
2006 ------------------ 43337 --------------- B ----------- O ---------- 300200 -
CASE Statement error in function -- Please help!
Hi All,
I created a function in my report.
It has a SQL query similar to the one below. The query works fine in SQL plus.
It has a CASE statement. I am getting error at line4 at the select statement. Error is: "Encountered symbol 'SELECT'....."
Can we use CASE statements like this in reports that use SELECT statements for RETURN EXPRESSIONS. Do we have to do any special?
Can someone help me out of this trouble?
THanks in advance.
SELECT PARENT_id,
CASE WHEN EXISTS (SELECT PARENT_id FROM CHILD CH1 WHERE CH1.PARENT_id = PARENT.PARENT_id AND UPPER(CH1.description) LIKE '%ABC%') THEN
(SELECT CH2.MOD_id FROM CHILD CH2 WHERE CH2.PARENT_id = PARENT.PARENT_id AND UPPER(CH2.description) LIKE '%ABC%')
ELSE
(SELECT MOD_id FROM
(SELECT MOD_id,PARENT_id FROM CHILD CH3 ORDER BY started) MOD2 WHERE MOD2.PARENT_id = PARENT.PARENT_id AND ROWNUM = 1
END
) MOD_ID
FROM PARENT;take out the parentheses after the PARENT_ID and see
like below
SELECT parent_id,
CASE
WHEN EXISTS (
SELECT parent_id
FROM CHILD ch1
WHERE ch1.parent_id = PARENT.parent_id
AND UPPER (ch1.description) LIKE '%ABC%')
THEN (SELECT ch2.mod_id
FROM CHILD ch2
WHERE ch2.parent_id = PARENT.parent_id
AND UPPER (ch2.description) LIKE '%ABC%')
ELSE (SELECT mod_id
FROM (SELECT mod_id, parent_id
FROM CHILD ch3
ORDER BY started) mod2
WHERE mod2.parent_id = PARENT.parent_id AND ROWNUM = 1)
END AS mod_id
FROM PARENT; -
Regarding case statement and decode function
Hi Experts,
I have question.....regarding case statement and decode statement....
Can you please explain me that which one will be efficient,to place in insert statement...
insert statement(
(case when ........then
case when ....then
else
end)
else
end)
or
insert statement(
case when.....then
decode(....)
else
end)
Can you people explain me which one is more efficient method?
Thanks in advance.......The are major differences to talk about in case of CASE vs DECODE, but performance wise both are pretty much the same.
Have a look at Tom's thread
Ask Tom "better performance - case or decode"
I would suggest to use CASE whenever possible. Don't worry about the performance part. -
Case Statement into XML , XMLType column
We are storing following(example) xml into xmltype column (column name xmlfile , table name xml_table) .
<?xml version = '1.0' encoding = 'UTF-8'?>
<context id="reporting_options">
<scenario>
<abc:isAllow>false</abc:isAllow>
</scenario>
</context>
<abc:tab1 contextRef="con1">89841</abc:tab1>
<abc:tab1 contextRef="con2">-18514</abc:tab1>
<abc:tab2 contextRef="con1">89841</abc:tab2>
<abc:tab2 contextRef="con2">-18514</abc:tab2>
<abc:tab3 contextRef="con1">By Current/Non-Current Classification</abc:tab3>
<abc:tab3 contextRef="con2">0</abc:tab3>
</xml>I want to extract the values for tab1 .. tab3 based on * <abc:isAllow>false</abc:isAllow>*. Now i'm doing in following way.Note , based on abc:isAllow values i need to pick contextRef="con1" or contextRef="con1".
select
case extractValue(xmlfile ,'//abc:isAllow', 'xxx:bac="http://www.abc.com/abc"')
when 'true' then extractValue(xmlfile ,'//abc:tab1[@contextRef="con1"]', 'xxx:bac="http://www.abc.com/abc"')
else extractValue(xmlfile ,'//*abc:tab1*[@contextRef="*con2*"]', 'xxx:bac="http://www.abc.com/abc"')
end as tab1,
case extractValue(xmlfile ,'//abc:isAllow', 'xxx:bac="http://www.abc.com/abc"')
when 'true' then extractValue(xmlfile ,'//abc:tab2[@contextRef="con1"]', 'xxx:bac="http://www.abc.com/abc"')
else extractValue(xmlfile ,'//abc:tab2*[@contextRef="con2"]', 'xxx:bac="http://www.abc.com/abc"')
end as tab2,
case extractValue(xmlfile ,'//abc:isAllow', 'xxx:bac="http://www.abc.com/abc"')
when 'true' then extractValue(xmlfile ,'//*abc:tab3*[@contextRef="con1"]', 'xxx:bac="http://www.abc.com/abc"')
else extractValue(xmlfile ,'//abc:tab3[@contextRef="con2"]', 'xxx:bac="http://www.abc.com/abc"')
end as tab3
from xml_tableI think , above query might not be optimized because "case when" part will ready abc:isAllow for each tag. and my actual xml is containing more than 200 tag. Any one suggest good way to handle this query.
Regards,
thees_k.TrySELECT XMLTYPE.GetClobVal
(XMLELEMENT
("variable",
XMLAttributes('vcInternationalDate[]' AS "type"),
XMLAGG(XMLELEMENT("item",
CASE
WHEN TEMPO IS NOT NULL
THEN XMLELEMENT("utc", TO_CHAR(TIME, 'dd/MM/yyyy HH24:MI:SS'))
END),
XMLELEMENT("timezone_offSet", TIMEZONE)))) AS "CREATIONDATE"
FROM twgenericosdb.TEST
WHERE ID = 1You could replace CASE with NVL2SELECT XMLTYPE.GetClobVal
(XMLELEMENT("variable",
XMLAttributes('vcInternationalDate[]' AS "type"),
XMLAGG(XMLELEMENT("item",
NVL2(TEMPO,
XMLELEMENT("utc", TO_CHAR(TIME, 'dd/MM/yyyy HH24:MI:SS')),
NULL),
XMLELEMENT("timezone_offSet", TIMEZONE))))) AS "CREATIONDATE"
FROM twgenericosdb.TEST
WHERE ID = 1Urs
Edited by: metzguar on 06.05.2010 15:04 -
How to convert the compund case statement into decode statement
(CASE
WHEN FRCST = 0 AND SALE = 0 THEN 'No transaction '
WHEN FRCST = 0 AND SALE <>0 THEN 'Sale ag. Nil Forecast : '||SALE||' Kgs'
WHEN FRCST<> 0 AND SALE = 0 THEN 'No Sale ag. Forecast : '||FRCST||' Kgs'
WHEN FRCST<>0 AND SALE<>0 AND DIFF=0 THEN 'No Variance'
ELSE TO_CHAR(ROUND((DIFF/FRCST),2))||'%'
END)VARIANCE
How to convert this tatement to decode statement ?
YogeshDecode(FRCST,0,DECODE(SALE,0,'nO TRANSACTION','SALE AGAINST NIL FORECAST'),DECODE(SALE,0,'NO SALE AGAINST FORECAST',
DECODE(|SALE-FORECAST|,0,'NO VARIANCE',TO_CHAR(ROUND((DIFF/FRCST),2))||'%')))As per me whole case can be replaced by above decode -
CASE statement (or similar functionality) in interactive report?
Hello,
I've written a report based on an anonymous block of PL/SQL that allows me to show a different colored icon on the report based on the value of one of the columns - show green if value is less than x, show yellow if value is between x and y, and show red if value is greater than y.
Here is the code block:
for i in (select proj_id, proj_name,
CASE
WHEN proj_cost < 10 THEN '<img src="#APP_IMAGES#green-circle.jpg">'
WHEN proj_cost > 10 and proj_cost <15 THEN '<img src="#APP_IMAGES#yellow-circle.jpg">'
WHEN proj_cost > 15 THEN '<img src="#APP_IMAGES#red-circle.jpg">'
ELSE NULL
END proj_cost
from project)
loop
htp.p('<p>' || i.proj_id || ', ' || i.proj_name || i.proj_cost ||'</p>');
end loop;
Can I do something similar with an interactive report? I want the flexibility of the interactive report but the ability to still include this customer requirement in the report.
Thanks!
-melissaHi,
You can use your select as interactive report region source
select proj_id,
proj_name,
CASE
WHEN proj_cost < 10 THEN '<img src="#APP_IMAGES#green-circle.jpg">'
WHEN proj_cost > 10 and proj_cost <15 THEN '<img src="#APP_IMAGES#yellow-circle.jpg">'
WHEN proj_cost > 15 THEN '<img src="#APP_IMAGES#red-circle.jpg">'
ELSE NULL
END proj_cost
from projecIt should work fine
Just make sure that column where is image type is "Standard report column".
If it is "Display as text" it will not show HTML
Br,JAri
Edited by: jarola on Mar 16, 2010 4:18 PM
for substitution sting APP_IMAGES you need probably use &APP_IMAGES. instead of #APP_IMAGES#
Other vise it should be fine -
Error while replacing IF statements with DECODE function in procedure
Hi All,
I have created a procedure which has nested IF statements. Now I want to replace the IF statements with DECODE functions to improve performance.
Procedure:
IF (var_int_sev = '0')
THEN
var_sev := '2';
ELSE
SELECT sev
INTO var_int_sev
FROM errorconfig
WHERE errorcode = var_errorcode;
var_sev := var_int_sev;
END IF;
I converted the above IF statement into DECODE function as mentioned below:
var_Sev := DECODE(var_int_sev,0,2,SELECT severity FROM errorconfig WHERE errorcode=var_ErrorCode)
But it throws below error at the select statement used inside DECODE.
Error(58,51): PLS-00103: Encountered the symbol "SELECT" when expecting one of the following: ( - + case mod new not null others <an identifier> <a double-quoted delimited-identifier> <a bind variable> avg count current exists max min prior sql stddev sum variance execute forall merge time timestamp interval date <a string literal with character set specification> <a number> <a single-quoted SQL string> pipe <an alternatively-quoted string literal with character set specification> <an alternativ
Can someone help me in converting the IF to DECODE in the above case. Also how can we use a select statement inside decode.instead of trying to rewrite all your code and hoping that the performance will be better, it's a better option to investigate and find out which part of your application is slow
read this:
When your query takes too long ... -
Count Distinct Wtih CASE Statement - Does not follow aggregation path
All,
I have a fact table, a day aggregate and a month aggregate. I have a time hierarchy and the month aggregate is set to the month level, the day aggregate is set to the day level within the time hierarchy.
When using any measures and a field from my time dimension .. the appropriate aggregate is chosen, ie month & activity count .. month aggregate is used. Day & activity count .. day aggregate is used.
However - when I use the count distinct aggregate rule .. the request always uses the lowest common denominator. The way I have found to get this to work is to use a logical table source override in the aggregation tab. Once I do this .. it does use the aggregates correctly.
A few questions
1. Is this the correct way to use aggregate navigation for the count distinct aggregation rule (using the source override option)? If yes, why is this necessary for count distinct .. what is special about it?
2. The main problem I have now is that I need to create a simple count measure that has a CASE statement in it. The only way I see to do this is to select the Based on Dimensions checkbox which then allows me to add a CASE statement into my count distinct clause. But now the aggregation issue comes back into play and I can't do the logical table source override when the based on dimensions checkbox is checked .. so I am now stuck .. any help is appreciated.
KOk - I found a workaround (and maybe the preferred solution for my particular issue), which is - Using a CASE Statement with a COUNT DISTINCT aggregation and still havine AGGREGATE AWARENESS
To get all three of the requirements above to work I had to do the following:
- Create the COUNT DISTINCT as normal (counting on a USERID physically mapped column in my case)
- Now I need to map my fact and aggregates to this column. This is where I got the case statement to work. Instead of trying to put the case statement inside of the Aggregate definition by using the checkbox 'Base on Dimension' (which didnt allow for aggregate awareness for some reason) .. I instead specified the case statement in the Column Mapping section of the Fact and Aggregate tables.
- Once all the LTS's (facts and aggregates) are mapped .. you still have to define the Logical Table Source overrides in the aggregate tab of the count distinct definition. Add in all the fact and aggregates.
Now the measure will use my month aggregate when i specify month, the day aggregate when i specify day, etc..
If you are just trying to use a Count Distinct (no CASE satement needed) with Aggregate Awareness, you just need to use the Logical Table Source override on the aggregate tab.
There is still a funky issue when using the COUNT aggregate type. As long as you dont map multiple logical table sources to the COUNT column it works fine and as expected. But, if you try to add in multiple sources and aggregate awareness it randomly starts SUMMING everything .. very weird. The blog in this thread says to check the 'Based on Dimension' checkbox to fix the problem but that did not work for me. Still not sure what to do on this one .. but its not currently causing me a problem so I will ignore for now ;)
Thanks for all the help
K -
How to turn a stored procedure with a parameter into table function?
Could someone please let me know how to turn the SP below into table-value function? I want to be able to run this function by using SELECT statements with the parameter. Thanks
CREATE
PROCEDURE
[dbo].[Transformation](@year
varchar(4))
AS
BEGIN
Declare@Q1
Varchar(100)=
'['+@year+'Q1'+']'
Declare@Q2
Varchar(100)=
'['+@year+'Q2'+']'
Declare@Q3
Varchar(100)=
'['+@year+'Q3'+']'
Declare@Q4
Varchar(100)=
'['+@year+'Q4'+']'
Declare@StrQuery
Varchar(1000)
Set@StrQuery
= 'Select Date, Job, [Cost Elements],Units,
'+@Q1+'+'+'+'+@Q2+'+'+'+'+@Q3+'+'+'+'+@Q4+'
as [Amounts], ''Update'' as [Description] From Export with (nolock)'
--Print @StrQuery
Exec(@StrQuery)
ENDYou cannot use dynamic SQL in user-defined functions.
Work around (not an ideal solution, it has problems): OPENQUERY.
Blog: http://www.sqlusa.com/bestpractices2005/selectfromsproc/
Kalman Toth Database & OLAP Architect
SQL Server 2014 Design & Programming
New Book / Kindle: Exam 70-461 Bootcamp: Querying Microsoft SQL Server 2012 -
Turn a procedure into a Function?
I've got a procedure that generates a random 4 digit pin as per my unique requirements. I'd like to turn it into a function so that I could call it in an updated statement to update rows in a table with a random pin number.
Would it be possible to turn this into a function? Never written one before and could use a steer please.
CREATE OR REPLACE PROCEDURE TEST.scr_pin_generator
IS
v_candidate_pin NUMBER (4);
v_pin_1 NUMBER (1);
v_pin_2 NUMBER (1);
v_pin_3 NUMBER (1);
v_pin_4 NUMBER (1);
v_pin_count NUMBER := 0;
v_done CHAR(1) := 'N';
c_no_of_pins_reqd NUMBER := 200000;
BEGIN
WHILE v_done = 'N'
LOOP
v_candidate_pin := ROUND (DBMS_RANDOM.VALUE (1, 9999));
IF v_candidate_pin < 1000
THEN
-- dbms_output.put_line('Reject1='||to_char(v_candidate_pin));
GOTO end_loop;
END IF;
v_pin_1 := SUBSTR (v_candidate_pin, 1, 1);
v_pin_2 := SUBSTR (v_candidate_pin, 2, 1);
v_pin_3 := SUBSTR (v_candidate_pin, 3, 1);
v_pin_4 := SUBSTR (v_candidate_pin, 4, 1);
/* avoid all numbers the same */
IF v_pin_1 = v_pin_2
THEN
-- dbms_output.put_line('Reject2='||to_char(v_candidate_pin));
GOTO end_loop;
END IF;
/* avoid consecutive up */
IF v_pin_2 = v_pin_1 + 1 AND v_pin_3 = v_pin_2 + 1
THEN
-- dbms_output.put_line('Reject3='||to_char(v_candidate_pin));
GOTO end_loop;
END IF;
/* avoid consecutive down */
IF v_pin_2 = v_pin_1 - 1 AND v_pin_3 = v_pin_2 - 1
THEN
-- dbms_output.put_line('Reject4='||to_char(v_candidate_pin));
GOTO end_loop;
END IF;
v_pin_count := v_pin_count + 1;
INSERT INTO random_test
VALUES (v_candidate_pin);
--dbms_output.put_line('Number='||to_char(v_candidate_pin));
<<end_loop>>
IF v_pin_count = c_no_of_pins_reqd
THEN
v_done := 'Y';
END IF;
END LOOP;
COMMIT;
END;
/I think something like this will give you what you want.
SQL> create table t as select object_name from dba_objects where rownum < 101;
Table created.
SQL> alter table t add pin number(4);
Table altered.
SQL> update t set pin = floor(dbms_random.value(1000, 9999));
100 rows updated.
SQL> select * from t;
OBJECT_NAME PIN
ICOL$ 4432
I_USER1 2994
CON$ 7600
UNDO$ 1970
C_COBJ# 3502
I_OBJ# 1052
PROXY_ROLE_DATA$ 7310
I_IND1 1318
I_CDEF2 8377
I_PROXY_ROLE_DATA$_1 6997
FILE$ 4116
UET$ 7381
I_FILE#_BLOCK# 8885
I_FILE1 6456
. -
SQL Expression in decode function or case statement?
Can I put SQL expressions in decode function or case statement?
For example,
select le.profile, decode( select count(1) from profile_data where NAME= 'XXXX_AFTER' and object_id = le.profile, 0, 'N', 'Y')
from element le;
or
select le.profile, case WHEN ( select count(1) from profile_data where NAME= 'XXXX_AFTER' and object_id = le.profile) = 0 THEN 'N'
ELSE 'Y'
from element le;
None of the above work.
Can anyone tell me how to make it work?
Is there any workaround?
Thanks,
JYou simply needed and END to your CASE statement;
SQL> with profile_data as (
select 'XXXX_AFTER' name, 1 object_id from dual),
element as (
select 1 profile from dual union all
select 2 from dual)
select le.profile,
case WHEN ( select count(1) from profile_data where NAME= 'XXXX_AFTER' and object_id = le.profile) = 0
THEN 'N'
ELSE 'Y'
END new_col
from element le
PROFILE N
1 Y
2 N -
Using a scalar user defined function in a select case statement
I have a simple select statement below and I want to have a case statement for some conditions based on the result of the udf returned value. I then want the returned value from that specific case statement to be returned where i have indicated 'DISPLAY
ZIPCODE' below.
SELECT
CASE
WHEN (SELECT Top 1 ZipCode FROM ufn_GetAddressByBusinessEntityIDandAddressTypeID(table1.BusinessEntityID,712) IS NOT NULL THEN 'DISPLAY ZIPCODE'
WHEN (SELECT Top 1 ZipCode FROM ufn_GetAddressByBusinessEntityIDandAddressTypeID(table1.BusinessEntityID,714) as r) IS NOT NULL THEN 'DISPLAY ZIPCODE'
ELSE NULL
END as Zipcode,
FROM
table1SELECT COALESCE(ufn_GetAddressByBusinessEntityIDandAddressTypeID(table1.BusinessEntityID,712),ufn_GetAddressByBusinessEntityIDandAddressTypeID(table1.BusinessEntityID,712)) AS Zipcode
FROM table1
Nope. This is two function calls. coalesce(a, b, c, ...) is just syntatic sugar for
CASE WHEN a IS NOT NULL THEN a
WHEN b IS NOT NULL THEN b
WHEN c IS NOT NULL THEN c
END
But if you use isnull it's a different matter. (But isnull() permits two arguments.)
Erland Sommarskog, SQL Server MVP, [email protected] -
Problem in using aggregate functions inside case statement
Hi All,
I am facing problem while using aggregate functions inside case statement.
CASE WHEN PSTYPE='S' THEN MAX(DECODE(POS.PBS,1,ABS(POS.PPRTQ),0)) ELSE SUM(DECODE(POS.PBS,1,ABS(POS.PPRTQ),0)) END,
how can I achieve above requirement ? Con anyone help me.
Thanks and Regards
DGHi All,
Below is my query:
SELECT
CASE WHEN p_reportid IN ('POS_RV_SN','POS_PB') THEN POS.PACCT
ELSE POS.PACCT || '-' || DECODE(POS.SYSTEMCODE,'GMI1','1', 'GMI2','2', 'GMI3','4', 'GMI4','3', '0') ||POS.PFIRM|| NVL(POS.POFFIC,'000') END,
CASE WHEN p_reportid IN ('POS_RV_SN','POS_PB') THEN POS.PACCT||POS.PCUSIP||DECODE(POS.PBS,1,'+',2,'-')
ELSE POS.PFIRM||POS.POFFIC||POS.PACCT||POS.PCUSIP||DECODE(POS.PBS,1,'+',2,'-') END,POS.SYSTEMCODE,CASE WHEN POS.PSTYPE='S' THEN POS.PSYMBL ELSE POS.PFC END,POS.PEXCH||DECODE(POS.PSUBEX,'<NULL>',''),
POS.PCURSY,
CASE WHEN POS.PSBCUS IS NULL THEN SUBSTR(POS.PCTYM,5,2) || SUBSTR(POS.PCTYM,1,4) ELSE POS.PSBCUS || SUBSTR(POS.PCTYM,5,2) || SUBSTR(POS.PCTYM,1,4) END ,
NVL(POS.PSUBTY,'F') ,POS.PSTRIK,*SUM(DECODE(POS.PBS,1,ABS(POS.PPRTQ),0)) ,SUM(DECODE(POS.PBS,2,ABS(POS.PPRTQ),0))* ,
POS.PCLOSE,SUM(POS.PMKVAL) ,
TO_CHAR(CASE WHEN INSTR(POS.PUNDCP,'.') > 0 OR LENGTH(POS.PUNDCP) < 15 THEN POS.PUNDCP ELSE TO_CHAR(TO_NUMBER(POS.PUNDCP) / 100000000) END),
POS.UBS_ID,POS.BBG_EXCHANGE_CODE,POS.BBG_TICKER ,POS.BBG_YELLOW_KEY,POS.PPCNTY,POS.PMULTF,TO_CHAR(POS.BUSINESS_DATE,'YYYYMMDD'),
POS.SOURCE_GMI_LIB,
--DECODE(POS.SYSTEMCODE,'GMI1','euro','GMI2','namr','GMI3','aust','GMI4','asia','POWERBASE','aust','SINACOR','namr',POS.SYSTEMCODE),
DECODE(p_reportid,'RVPOS_SING','euro','RVPOS_AUSTDOM','aust','RVPOS_AUSTEOD','euro','RVPOS_GLBLAPAC','asia','POS_RV_SN','namr','POS_PB','aust',POS.SYSTEMCODE),
POS.RIC,
CASE WHEN PSUBTY = 'S' THEN POS.TYPE ELSE NULL END,
DECODE(POS.UBS_ID,NULL,POS.PCUSP2,POS.ISIN),POS.UNDERLYING_BBG_TICKER,POS.UNDERLYING_BBG_EXCHANGE,POS.PRODUCT_CLASSIFICATION,
CASE WHEN PSUBTY = 'S' THEN POS.PSDSC2 ELSE NULL END,
CASE WHEN PSUBTY = 'S' THEN C.SSDSC3 ELSE NULL END,
NVL(C.SSECID,POS.PCUSIP),
NULL,
POS.PYSTMV,
POS.PMINIT,
POS.PEXPDT,
CASE WHEN POS.PSUBTY='S' THEN SUBSTR(C.ZDATA2,77,1) ELSE NULL END,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL
FROM POSITIONS_WRK POS LEFT OUTER JOIN
(SELECT * FROM CDS_PRODUCTS CP INNER JOIN FUTURE_MASTER FM ON
(CP.STRXCH=FM.ZEXCH AND CP.SFC=FM.ZFC AND CP.BUSINESS_DATE = FM.BUSINESS_DATE )) C ON POS.PCUSIP = C.SCUSIP
AND NVL(POS.PCUSP2,'X') = NVL(C.SCUSP2,'X')
WHERE
POS.PEXCH NOT IN ('A1','A2','A3','B1','B3','C2','D1','H1','K1','L1','M1','M3','P1','S1')
AND (POS.PSBCUS IS NOT NULL OR POS.PCTYM IS NOT NULL OR POS.PSTYPE ='S')
AND POS.BUSINESS_DATE = run_date_char
GROUP BY
POS.UBS_ID,POS.SYSTEMCODE,POS.RECIPIENTCODE,POS.BUSINESS_DATE,POS.PACCT,POS.PFIRM,POS.POFFIC,POS.PCUSIP,POS.PBS,CASE WHEN POS.PSTYPE='S' THEN POS.PSYMBL ELSE POS.PFC END,
POS.PEXCH,POS.PSUBEX,POS.PCURSY,
CASE WHEN POS.PSBCUS IS NULL THEN SUBSTR(POS.PCTYM,5,2) || SUBSTR(POS.PCTYM,1,4) ELSE POS.PSBCUS || SUBSTR(POS.PCTYM,5,2) || SUBSTR(POS.PCTYM,1,4) END,
NVL(POS.PSUBTY,'F') ,POS.PSTRIK,POS.PCLOSE,TO_CHAR(CASE WHEN INSTR(POS.PUNDCP,'.') > 0 OR LENGTH(POS.PUNDCP) < 15 THEN POS.PUNDCP ELSE TO_CHAR(TO_NUMBER(POS.PUNDCP) / 100000000) END),
POS.BBG_EXCHANGE_CODE,POS.BBG_TICKER,POS.BBG_YELLOW_KEY,POS.PPCNTY,POS.PMULTF,POS.PSUBTY,POS.SOURCE_GMI_LIB,RIC,
CASE WHEN PSUBTY = 'S' THEN POS.TYPE ELSE NULL END,
DECODE(POS.UBS_ID,NULL,POS.PCUSP2,POS.ISIN),POS.UNDERLYING_BBG_TICKER,POS.UNDERLYING_BBG_EXCHANGE,POS.PRODUCT_CLASSIFICATION,
CASE WHEN PSUBTY = 'S' THEN POS.PSDSC2 ELSE NULL END,
CASE WHEN PSUBTY = 'S' THEN C.SSDSC3 ELSE NULL END,
NVL(C.SSECID,POS.PCUSIP),
POS.PYSTMV,
POS.PMINIT,
POS.PEXPDT,
CASE WHEN PSUBTY = 'S' THEN SUBSTR(C.ZDATA2,77,1) ELSE NULL END;Now, could you plz help me in replacing the bold text in the query with the requirement.
Thanks and Rgds
DG
Edited by: BluShadow on 16-May-2011 09:39
added {noformat}{noformat} tags. Please read: {message:id=9360002} for details on how to post code/data
Maybe you are looking for
-
LG Ally text message memory full
I have had this phone for a little over a month now and I get the message "text memory full" all the time. I have 2 conversations open all the time and I clear them once a week. Other than that I don't have tons of messages. I looked online and it sa
-
I am using the sax parser provided by the package javax.xml.parsers to parse an XML file. It works fine as long as I have an XML file which has English characters. When I use it for parsing a file which has Korean characters in it, the parser fails t
-
Cannot install on Vista...
Install gets thru about 80% then get following error and the installation reverses on closes. An error occured during the installation of assembly 'Microsoft.VC80.CRT,publicKeyToken= "1fc8b3b9a1e18e3b",type="win32",version="8.0.50727.762", processorA
-
adobe captivate 8, When displaying the application in Thai language, the tier-3 symbols are not displayed.
-
Configuration error:16 CS5.5 Design Standard on Mac
Hi I have just encountered this configuration error:16. I bought the software in Sept 2011. I transferred it from my iMac to a new Macbook Pro in Nov 2012. It has been working fine up until now. Please help - I have URGENT deadlines to meet!