If then else in update query
Hello,
I was hoping anyone could provide ideas on the best way to do an update query based on an if then else statement I am using Oracle 11 on a linux server. I am writing within a perl script. I've researched online and saw some examples using case. Below is the basic query logic I am trying to implement. I would really appreciate any suggestions.
Thanks,
JC
If the MAINT_CENTER IN ('ENOC1CENTER','PMCTGAAHSDC','ATTCSPCRT01','ATTCSPCWS01','NTNLWHS4NSA') AND CAC1=’S’ and substring(CKT_ID,4,2) IN ('KQ','KR','KS','KP','L1','L2','L3','VL') and askme_temp.CKT_ID = heci.CKT_ID then SUBPRODUCT =’IPAG’
ELSE If the MAINT_CENTER IN ('ENOC1CENTER','PMCTGAAHSDC','ATTCSPCRT01','ATTCSPCWS01','NTNLWHS4NSA') AND CAC1=’S’ and substring(CKT_ID,4,2) IN ('KQ','KR','KS','KP','L1','L2','L3','VL') AND REGION=’SE’ then SUBPRODUCT =’METRO_E’
ELSE If the MAINT_CENTER IN ('ENOC1CENTER','PMCTGAAHSDC','ATTCSPCRT01','ATTCSPCWS01','NTNLWHS4NSA') AND CAC1=’S’ and substring(CKT_ID,4,2) IN ('KQ','KR','KS','KP','L1','L2','L3','VL') then SUBPRODUCT =’OPT_E_MAN’
Hi,
Welcome to the forum!
CASE sounds like a good idea to me.
For example:
UPDATE table_x
SET subproduct = CASE
WHEN askme_temp.CKT_ID = heci.CKT_ID
THEN 'IPAG'
WHEN region = 'SE'
THEN 'METRO_E'
ELSE 'OPT_E_MAN'
END
WHERE maint_center IN ( 'ENOC1CENTER'
, 'PMCTGAAHSDC'
, 'ATTCSPCRT01'
, 'ATTCSPCWS01'
, 'NTNLWHS4NSA'
AND cac1 = 'S'
AND SUBST (ckt_id, 4, 2) IN ('KQ', 'KR', 'KS', 'KP', 'L1', 'L2', 'L3', 'VL')
AND ...
;CASE expressions are evaluated in the order in which you write them, so if askme_temp.ckt_id = heci.ckt_id (whatever those things are), subproduct will be set to 'IPAG'. It won't matter whether region is 'METRO_E' or not; if the 1st condition is TRUE, the first THEN value is returned, and the other WHEN expressions aren't even evaluated.
What do you want to do if none of those conditions are met?
Any conditions that are common to all the rows being UPDATEd can be put in the WHERE clause; they don't have to be repeated in the CASE expression.
Remember, MERGE is often more convenient to use than UPDATE.
Edited by: Frank Kulash on Jul 27, 2011 3:23 PM
Similar Messages
-
How to write IF-THEN-ELSE in query (syntx)
Dear Experts,
As the decode syntx is Oracel's, is there any syntx could be used for IF-THen-Else function in query generator?
Thanks.
EmilyMorning, Gouri,
It works!! Thanks very much!
BTW, in Inventory menu, the report 'Inventory Posting List, does it pull data from table 'OINM' ?
It looks like OINM does not link with tables of ODLN (PL/delivery) and OPOR (PO), is it correct?
If I would like link OINM to ODLN and OPOR, which table interrelated between them??
Pls kinldy asdvise.
Thanks in advance.
Emily -
Charactersitic values to be used in IFTHEN ELSE STATEMENT IN QUERY
scenario: i need to use the characteristic values(not the attributes) to be used in an IF THEN ELSE STATEMENT in query. so i created a formula variable for the characteritic of processing type replacement path, replace with key.The values are not fetched in the result and is displayed as X.
what should i replace with key,lable, constant or other options whereas my requirement is the all the values present in the characteristc should be used.
eg. if char name is xyz and has the values 1,2,3,4,5 till -
20.
then in a calculated key figure :(formulavariable =1)* kefig1keyfig2 +not(formulavariable =1)kef2keyfig3.
this formula variable should have all the values of the characteristic values ie 1,2,3---20.
2. how should i do get the values of characterstics values in the equation give me the steps in detail..
3. i do not want to use the attributes, though i tried initally while creating the formual variable i replaced with attribute value, there is was an error and there were no reult.
i tried to create char. variable for the characteristic of manual entr , not ready for input values and gave all the values 1,2,3 --20 as default values and then created formaul variable and repalce with the variable, however this characteristic variable is not at all displayed from the list of variables which will be displayed while creating the formula variable.
help me out.
Thankshi srini,
i have includedthe char in rows. i want you to explain in detail how to use these values in the if then else statement in query.
i have created a calculated key figure 2= (formual variable =1 & keyfig a =0)* keyfig1kefig2 +not(formual variable =1 & keyfig a =0)keyfig2 *calculated keyfig1.
so this formula variable of replacement path have ref. to then char. and with what value should it replace, key, name, external char or attribut etc so that i should get the values of the char from 1 to20.
i donot to repalce with the attribute. i just want the char. values and not thier attributes (1. description 2. the second attribute has the values say abc1,efg2,ghi3 for respective charteristic values.
ie
char value desc 2nd attrib
1 hi abc1
2 bye defg2
3 ciao ghi3 -
After Insert Trigger - IF-THEN-ELSE
Is it possible to put an if-then-else statement in an after insert trigger with an update to a second table?
CREATE OR REPLACE trigger bev_trg
after insert
on bev
for each row
DECLARE
MEINS VARCHAR2(3);
SPART VARCHAR2(2);
FKIMG NUMBER(22);
SHKZG CHAR(1);
BEGIN
insert into bev2
(vbeln,
posnr)
values
(:new.vbeln,
:new.posnr
IF FKIMG = '10' and MEINS = 'EA'
THEN
update bev2 set bwsie = (fkimg * '12.17') ;
ELSIF
FKIMG = '12' and MEINS = 'EA'
THEN
update bev2 set bwsie = (fkimg * '19.02');
ELSIF
SHKZG = 'X'
THEN
update bev2 set bwsie = (fkimg * '-1');
ELSE
update bev2 set bwsie = '0' ;
END IF;
update bev2 set bwfkimg = (fkimg * '-1') where SHKZG = 'X';
end;
This does not do the updates.
Thanks
BevMy original problem is this: I need to create a table
derived from data in another table
and change it to be the conditional data in the update statements.
create table bev(
VBELN VARCHAR2(10),
POSNR VARCHAR2(6),
MEINS VARCHAR2(3),
SPART VARCHAR2(2),
FKIMG NUMBER(22),
SHKZG CHAR(1),
BWSIE NUMBER(9,2),
BWFKIMG NUMBER(22)
update bev set bwsie = (fkimg * '12.17') where SPART = '10' and meins = 'EA' ;
update bev set bwsie = (fkimg * '19.02') where SPART = '12' and meins = 'EA';
update bev set bwsie = (fkimg * '27.39') where SPART = '15' and meins = 'EA';
update bev set bwsie = (fkimg * '48.69') where SPART = '20' and meins = 'EA';
update bev set bwsie = (fkimg * '109.56') where SPART = '30' and meins = 'EA';
update bev set bwsie = '0' where meins = 'EA' and SPART not in('10','12','15','20','30');
update bev set bwsie = (fkimg * '-1') where SHKZG = 'X';
update bev set bwfkimg = (fkimg * '-1') where SHKZG = 'X';
This did not produce the required results so I thought I would try
creating a second table
and using a trigger with if-then-else to update it.
Can't use the trigger on the
original table because it mutates.
create table bev2(
VBELN VARCHAR2(10),
POSNR VARCHAR2(6),
BWSIE NUMBER(9,2),
BWFKIMG NUMBER(22)
insert into bev select vbeln, posnr, meins, spart, fkimg , shkzg, '', ''
from [email protected]
where vbeln = '0090043834' and posnr = '000011'
insert into bev select vbeln, posnr, meins, spart, fkimg , shkzg, '', ''
from [email protected]
where vbeln = '0090043833' and posnr = '000011'
CREATE OR REPLACE trigger bev_trg
after insert
on bev
for each row
DECLARE
MEINS VARCHAR2(3);
SPART VARCHAR2(2);
FKIMG NUMBER(22);
BEGIN
insert into bev2
(vbeln,
posnr,
fkimg
values
(:new.vbeln,
:new.posnr,
:new.fkimg
IF :new.FKIMG = '10' and :new.MEINS = 'EA'
THEN
update bev2 set bwsie = (:new.fkimg * '12.17') ;
ELSIF
:new.FKIMG = '12' and :new.MEINS = 'EA'
THEN
update bev2 set bwsie = (:new.fkimg * '19.02');
ELSIF
:new.FKIMG = '15' and :new.MEINS = 'EA'
THEN
update bev2 set bwsie = (:new.fkimg * '27.39');
ELSIF
:new.FKIMG = '20' and :new.MEINS = 'EA'
THEN
update bev2 set bwsie = (:new.fkimg * '48.69');
ELSIF
:new.FKIMG = '30' and :new.MEINS = 'EA'
THEN
update bev2 set bwsie = (:new.fkimg * '109.56');
ELSIF
SHKZG = 'X'
THEN
update bev2 set bwsie = (:new.fkimg * '-1');
ELSE
update bev2 set bwsie = '0' ;
END IF;
update bev2 set bwfkimg = (:new.fkimg * '-1') where SHKZG = 'X';
end; -
Can a user input query in WFA have IF THEN ELSE
Below is my query and when I save it WFA throws the following error.Illegal user input query 'IF '${vfilerName}' != 'vfiler0' THEN
SELECT
vol.name,
array.ip AS 'array.ip'
FROM
storage.vfiler AS vfl,
storage.volume AS vol,
storage.array AS array
WHERE
vol.vfiler_id = vfl.id... HERE is my actual query. IS an IF THEN ELSE supported or I am doing something wrong.... IF '${vfilerName}' != 'vfiler0' THEN
SELECT
vol.name,
array.ip AS 'array.ip'
FROM
storage.vfiler AS vfl,
storage.volume AS vol,
storage.array AS array
WHERE
vol.vfiler_id = vfl.id
AND vfl.name = '${vfilerName}'
AND vol.array_id = array.id
AND (
array.ip = '${arrayName}'
OR array.name = '${arrayName}'
AND vol.name = '${volName}'
ORDER BY
vol.name DESC
ELSE
SELECT
vol.name AS 'name',
array.ip AS 'array.ip',
array.name AS 'array.name'
FROM
storage.volume AS vol
JOIN
storage.array AS array
ON vol.array_id = array.id
WHERE
array.ip = '${arrayName}'
OR array.name = '${arrayName}'
END IFYes you can use IF, but you cannot use Select ..... IF.... Select... ELSE.... SELECT... . It's not a valid SQL statement. If you want many SELECT statements you should use UNION but most of the time you won't need it. I've create a query that uses and it may help you. Take a look at the way I use IF. SELECT
export_policy.name 'Nome das políticas',
GROUP_CONCAT(if(rw_rule='sys'
OR rw_rule='any',
export_rule.clientmatch,
null)) 'REGRAS RW',
GROUP_CONCAT(if((ro_rule='sys'
OR ro_rule='any')
AND rw_rule='none',
export_rule.clientmatch,
null)) 'Regras RO'
FROM
cm_storage.export_policy
INNER JOIN
cm_storage.export_rule
ON export_policy.id=export_rule.policy_id
JOIN
cm_storage.vserver
ON export_policy.vserver_id=vserver.id
WHERE
vserver.name='${VserverName}'
AND export_policy.name!='default'
GROUP BY
export_policy.name You can have some reference of IF usage here: https://dev.mysql.com/doc/refman/5.1/en/control-flow-functions.html#function_if -
Query if-then-else logic with calculation
Hello,
I want to calculate within a BEX-formula.
I have two key-figures:
- Quantity
- Value
The logic should be like this:
IF Value > 0 THEN Value / Quantity ELSE 0
( / means: divided)
How can I reach this?
The URL
http://help.sap.com/saphelp_nw70ehp1/helpdata/de/e3/e60138fede083de10000009b38f8cf/frameset.htm
does not help me.
Thanks for your help,
ThomasThat is the way to perform if then else...
As long as boolean operations returns 0 or 1 you must play with that in order to get the desired result.
In case you have DIV problems you can use this operator:
NDIV0 (x): Is equal to 0 with division by 0, otherwise x.
NDIV(<Expression>)
Delivers 0 if the expression named in <Expression> gives a division by 0 in
the calculation. Otherwise, the result is the value of the expression.
Is used to
- Avoid the output of an error message
- Continue calculating with a defined result
Please give an example if I am missing something.
Regards,
Sebastian,. -
Hi, I want to update status_code of table_2. T_ID is the primary key in both table (Table_1 and table_2). The condition is any person's age >70 then status_code should be 'R' and if person's age<70 then status_code should be 'N'. Please help on this
Update query.
/*Table_1*/
T_ID LASTNAME FIRSTNAME DOB
1001 KAISER SUJIR 01/01/1942
1002 SMITH HUJR 01/01/1948
1003 JOHN JANE 02/01/1958
/*Table_2*/
T_ID LASTNAME FIRSTNAME STATUS_CODE
1001 KAISER SUJIR R
1002 SMITH HUJR R
1003 JOHN JANE R
/*Need the Following Result after the Update*/
T_ID LASTNAME FIRSTNAME STATUS_CODE
1001 KAISER SUJIR R --The Age is >70 that's why status_code is 'R'
1002 SMITH HUJR N --The Age is <70
1003 JOHN JANE N --The Age is <70DECLARE @table1 TABLE (T_ID INT, lastName VARCHAR(30), firstName VARCHAR(30), dob DATE)
INSERT INTO @table1 (T_ID, lastName, firstName, dob) VALUES (1001, 'KAISER', 'SUJIR' ,'01/01/1942'),(1002, 'SMITH', 'HUJR', '01/01/1948'),(1003, 'JOHN', 'JANE', '02/01/1958'),(1004, 'Jack', 'Jackson', '12/03/1944')
DECLARE @table2 TABLE (T_ID INT, lastName VARCHAR(30), firstName VARCHAR(30), statusCode CHAR(1))
INSERT INTO @table2 (T_ID, lastName, firstName, statusCode) VALUES (1001, 'KAISER', 'SUJIR', 'R'),(1002, 'SMITH', 'HUJR', 'R'),(1003, 'JOHN', 'JANE', 'R'),(1004, 'Jack', 'Jackson', 'R')
-- tables set up
UPDATE @table2
SET statusCode = CASE WHEN DATEDIFF(YEAR,t1.dob,CURRENT_TIMESTAMP) - CASE WHEN DATEADD(YEAR,DATEDIFF(YEAR,t1.dob,CURRENT_TIMESTAMP),t1.dob) > CURRENT_TIMESTAMP THEN 1 ELSE 0 END >= 70 THEN 'R' ELSE 'N' END
FROM @table2 t2
INNER JOIN @table1 t1
ON t2.T_ID = t1.T_ID
SELECT *, DATEDIFF(YEAR,t1.dob,CURRENT_TIMESTAMP) - CASE WHEN DATEADD(YEAR,DATEDIFF(YEAR,t1.dob,CURRENT_TIMESTAMP),t1.dob) > CURRENT_TIMESTAMP THEN 1 ELSE 0 END
FROM @table2 t2
INNER JOIN @table1 t1
ON t2.T_ID = t1.T_ID -
my table : workingdate
sno name startdate
1 ss 1-12-2011
2 bb 1-11-2011
I can update name or start date or both .i will pass new date,name to update through front end.
I need to validate the condition in case statement i.e. when the new date passed check whether it is greater then start date. if it is greater then it should update with new start date.
if no then it should be update it will old value.
i using below query
update workingdate set name='sss',startdate=(
case
when
(TO_DATE('2011-12-10','yyyy-MM-dd') > (select TO_DATE(startdate,'yyyy-MM-dd') from workingdate where sno=1))
then TO_DATE('2011-12-10','yyyy-MM-dd')
else
select TO_DATE(start_date,'yyyy-MM-dd') from workingdate where sno=1
end
where sno=1;
but when i execute the above query it shows me
Error report:
SQL Error: ORA-00936: missing expression
00936. 00000 - "missing expression"
*Cause:
*Action:
how could i resolve this.......................Check this out
UPDATE workingdate
SET NAME='sss',
startdate=(CASE WHEN (TO_DATE('2011-12-10','yyyy-MM-dd') > startdate THEN TO_DATE('2011-12-10','yyyy-MM-dd') ELSE start_date END)
WHERE sno=1;Cheers
Kanchana -
This is my update query in oracle but it is giving error:
Update (select NM.Nominal_Amount,NM.Number_of_Units,NM.Current_Spot,NM.Published_Spot,NM.Strike_Price
from note_master NM ,
( select NORM.Note_Master_ID, NORM.Asset, NORM.Currency , 50 as Spot_Price_Calc, NVL(TOADD.NA,0) As NA, NVL(TOADD.NS,0)
As NS, NVL(TOADD.NA_P,0) As NA_P, NVL(TOADD.NS_P,0) As NS_P, NVL(TOADD.SA,0) As SA, (50 * (NORM.Strike_Price_Per/100)) as
rike_Price_Calc, (Case When UPPER(NORM.Misc2) = 'Q' THEN (NORM.No_Of_Shares * 50 * (NORM.Strike_Price_Per/100)) Else
NORM.Nominal_Amount End )as Nominal_Amount_Calc, (Case When UPPER(NORM.Misc2) ='N' THEN (NORM.Nominal_Amount /( 50 * (NORM.Strike_Price_Per/100)))
Else NORM.No_Of_Shares End )as NO_Of_Shares_Calc, (Case When UPPER(NORM.Misc2) = 'Q' THEN (NORM.No_Of_Shares * 50 * (NORM.Strike_Price_Per/100) * NORM.Issue_Price )/100
Else (NORM.Nominal_Amount * NORM.Issue_Price )/100 End )as Settlement_Amt_Calc from ( select Note_Master_Id, MIN(Spot_Price) as Spot_Price, Min(Strike_Price) as
Strike_Price, SUM(Nominal_Amount) as Nominal_Amount, SUM(No_Of_Shares) as No_Of_Shares , MIN(Issue_Price) as Issue_Price, MIN(Asset) as Asset, MIN(Currency) as Currency,
MIN(Strike_Price_Per) as Strike_Price_Per, MIN(Misc2) as Misc2 from ( Select Note_Master_Id, Spot_Price, Strike_Price, Nominal_Amount, No_Of_Shares, Issue_Price, Asset,
Currency , Strike_Price_Per,Misc2 from Sample_ADF_FinIQ_Common.Note_Order_RM Where Order_Status_Flag = 'YYYYYYNNNNNNNNNN' And RO_ID = 'R000000002' ) NORM Group by Note_Master_Id ) NORM
Left Outer JOIN Sample_ADF_FinIQ_Common.RATESSPOTBIDASK RSBA On RSBA.PairCode = (NORM.Asset ) Left Outer JOIN ( select Note_Master_ID,sum(Nominal_Amount)
as NA, sum(No_Of_Shares) as NS, sum(NominalAmt_Pending) as NA_P, sum(NoOfShares_Pending) as NS_P,sum(Settlement_Amt) as SA from Note_Order_RM
Where RO_ID <> 'R000000002' group by Note_Master_ID ) TOADD On TOADD.Note_Master_ID = NORM.Note_Master_ID ) RESULT1 where NM.Note_Master_ID = RESULT1.Note_Master_ID )
set Price_Updated_YN = 'Y' ,
Nominal_Amount = RESULT1.NA + RESULT1.Nominal_Amount_Calc , Number_Of_Units = RESULT1.NS + RESULT1.NO_Of_Shares_Calc ,
Current_Spot = RESULT1.Spot_Price_Calc , Published_Spot = RESULT1.Spot_Price_Calc , Strike_Price = RESULT1.Strike_Price_Calc
where NM.Note_Master_ID = RESULT1.Note_Master_ID;
error :
rror at Command Line:17 Column:105
Error report:
SQL Error: ORA-00904: "RESULT1"."STRIKE_PRICE_CALC": invalid identifier
00904. 00000 - "%s: invalid identifier"
can anybody help.
ThanksStill one more typo problem exists in you sql stament , equal to(=) operator is missing in your original statement look below
original
Where RO_ID 'R000000002' group by Note_Master_ID ) TOADD On TOADD.Note_Master_ID = NORM.Note_Master_ID ) RESULT1 where NM.Note_Master_ID = RESULT1.Note_Master_ID )
set Price_Updated_YN = 'Y'
modified
Where RO_ID='R000000002' group by Note_Master_ID ) TOADD On TOADD.Note_Master_ID = NORM.Note_Master_ID ) RESULT1 where NM.Note_Master_ID = RESULT1.Note_Master_ID )
set Price_Updated_YN = 'Y' Ok, once try with this code, some syntax prob i modified it.
Update (select NM.Nominal_Amount,NM.Number_of_Units,NM.Current_Spot,NM.Published_Spot,NM.Strike_Price
from note_master NM ,
( select NORM.Note_Master_ID, NORM.Asset, NORM.Currency , 50 as Spot_Price_Calc, NVL(TOADD.NA,0) As NA, NVL(TOADD.NS,0)
As NS, NVL(TOADD.NA_P,0) As NA_P, NVL(TOADD.NS_P,0) As NS_P, NVL(TOADD.SA,0) As SA, (50 * (NORM.Strike_Price_Per/100)) as
Strike_Price_Calc, (Case When UPPER(NORM.Misc2) = 'Q' THEN (NORM.No_Of_Shares * 50 * (NORM.Strike_Price_Per/100)) Else
NORM.Nominal_Amount End )as Nominal_Amount_Calc, (Case When UPPER(NORM.Misc2) ='N' THEN (NORM.Nominal_Amount /( 50 * (NORM.Strike_Price_Per/100)))
Else NORM.No_Of_Shares End )as NO_Of_Shares_Calc, (Case When UPPER(NORM.Misc2) = 'Q' THEN (NORM.No_Of_Shares * 50 * (NORM.Strike_Price_Per/100) * NORM.Issue_Price )/100
Else (NORM.Nominal_Amount * NORM.Issue_Price )/100 End )as Settlement_Amt_Calc from ( select Note_Master_Id, MIN(Spot_Price) as Spot_Price, Min(Strike_Price) as
Strike_Price, SUM(Nominal_Amount) as Nominal_Amount, SUM(No_Of_Shares) as No_Of_Shares , MIN(Issue_Price) as Issue_Price, MIN(Asset) as Asset, MIN(Currency) as Currency,
MIN(Strike_Price_Per) as Strike_Price_Per, MIN(Misc2) as Misc2 from ( Select Note_Master_Id, Spot_Price, Strike_Price, Nominal_Amount, No_Of_Shares, Issue_Price, Asset,
Currency , Strike_Price_Per,Misc2 from Sample_ADF_FinIQ_Common.Note_Order_RM Where Order_Status_Flag = 'YYYYYYNNNNNNNNNN' And RO_ID = 'R000000002' ) NORM Group by Note_Master_Id ) NORM
Left Outer JOIN Sample_ADF_FinIQ_Common.RATESSPOTBIDASK RSBA On RSBA.PairCode = (NORM.Asset ) Left Outer JOIN ( select Note_Master_ID,sum(Nominal_Amount)
as NA, sum(No_Of_Shares) as NS, sum(NominalAmt_Pending) as NA_P, sum(NoOfShares_Pending) as NS_P,sum(Settlement_Amt) as SA from Note_Order_RM
Where RO_ID 'R000000002' group by Note_Master_ID ) TOADD On TOADD.Note_Master_ID = NORM.Note_Master_ID ) RESULT1 where NM.Note_Master_ID = RESULT1.Note_Master_ID )
set Price_Updated_YN = 'Y' ,
Nominal_Amount = RESULT1.NA + RESULT1.Nominal_Amount_Calc , Number_Of_Units = RESULT1.NS + RESULT1.NO_Of_Shares_Calc ,
Current_Spot = RESULT1.Spot_Price_Calc , Published_Spot = RESULT1.Spot_Price_Calc , Strike_Price = RESULT1.Strike_Price_Calc
where NM.Note_Master_ID = RESULT1.Note_Master_ID;Edited by: darkStargate on Dec 8, 2011 7:42 PM -
Is there any way we can simplify this update query ?
is there any way we can simplify this update query ? There is nothing wrong with the query ,but it looks so clumsy ...is there any other ways of doing this update like using with clause or exists or any other?
[code]
UPDATE STG_TMP_MBS_POOL s SET s.instrument_id = case when ( (select distinct iai.alternate_id from instrument_alternate_id iai, STG_TMP_MBS_POOL s where s.fi_instrument_id=iai.fi_instrument_id and iai.alternate_id_type_code IN ( 'FMR_CUSIP','CUSIP')) > 1) then (select distinct iai.alternate_id from instrument_alternate_id iai, STG_TMP_MBS_POOL s where s.fi_instrument_id=iai.fi_instrument_id and iai.alternate_id_type_code = 'FMR_CUSIP') else (select distinct iai.alternate_id from instrument_alternate_id iai, STG_TMP_MBS_POOL s where s.fi_instrument_id=iai.fi_instrument_id and iai.alternate_id_type_code IN ('FMR_CUSIP', 'CUSIP')) END;
[\code]update stg_tmp_mbs_pool s
set s.instrument_id = case when (select distinct iai.alternate_id
from instrument_alternate_id iai,
stg_tmp_mbs_pool s
where s.fi_instrument_id = iai.fi_instrument_id
and iai.alternate_id_type_code in ('FMR_CUSIP','CUSIP')
) > 1
then (select distinct iai.alternate_id
from instrument_alternate_id iai,
stg_tmp_mbs_pool s
where s.fi_instrument_id = iai.fi_instrument_id
and iai.alternate_id_type_code = 'FMR_CUSIP'
else (select distinct iai.alternate_id
from instrument_alternate_id iai,
stg_tmp_mbs_pool s
where s.fi_instrument_id = iai.fi_instrument_id
and iai.alternate_id_type_code in ('FMR_CUSIP','CUSIP')
end
Maybe
begin
update stg_tmp_mbs_pool s
set s.instrument_id = (select distinct iai.alternate_id
from instrument_alternate_id iai,
stg_tmp_mbs_pool s
where s.fi_instrument_id = iai.fi_instrument_id
and iai.alternate_id_type_code in ('FMR_CUSIP','CUSIP')
update stg_tmp_mbs_pool s
set s.instrument_id = (select distinct iai.alternate_id
from instrument_alternate_id iai,
stg_tmp_mbs_pool s
where s.fi_instrument_id = iai.fi_instrument_id
and iai.alternate_id_type_code = 'FMR_CUSIP'
where s.instrument_id > 1;
end;
Regards
Etbin -
Update query (or other method) to a typed dataset
Hi
i have created a typed DataSet in code that is created at runtime. It gets populated then it needs to be updated based on 2 paramaters
EmployeeID & AssignmentID
How can i run an update query on the runtime created Dataset? Hee is how i create my Dataset-
Private sGridDataSet As New DataSet("GridDataset")
Private tblGridTable As DataTable
sGridDataSet.CaseSensitive = False
tblGridTable = sGridDataSet.Tables.Add("tblGrid")
With tblGridTable
.Columns.Add("AssignmentID", GetType(System.String))
.Columns.Add("ProjectName", GetType(System.String))
.Columns.Add("Day1", GetType(System.String))
.Columns.Add("Day2", GetType(System.String))
.Columns.Add("Day3", GetType(System.String))
.Columns.Add("Day4", GetType(System.String))
.Columns.Add("Day5", GetType(System.String))
.Columns.Add("Day6", GetType(System.String))
.Columns.Add("Day7", GetType(System.String))
End With
'get data from qryAssignments
sAssignID = Me.AssignmentData.qryAssignments.Rows(j)(1)
sProjName = Me.AssignmentData.qryAssignments.Rows(j)(0)
newValues = {sAssignID, sProjName, Day1, Day2, Day3, Day4, Day5, Day6, Day7}
tblGridTable.Rows.Add(newValues)
Me.QryAssignmentsTableAdapter.ClearBeforeFill = True
Dim sDate As Date = Me.txtDate.Text
Dim EndDate As Date = sDate.AddDays(6)
Me.QryAssignmentTimesTableAdapter.Fill(Me.AssignmentData.qryAssignmentTimes, Me.txtEmployeeID.Text, Me.txtDate.Text, CStr(CType(CStr(EndDate), DateTime)))
Dim p As Integer = 0
For p = 0 To Me.AssignmentData.qryAssignmentTimes.Rows.Count - 1
vDayNo = Weekday(Me.AssignmentData.qryAssignmentTimes.Rows(p)(0), FirstDayOfWeek.Monday)
Dim m As String = Me.AssignmentData.qryAssignmentTimes.Rows(p)(0)
'NEED TO UPDATE DATASET TABLE HERE BASED ON EMPLOYEEID AND ASSIGNMENTID
Next
Me.GridControl1.DataSource = tblGridTable
Hopefully, someone can give me a few pointers :)
Thanks
Nigel
Nacho is the derivative of Nigel &quot;True fact!&quot;Hello,
If I have more than one table to work with, a DataSet would be the container while if one table then no DataSet, just a DataTable. I would use code similar to the following which is for MS-Access yet by changing to SqlClient data provider instead of OelDb
data provider the same methods work.
Taken from
this project.
Module DatabaseOperations
Private Builder As New OleDb.OleDbConnectionStringBuilder With
.Provider = "Microsoft.ACE.OLEDB.12.0",
.DataSource = IO.Path.Combine(Application.StartupPath, "Database1.accdb")
''' <summary>
''' Read USA customers from database into a DataTable
''' </summary>
''' <returns></returns>
''' <remarks>
''' Database is assumed to be in the Bin\Debug folder.
''' </remarks>
Public Function LoadCustomers() As DataTable
Using cn As New OleDb.OleDbConnection With {.ConnectionString = Builder.ConnectionString}
Using cmd As New OleDb.OleDbCommand With {.Connection = cn}
cmd.CommandText =
<SQL>
SELECT
Identifier,
CompanyName,
ContactName,
ContactTitle,
Address,
City,
PostalCode,
Country
FROM Customer;
</SQL>.Value
Dim dt As New DataTable With {.TableName = "Customer"}
Try
cn.Open()
dt.Load(cmd.ExecuteReader)
dt.Columns("Identifier").ColumnMapping = MappingType.Hidden
dt.Columns("Country").ColumnMapping = MappingType.Hidden
Catch ex As Exception
MessageBox.Show("Failed to load customer data. See error message below" & Environment.NewLine & ex.Message)
End Try
dt.AcceptChanges()
Return dt
End Using
End Using
End Function
Public Function RemoveCurrentCustomer(ByVal Identfier As Integer) As Boolean
Try
Using cn As New OleDb.OleDbConnection With {.ConnectionString = Builder.ConnectionString}
Using cmd As New OleDb.OleDbCommand With {.Connection = cn}
cmd.CommandText = "DELETE FROM Customer WHERE Identifier = ?"
Dim IdentifierParameter As New OleDb.OleDbParameter With
.DbType = DbType.Int32,
.ParameterName = "P1",
.Value = Identfier
cmd.Parameters.Add(IdentifierParameter)
Try
cn.Open()
Dim Affected = cmd.ExecuteNonQuery
Return Affected = 1
Catch ex As Exception
Return False
End Try
End Using
End Using
Catch ex As Exception
' Handle or not handle exceptions for failed save operation
Return False
End Try
End Function
Public Function AddNewRow(ByVal Name As String, ByVal Contact As String, ByRef Identfier As Integer) As Boolean
Dim Success As Boolean = True
Try
Using cn As New OleDb.OleDbConnection With {.ConnectionString = Builder.ConnectionString}
Using cmd As New OleDb.OleDbCommand With {.Connection = cn}
cmd.CommandText =
<SQL>
INSERT INTO Customer
CompanyName,
ContactName
Values
@CompanyName,
@ContactName
</SQL>.Value
cmd.Parameters.AddWithValue("@CompanyName", Name)
cmd.Parameters.AddWithValue("@ContactName", Contact)
cn.Open()
cmd.ExecuteNonQuery()
cmd.CommandText = "Select @@Identity"
Identfier = CInt(cmd.ExecuteScalar)
End Using
End Using
Catch ex As Exception
Success = False
End Try
Return Success
End Function
Public Function SaveChanges(ByVal sender As DataRow) As Boolean
Try
Using cn As New OleDb.OleDbConnection With {.ConnectionString = Builder.ConnectionString}
Using cmd As New OleDb.OleDbCommand With {.Connection = cn}
cmd.CommandText =
<SQL>
UPDATE
Customer
SET
CompanyName=?,
ContactName=?
WHERE Identifier = ?
</SQL>.Value
Dim CompanyNameParameter As New OleDb.OleDbParameter With
.DbType = DbType.String,
.ParameterName = "P1",
.Value = sender.Field(Of String)("CompanyName")
cmd.Parameters.Add(CompanyNameParameter)
Dim ContactNameParameter As New OleDb.OleDbParameter With
.DbType = DbType.String,
.ParameterName = "P2",
.Value = sender.Field(Of String)("ContactName")
cmd.Parameters.Add(ContactNameParameter)
Dim IdentifierParameter As New OleDb.OleDbParameter With
.DbType = DbType.Int32,
.ParameterName = "P3",
.Value = sender.Field(Of Int32)("Identifier")
cmd.Parameters.Add(IdentifierParameter)
Try
cn.Open()
Dim Affected = cmd.ExecuteNonQuery
Return Affected = 1
Catch ex As Exception
Return False
End Try
End Using
End Using
Catch ex As Exception
' Handle or not handle exceptions for failed save operation
Return False
End Try
End Function
End Module
Here is an example of retrieving a row of data via a where condition
Public Sub LoadSingle(ByVal Identifier As Integer)
Using cn As New OleDb.OleDbConnection With
.ConnectionString = Builder.ConnectionString
Using cmd As New OleDb.OleDbCommand With {.Connection = cn}
cmd.CommandText =
<SQL>
SELECT
Identifier,
CompanyName,
ContactName
FROM
Customers
WHERE Identifier=@Identifier
</SQL>.Value
cmd.Parameters.Add(New OleDb.OleDbParameter With
.DbType = DbType.Int32,
.ParameterName = "@Identifier",
.Value = Identifier
cn.Open()
Dim Reader As OleDb.OleDbDataReader = cmd.ExecuteReader
If Reader.HasRows Then
Reader.Read()
Console.WriteLine("Name: {0} Contact name: {1}",
Reader.GetString(1), Reader.GetString(2))
End If
End Using
End Using
End Sub
Here you can see (using a random example) that SQL-Server code uses the same logic and methods
Using cn As New SqlConnection With {.ConnectionString = MyConnectionString}
Dim CompanySearch As String = "An"
Using cmd As New SqlCommand With {.Connection = cn}
cmd.CommandText =
<SQL>
SELECT CompanyName
FROM
Customers
WHERE
CompanyName LIKE @CompanyName
</SQL>.Value
cmd.Parameters.Add(
New SqlParameter With
.DbType = DbType.String,
.Value = CompanySearch & "%",
.ParameterName = "@CompanyName"
cn.Open()
Dim Reader = cmd.ExecuteReader
If Reader.HasRows Then
While Reader.Read
Console.WriteLine(Reader.GetString(0))
End While
Else
Console.WriteLine("No matches")
End If
End Using
End Using
So all the above is "hand coding" and there is still the option to use Adapters but for simple stuff they are over kill. The only benefit for them with simple stuff is if you are a visual person, thats it.
See also:
This article on creating SQL statement as per how I did it in the examples above. In the next release of Visual Studio this method will be easier similar to C#
Currently in C# we can do this
string selectStatement = @"
SELECT CompanyName
FROM
Customers
WHERE
CompanyName LIKE @CompanyName";
On creating a DataTable, check out this simple utility
https://code.msdn.microsoft.com/DataTable-creator-95b655b3
Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. -
Sum function within if/then/else (xdofx:if)
I'm attempting to display a total at a particular group within my report. This total is conditional and should choose to display a placeholder value or the sum of another placeholder value (in a child group).
I have been able to vary my output based on the value I want to check: FIXED_QUOTE_FLAG - I have the if/then/else working in a simplified fashion
I can display literals and some placeholders correctlly eg. print a literal value of 00110011 or the value of placeholder QUOTED_PRICE
I can also display a calculated placeholder, using sum within the group I am concerned with: sum (current-group()/ACTIVITY_CHRG)
But when I try to get everythign working together ...
I cannot get the sum to work inside the if/then/else condition. The result is NULL (blank in HTML output).
The following is the snippet which is not working correctly:
<?xdofx:if FIXED_QUOTE_FLAG = 'Y' then QUOTED_PRICE else sum (current-group()/ACTIVITY_CHRG) end if?>
Message was edited by:
gareth_adamsonTo answer you first question, perhaps sum is not a supported function in the xdofx namespace. It's annoying when this problem comes up because xdofx namespace seems to be the only way to do if then else clauses. I'm not entirely certain on the above, but you could resort to using BI Publisher's built-in if statement.
For your problem, something like this:
<?if: FIXED_QUOTE_FLAG='Y'?>
QUOTED_PRICE
<?end if?>
<?if: FIXED_QUOTE_FLAG!='Y'?>
<?sum(current-group()/ACTIVITY_CHRG)?>
<?end if?>
EDIT:
There is a way to do if else without xdofx namespace. It is done with <?choose:?> <?when:?> and <?otherwise:?> tags. Here is example syntax copied from Tim Dexter's blog:
<?choose:?>
<?when:count(TRX_NUMBER) > 0?>
Invoice Table
<?end when?>
<?otherwise:?>
No Data Found
<?end otherwise?>
<?end choose?>
To answer the second question about a running total, you will need to use the <?xdoxslt:set_variable($_XDOCTX,'var_name',var_value)?> and the <?xdoxslt:get_variable($_XDOCTX,'var_name')?>. This method of working with variables is the only method that allows you to update a variable. This makes it good for running totals. Consult the official user guide under "Creating an RTF Template" the section about using variables and calculating running totals.
So, in your problem, once you get the first part working, you will have to add that value to your running total. It will look something like this:
<?xdoxslt:set_variable($_XDOCTX,'running_total',xdoxslt:get_variable($_XDOCTX,'running_total') + conditional_value)?>
Remember to initialize the running total to zero! Hope this helps.
Thanks,
Matt Soukup
Message was edited by:
Matt Soukup -
Select in CASE statement or in IF-THEN-ELSE
I have been struggling for a week with a problem and still can't solve the way I want.
Given four text fields in page : p1_name, p1_place_name, p1_place_number and p1_place_init_letter - where user types text and press 'Search' button to see the results.
p1_name finds results in table EMPLOYEES
p1_place_name, p1_place_number and p1_place_init_letter find results in table PLACES
the two tables are linked by id_place field
I would like reports to be shown depending on search results:
- if p1_name exists and (p1_place_name and p1_place_number and p1_place_init_letter) exist AND EMPLOYEES.id_place = PLACES.id_place then a single report shows only employee row
- if p1_name exists and (p1_place_name and p1_place_number and p1_place_init_letter) exist AND EMPLOYEES.id_place # PLACES.id_place then two reports showing 1) employees with name = :p1_name and 2) places with name, number and init_letter = :p1_.....
- if p1_name not exists and (p1_place_name and p1_place_number and p1_place_init_letter) exist then a message with 'NO EMPLOYEE' and report shows only places where name, number and init_letter = :p1_.....
- if p1_name exists and (p1_place_name and p1_place_number and p1_place_init_letter) not exist then report shows only employee row where name = :p1_name and message with 'NO PLACE'
- if p1_name not exists and (p1_place_name and p1_place_number and p1_place_init_letter) not exist then messages 'NO EMPLOYEE' and 'NO PLACE'
I do NOT know if it is possible, and if it is, then what do I have to use : IF - THEN - ELSE or CASE ?
I tried to build HTML report region conditionally shown for each situation, but they do not work the way I want.
Could you please help me ?
Thank you in advance !Agree with Dan. Use a dedicated report region for a unique query. Use a rendering condition to determine if that reporting region must be rendered (i.e. whether or not that reporting query must be executed ).
The alternative is creating a function that constructs the SQL query dynamically, based on the user supplied values for page items. Use the function as the source for the reporting region, instead of a SQL statement. (this is similar to creating a ref cursor for a client, minus the actual step to create the ref cursor - instead the source SQL for that ref cursor is returned).
Also consider asking your Apex questions in the dedicated Apex forum on OTN. -
If-then-else in a select statement
hi, is it possible to make a if-then-else in a select query, something like:
select name, age, if(sex=f,1,2) as my_columnn from table1;
thx.Hallo,
yes it is possible:
1. with decode
select name, decode(sex, 'f',1,2) as your_column from table1;
2. with case
select name, case when sex='f' THEN 1 ELSE 2 END) as your_column from table1;
Regards
Dmytro -
Insert and update query to calculate the opening and closing balance
create table purchase(productid number(5) ,dateofpurchase date,
qty number(5));
create table inventory(invid number(5),productid number(5),
idate date,openingqty number(5),closingqty number(5));
Records in inventory:
1,1,'01-jan-2009', 10, 20
2,1,'03-jan-2009', 20, 30
3,1,'04-jan-2009', 40, 50
when I enter the purchase invoice for 15 qty on 02-jan-2009
after say '15-jan-09' , a new record should get inserted
with opening balance = (closing balance before 02-jan-2009)
and all the opening and closing balance for that product should
get affected.
If the invoice for 20 qty is entered for the existing date say
'03-jan-2009' in inventory , then the closing balance
for 03-jan-2009 should get updated and all the following records
should get affected.
I need the insert for the first one and update query for the
second one.
Vinodh<strike>You can do this in one statement by using the merge statement</strike>
Hmm, maybe I spoke too soon.
Edited by: Boneist on 25-Sep-2009 13:56
Thinking about it, why do you want to design your system like this?
Why not simply have your purchases table hold the required information and then either work out the inventory on the fly, or have a job that calls a procedure to add a row for the previous day?
If you continue with this design, you're opening yourself up to a world of pain - what happens when the data doesn't match the purchases table? Also when is the inventory cut-off to reset the opening/closing balances? Monthly? Annually? Weekly? If it's set to one of those, what happens when the business request the inventory for a particular week?
Edited by: Boneist on 25-Sep-2009 13:59
Maybe you are looking for
-
How do I use the "double-layer" function with my iMac?
Hi, Just wondering who can help me. I want to burn a dvd using the double-layer feature. The thing is I don't know if my iMac comes with that application preinstalled. I don't even know if I need an application and which one. The only thing I have fo
-
hey guys i was just wondering why in a BPM scenario we have to do interface mapping between outbound(or inbound) and abstract interface,whereas in a regular scenario(without BPM) we do it between outbound and inbound interfaces?is it just because BPM
-
Importing birthdays into address book
I am trying to import my birthdays from microsoft outlook into the contact information in address book. Can anyone tell me how to do this on a mass scale?
-
Kernel panics on waking from sleep
Hi I have a problem with my MBP, which is up to date with all the latest OSX and firmware updates as far as I can tell. Quite often - at least once a day on average - the computer will go into a kernel panic on waking from sleep. It's not every time,
-
We are implementing Marketing in Phase I - Campaign Management, Leads, etc. How far is the Organizational Plan important to implement Marketing module. Is it necessary at all? Or can this be done even without org plan developed? Any ideas are welcome