Help needed in writing SQL CASE or DECODE statement

Hi experts,
I need to write a SQL to select order_num, cntry_cde, prod_id and Qty by joining order_num on PROD_ORDER and PROD_ORDER_TXT.
Here is my sample data
PRODORDER_               
order_num     cntry_cde     Prod_id     Qty
100     US     A1     5
101     US     A2     10
102     AU     A3     4
103     AU     A4     9
104     IN     A5     3
PRODORDER_TXT_               
order_num     cntry_cde     Prod_id     
100     US     A1     
101     US     A2     
102     NZ     A3     
103     AU     A4     
104          A5     
Here is the requirement,
1) If the cntry_cde in PROD_ORDER is same as cntry_cde in PROD_ORDER_TXT then select PROD_ORDER.cntry_cde (orders 100, 101, 103)
2) If they are different, pick the country code from PROD_ORDER_TXT (order 102, AU <> NZ)
3) If they are different and PROD_ORDER_TXT.cntry_cde is NULL, I cannot use it as cntry_cde in my report (order 104). It happenend just because of the bad data at source.
I cannot avoid it. Then simply use the cntry_cde from PROD_ORDER
Output expected
100     US     A1     5
101     US     A2     10
102     NZ     A3     4 -- AU changed to NZ
103     AU     A4     9
104     IN     A5     3 -- IN retained as PROD_ORDER_TXT.cntry_cde is null
sample table creation and insert statements are below
create table prod_order
(order_num number,
cntry_cde CHAR(2),
prod_id VARCHAR2(6),
qty number)
create table prod_order_txt
(order_num number,
cntry_cde CHAR(2),
prod_id VARCHAR2(6))
insert into prod_order values (100, 'US', 'A1',5);
insert into prod_order values (101, 'US', 'A2',1);
insert into prod_order values (102, 'AU', 'A3',4);
insert into prod_order values (103, 'AU', 'A4',9);
insert into prod_order values (104, 'IN', 'A5',3);
insert into prod_order_txt values (100,'US','A1');
insert into prod_order_txt values (101,'US','A2');
insert into prod_order_txt values (102,'NZ','A3');
insert into prod_order_txt values (103,'AU','A4');
insert into prod_order_txt values (104,NULL,'A5');
commit;
Thanks for your help in advance
Edited by: sarvan on Mar 28, 2012 1:39 PM

Hello
Thank you for posting all of the ddl and test data along with your expected output - very helpful!. One small point would be to remember to type {noformat}{noformat} before and after any section of code or data in your post so that formatting is retained.  Anyway, this should be a simple join and a combination of CASE and NVL...Select
po.order_num,
CASE
WHEN po.cntry_cde != NVL(pot.cntry_cde,po.cntry_cde)
THEN
pot.cntry_cde
ELSE
po.cntry_cde
END cntry_code,
po.prod_id,
po.qty
FROM
prod_order po
JOIN
prod_order_txt pot
ON
( po.order_num = pot.order_num
ORDER_NUM CN PROD_I QTY
100 US A1 5
101 US A2 1
102 NZ A3 4
103 AU A4 9
104 IN A5 3
5 rows selected.
HTH
David
Edited by: Bravid on Mar 28, 2012 8:32 AM
corrected !=                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

Similar Messages

  • Help needed for writing query

    help needed for writing query
    i have the following tables(with data) as mentioned below
    FK*-foregin key (SUBJECTS)
    FK**-foregin key (COMBINATION)
    1)SUBJECTS(table name)     
    SUB_ID(NUMBER) SUB_CODE(VARCHAR2) SUB_NAME (VARCHAR2)
    2           02           Computer Science
    3           03           Physics
    4           04           Chemistry
    5           05           Mathematics
    7           07           Commerce
    8           08           Computer Applications
    9           09           Biology
    2)COMBINATION
    COMB_ID(NUMBER) COMB_NAME(VARCHAR2) SUB_ID1(NUMBER(FK*)) SUB_ID2(NUMBER(FK*)) SUB_ID3(NUMBER(FK*)) SUBJ_ID4(NUMBER(FK*))
    383           S1      9           4           2           3
    384           S2      4           2           5           3
    ---------I actually designed the ABOVE table also like this
    3) a)COMBINATION
    COMB_ID(NUMBER) COMB_NAME(VARCHAR2)
    383           S1
    384           S2
    b)COMBINATION_DET
    COMBDET_ID(NUMBER) COMB_ID(FK**) SUB_ID(FK*)
    1               383          9
    2               383          4
    3               383          2
    4               383          3
    5               384          4
    6               384          2          
    7               384          5
    8               384          3
    Business rule: a combination consists of a maximum of 4 subjects (must contain)
    and the user is less relevant to a COMB_NAME(name of combinations) but user need
    the subjects contained in combinations
    i need the following output
    COMB_ID COMB_NAME SUBJECT1 SUBJECT2      SUBJECT3      SUBJECT4
    383     S1     Biology Chemistry      Computer Science Physics
    384     S2     Chemistry Computer Science Mathematics Physics
    or even this is enough(what i actually needed)
    COMB_ID     subjects
    383           Biology,Chemistry,Computer Science,Physics
    384           Chemistry,Computer Science,Mathematics,Physics
    you can use any of the COMBINATION table(either (2) or (3))
    and i want to know
    1)which design is good in this case
    (i think SUB_ID1,SUB_ID2,SUB_ID3,SUB_ID4 is not a
    good method to link with same table but if 4 subjects only(and must) comes
    detail table is not neccessary )
    now i am achieving the result by program-coding in C# after getting the rows from oracle
    i am using oracle 9i (also ODP.NET)
    i want to know how can i get the result in the stored procedure itsef.
    2)how it could be designed in any other way.
    any help/suggestion is welcome
    thanks for your time --Pradeesh

    Well I forgot the table-alias, here now with:
    SELECT C.COMB_ID
    , C.COMB_NAME
    , (SELECT SUB_NAME
    FROM SUBJECTS
    WHERE SUB_ID = C.SUB_ID1) AS SUBJECT_NAME1
    , (SELECT SUB_NAME
    FROM SUBJECTS
    WHERE SUB_ID = C.SUB_ID2) AS SUBJECT_NAME2
    , (SELECT SUB_NAME
    FROM SUBJECTS
    WHERE SUB_ID = C.SUB_ID3) AS SUBJECT_NAME3
    , (SELECT SUB_NAME
    FROM SUBJECTS
    WHERE SUB_ID = C.SUB_ID4) AS SUBJECT_NAME4
    FROM COMBINATION C;
    As you need exactly 4 subjects, the columns-solution is just fine I would say.

  • Help needed in writing a function.

    I am using Oracle 11g and SQL plus. I am a complete newbie, so I need some help here in writing a function. I guess my question is more about writing the trigonometric functions within the function.
    latA, longA latB, longB // these are the four input parameters,
    theta = longA - longB
    distX = sin( latA * PI / 180) * sin ( latB * PI /180) + cos ( latA * PI/180) * cos ( latB * PI/180) * cos ( theta * PI / 180)
    distY = acos(distX) // this is arc cosine
    distZ = distY * 180 / PI // PI refers to the mathematical PI
    distP = distZ * 60 * 1.1515; // this value should be returned. Of course the intermediate variable names don't matter.
    Please help. Thanks.

    CREATE OR REPLACE FUNCTION fucntion_name(latA IN NUMBER, longA IN NUMBER, latB IN NUMBER, longB IN NUMBER) RETURN NUMBER
    IS
    pi      CONSTANT NUMBER:=3.14159;
    theta NUMBER;
    distX  NUMBER;
    distY  NUMBER;
    distZ  NUMBER;
    distP  NUMBER;
    BEGIN
    theta :=longA - longB;
    distX :=sin( latA * PI /180) * sin ( latB * PI /180) + cos ( latA * PI/180) * cos ( latB * PI/180) * cos ( theta * PI / 180);
    distY :=acos(distX); --this is arc cosine
    distZ :=distY * 180/PI;  --PI refers to the mathematical PI
    distP :=distZ * 60 * 1.1515; --this value should be returned. Of course the intermediate variable names don't matter.
    RETURN distP;
    END;Edited by: Ora on May 3, 2011 11:46 PM

  • Help needed in framing SQL query.

    Hi,
    I have table having following schema:
    PRODUCT_ID         INT
    DATE                   DATETIME
    ITEMS_SOLD         INT
    This table contains data for a week (sunday to saturday). I want to write an SQL query to get (filter out) PRODUCT_ID of products which has same no. of ITEMS_SOLD for all 7 days. Also for given PRODUCT_ID I need to find the longest period of successive days where the no. of ITEMS_SOLD is same for all days in this period. Eg.(PRODUCT_ID 23 was sold as following along the week in no. of units sold: 4,6,6,6,6,7,4 .So the longest period is *4 days* from Monday to Thursday.) The first condition is special case of second condition where no. of days is 7.
    Any help to get the SQL query will be appreciated.
    Thanks,
    Akshay.

    PRODUCT_ID      DATE           ITEMS_SOLD
    1          10/10/2011     3
    1          11/10/2011     3
    1          12/10/2011     3
    1          13/10/2011     3
    1           16/10/2011     5
    2          10/10/2011     4
    2           11/10/2011     4
    2          12/10/2011     4
    2          13/10/2011     4
    2           14/10/2011     4
    2          15/10/2011     4
    2          16/10/2011     4
    Output:
    PRODUCT_ID ITEMS_SOLD NO_OF_DAYS
    1          3                4     
    2          4               7
    Explanation of results:
    The table to be queried contains data for 1 week: from 10/10/2011(Sunday) to 16/10/2011(Saturday). Now, product with PRODUCT_ID '1' was sold on dates 10,11,12,13,16. Out of these 5 days 3 units were sold on 4 successive days (from 10-13). So output should be like :
    PRODUCT_ID ITEMS_SOLD NO_OF_DAYS
    1          3               4     
    as longest period of successive days is 4 where same no. of units were sold i.e 3 units (other period is of 1 day on 16th ).
    For PRODUCT_ID 2 we have only one period of 7 days where 4 units were sold each day. So we output :
    PRODUCT_ID ITEMS_SOLD NO_OF_DAYS
    2           4               7
    Other case where same PRODUCT_ID have different units sold on each day should be ignored.
    I hope that clarifies the problem more. Let me know in case I have missed out anything which should have been mentioned.
    -Akshay.

  • Help needed in writing query

    Hi,
    Could anyone help me in writing below query without syntax errors.
    I tried but no luck
    select xmlelement("g", XMLATTRIBUTES(g.contentgroup_id as "id",g.groupname as "label",
    (select xmlagg(xmlelement ("c",XMLATTRIBUTES(c.title as "title",c.content_id as "id")))) as "A"))
    as "A" from
    (SELECT g.contentgroup_id AS id, g.groupname AS label, c.title AS label, c.content_id AS id
    FROM content_ec c FULL OUTER JOIN contentgroup_ec g ON c.group_id = g.contentgroup_id
    oRDER BY g.groupname ,c.title ASC );
    Any help really appreciated.
    Thanks

    Few tips to get your question answered here
    1. Give your database version. Some thing that does not work in one version works fine in the next. And 8i,9i or 10g is not version. best way to give the version is to query your v$version table like this.
    SQL> select * from v$version where rownum = 1
      2  /
    BANNER
    Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 - Prod2. You should understand we don't have what you have, meaning you should provide your data structure and some sample data for us to help.
    3. "I got an error"... "Its not working"... and the list goes on. Sentences like this does not help. If you got a error past the entire error. If stuff does not work, tell us the details.
    4. Just don't throw some output and say i want it. Please explain to every one how you derive it.
    5. And the most important thing. Use \...\ tag to format. Please.. Please.. Please.. use it. It helps every one a lot. When you use it your SQL looks some thing like this.
    SELECT xmlelement("g", XMLATTRIBUTES(g.contentgroup_id as "id",g.groupname as "label",
         (select xmlagg(xmlelement ("c",XMLATTRIBUTES(c.title as "title",c.content_id as "id")))) as "A")) as "A"
       FROM (SELECT g.contentgroup_id AS id,
                 g.groupname AS label,
                 c.title AS label,
                 c.content_id AS id
            FROM content_ec c
            FULL OUTER JOIN contentgroup_ec g
              ON c.group_id = g.contentgroup_id
           ORDER BY g.groupname ,c.title ASC );6. And also do search this forum. Most of your my queries are answered by simple search.
    Thanks,
    Karthick.

  • Help Needing in optimizing SQL

    I need help optimizing the following SQL.
    Following are the schema elements -
    cto_xref_job_comp - Contains the Job Data
    cto_mast_component - Contains component
    cto_mast_product - Contains product info
    cto_mast_model - Contains model info
    cto_xref_mod_prod - Contains model and product assoiciation
    cto_mast_model_scan - Contain the Scan order for each model family (the mod_id(should be renamed) refers to mod_fam_id on the cto_mast_model table).
    Here is what I am trying to achieve
    I want all the ATP components whose Travel card order (on cto_mast_model_scan > 0 ) and in addition I need the Phantoms that do not have any ATP components under them if they do not appear on ATP component list.
    SELECT f.travelcard_order, b.job_number,
    b.product_code,
    b.line_number,
                   b.component_type,
    b.component_item_number,
    b.parent_phantom,
    b.item_type,
    a.comp_id,
    a.comp_type_id,
    a.comp_desc_short,
    b.batch_id,
    b.quantity_per_unit,
    a.comp_notes,
                   b.COMPONENT_ITEM_DESCRPTION
    FROM      cto_xref_job_comp b,
                        cto_mast_component a,
                        cto_mast_product c,
    cto_xref_mod_prod d,
    cto_mast_model e,
                   cto_mast_model_scan f
    WHERE ( b.job_number = 'CTO2499814001' ) AND
    ( b.batch_id = 21 ) AND
    (b.item_type = 'ATP') AND
                   (b.parent_phantom = a.comp_desc_short ) and          
                   (b.product_code = c.prod_desc_short ) and
    (c.prod_id = d.prod_id ) and
    (d.mod_id = e.mod_id) and
    (e.mod_fam_id = f.mod_id) and
    (a.comp_type_id=f.comp_type_id) and
                                       (f.travelcard_order > 0)
    union
    SELECT distinct f.travelcard_order, b.job_number,
    b.product_code,
    b.line_number,
                   b.component_type,
    b.parent_phantom,
    b.item_type,
    a.comp_id,
    a.comp_type_id,
    a.comp_desc_short,
    b.batch_id,
    1,
    a.comp_notes,
    FROM      cto_xref_job_comp b,
                        cto_mast_component a,
                        cto_mast_product c,
    cto_xref_mod_prod d,
    cto_mast_model e,
                   cto_mast_model_scan f
    WHERE ( b.job_number = 'CTO2499814001' ) AND
    ( b.batch_id = 21 ) AND (b.item_type is null) and
                   (substr(b.parent_phantom,1,1)='C') and
                   (b.parent_phantom = a.comp_desc_short )
    and (b.parent_phantom not in (select parent_phantom from cto_xref_job_comp where job_number=b.job_number and batch_id=b.batch_id and item_type='ATP')) and           
                   (b.product_code = c.prod_desc_short ) and
    (c.prod_id = d.prod_id ) and
    (d.mod_id = e.mod_id) and
    (e.mod_fam_id = f.mod_id) and
    (a.comp_type_id=f.comp_type_id) and (f.travelcard_order > 0)

    Here is a small example.
    DECLARE
         my_table VARCHAR2(10) := 'DUAL';
         my_value INTEGER;
    BEGIN
         EXECUTE IMMEDIATE 'SELECT 1 FROM ' || my_table INTO my_value;
         DBMS_OUTPUT.PUT_LINE(my_value);
    END;
    you can use your cursor value in the place of my_table.
    Thanks,
    Karthick.
    http://www.karthickarp.blogspot.com/

  • Help needed on writing a SQL query

    Here is my table that shows records of 3 ORDER_ID (10, 20 and 30). All I need to do is, pick the first record of each order_id and check the event_id, if the event_id is same for the next record, ignore it, else show it and ignore rest all records for that order_id. This way my query output will show only two records for each ORDER_ID. Query should produce records that are in BOLD in the sample data. (Database - 11g)
    Thanks for your help in advance
    ORDER_ID     EVENT_ID     EVNT_DATE     STATE_CODE
    *10     16937555     20100212     COMPLETE*
    10     16937555     20100212     ACTIVE
    *10     16308004     20100129     OCCURRED*
    10     16131904     20100125     ACTIVE
    10     16270684     20100128     OCCURRED
    10     14899116     20091213     ACTIVE
    10     16085672     20100123     COMPLETE
    10     16085673     20100123     OCCURRED
    10     14899119     20100123     COMPLETE
    10     14899120     20100123     COMPLETE
    *20     17134164     20100223     COMPLETE*
    20     17134164     20100223     ACTIVE
    20     17134164     20100223     STARTED
    *20     15479131     20100105     OCCURRED*
    20     15478409     20100105     OCCURRED
    20     15478408     20100105     ACTIVE
    20     15119404     20100105     COMPLETE
    20     14346123     20091129     ACTIVE
    20     15467821     20100104     OCCURRED
    20     14346125     20091216     COMPLETE
    20     14346126     20091215     COMPLETE
    20     14346126     20091214     COMPLETE
    *30     18814670     20100412     COMPLETE*
    30     18814670     20100412     ACTIVE
    *30     18029509     20100320     OCCURRED*
    30     16853720     20100211     ACTIVE
    30     17965764     20100319     OCCURRED
    30     16386708     20100211     COMPLETE
    30     16804451     20100211     OCCURRED
    30     15977897     20100121     ACTIVE
    Edited by: sarvan on Aug 12, 2011 7:16 AM

    try this [Not fully tested]
    SQL> select * from v$version;
    BANNER
    Oracle Database 11g Enterprise Edition Release 11.2.0.2.0 - 64bit Production
    PL/SQL Release 11.2.0.2.0 - Production
    CORE    11.2.0.2.0      Production
    TNS for Linux: Version 11.2.0.2.0 - Production
    NLSRTL Version 11.2.0.2.0 - Production
    Elapsed: 00:00:00.00
    SQL> SELECT *
      2    FROM (SELECT order_id, event_id, evnt_date, state_code, next_evntid,
      3                 ROW_NUMBER () OVER (PARTITION BY event_id ORDER BY NULL)
      4                                                                       AS rownm
      5            FROM (WITH t AS
      6                       (SELECT 10 AS order_id, 16937555 AS event_id,
      7                               20100212 AS evnt_date, 'COMPLETE' AS state_code
      8                          FROM DUAL
      9                        UNION ALL
    10                        SELECT 10, 16937555, 20100212, 'ACTIVE'
    11                          FROM DUAL
    12                        UNION ALL
    13                        SELECT 10, 16308004, 20100129, 'OCCURRED'
    14                          FROM DUAL
    15                        UNION ALL
    16                        SELECT 10, 16131904, 20100125, 'ACTIVE'
    17                          FROM DUAL
    18                        UNION ALL
    19                        SELECT 10, 16270684, 20100128, 'OCCURRED'
    20                          FROM DUAL
    21                        UNION ALL
    22                        SELECT 20, 17134164, 20100223, 'COMPLETE'
    23                          FROM DUAL
    24                        UNION ALL
    25                        SELECT 20, 17134164, 20100223, 'ACTIVE'
    26                          FROM DUAL
    27                        UNION ALL
    28                        SELECT 20, 17134164, 20100223, 'STARTED'
    29                          FROM DUAL
    30                        UNION ALL
    31                        SELECT 20, 15479131, 20100105, 'OCCURRED'
    32                          FROM DUAL)  -- End of test data
    33                  SELECT order_id, event_id, evnt_date, state_code,
    34                         LEAD (event_id, 1, 0) OVER (PARTITION BY order_id ORDER BY NULL)
    35                                                                 AS next_evntid
    36                    FROM t)
    37           WHERE event_id = next_evntid)
    38   WHERE rownm <= 2
    39  /
      ORDER_ID   EVENT_ID  EVNT_DATE STATE_CO NEXT_EVNTID      ROWNM
            10   16937555   20100212 COMPLETE    16937555          1
            20   17134164   20100223 COMPLETE    17134164          1
            20   17134164   20100223 ACTIVE      17134164          2
    Elapsed: 00:00:00.00
    SQL> PS - You should seriously think about ordering the data before you do this kind off operations.
    Edited by: Sri on Aug 12, 2011 9:12 AM

  • Help Needed in Dynamic Sql or alternate to Dynamic Sql

    Hi Am working in sqlserver 2008 R2 and here is my Table structure and SPC
    ;create table SalaryReport(IdSalary int primary key identity(1,1),
    IDMainCompany int,IDSubCompany int,Salary money,Incentive int,NoofEmployees int, SalaryDate datetime, Creditscore int );
    insert into SalaryReport (IDMainCompany,IDSubCompany,Salary,Incentive,NoofEmployees,SalaryDate,Creditscore)
    ( Select 100 as IDMainCompany , 1000 as IDSubCompany ,200000 AS Salary, 20000 as Incentive, 500 as NoofEmployees,
    '2014-01-01' as SalaryDate, 60 as Creditscore union all
    Select 100 as IDMainCompany , 1001 as IDSubCompany ,300000 AS Salary, 40000 as Incentive, 600 as NoofEmployees,
    '2014-01-01' as SalaryDate , 70 as Creditscore union all
    Select 100 as IDMainCompany , 1002 as IDSubCompany ,400000 AS Salary, 40000 as Incentive, 1500 as NoofEmployees,
    '2014-01-01' as SalaryDate , 45 as Creditscore union all
    Select 101 as IDMainCompany , 1003 as IDSubCompany ,30000 AS Salary, 2000 as Incentive, 100 as NoofEmployees,
    '2014-01-01' as SalaryDate, 60 as Creditscore union all
    Select 102 as IDMainCompany , 1004 as IDSubCompany ,450000 AS Salary, 25000 as Incentive, 700 as NoofEmployees,
    '2014-01-01' as SalaryDate, 30 as Creditscore)
    Sample Test Script:
    DECLARE @IDMainCompany int = 100;
    DECLARE @Process_Date datetime = '2014-01-01';
    declare @Query nvarchar(max);
    SELECT
    CAST(SR.IDMainCompany AS VARCHAR(12)) AS IDMainCompany
    ,CAST(SR.IDSubCompany AS VARCHAR(12)) AS IDSubCompany
    ,CAST(SR.Salary AS VARCHAR(12)) AS Salary
    ,CAST(SR.Incentive AS VARCHAR(12)) AS Incentive
    ,CAST(SR.NoofEmployees AS VARCHAR(12)) AS NoofEmployees
    ,CAST(SR.SalaryDate AS VARCHAR(15)) AS SalaryDate
    ,CAST((SR.Creditscore) AS VARCHAR(15)) AS average
    FROM SalaryReport SR
    WHERE SR.IDMainCompany = @IDMainCompany
    AND DATEPART(MM, SR.SalaryDate) = DATEPART(MM, @Process_Date)
    UNION ALL
    SELECT
    '' AS IDMainCompany
    ,'' AS IDSubCompany
    ,'Total: ' + CAST(SUM(SR.Salary) AS VARCHAR(12)) AS Salary
    ,'Total: ' + CAST(SUM(SR.Incentive) AS VARCHAR(12)) AS Incentive
    ,'Total: ' + CAST(SUM(SR.NoofEmployees) AS VARCHAR(12)) AS NoofEmployees
    ,'' AS SalaryDate
    ,'Total: ' +CAST(avg(SR.Creditscore) AS VARCHAR(12)) AS Totalaverage
    FROM SalaryReport SR
    WHERE SR.IDMainCompany = @IDMainCompany
    AND DATEPART(MM, SR.SalaryDate) = DATEPART(MM, @Process_Date)
    group by IDMainCompany, DATEPART(MM, SalaryDate)
    the sample data i posted is having less columns. actually i have 20 columns in the select list. Also the parameters to the where condition i gave two i.e IDMainCompany, SalaryDate. I will also need to use IDSubCompany for some case. My skeleton will be 
    Create Procedure Test(@IDMainCompany int, @IDSubCompany int = null, @SalaryDate datetime)
    as
    BEGIN
    IF(@IDMainCompany is not null && @IDMainCompany > 0 && @SalaryDate is not null && @SalaryDate <> ' ' &&
    @IDSubCompany is null)
    BEGIN
    --The logic what discussed on previous posts will falls here with @IDMainCompany, @SalaryDate as parameter to the where condition
    END
    IF(@IDMainCompany is not null && @IDMainCompany > 0 && @SalaryDate is not null && @SalaryDate <> ' ' &&
    @IDSubCompany is null && @IDSubCompany > 0 )
    BEGIN
    --The logic what discussed on previous posts will falls here with @IDMainCompany, @SalaryDate,@IDSubCompany as parameter to the where condition
    END
    END
    As said i need to include 20 columns in the select list and as union all used on the previous sample there are 20 columns on the first query and 20 columns on the second query after the union all. The SPC will become big. If i repeat this for second if condition,
    it will be too big. How can i reduce this writing more lines.
    I am aware of the concept dynamic sql. Is there any other way to do this? or if dynamic sql is the only option, can anyone help me rewriting this select statements as dynamic sql
    Could anyone please assist me 
    loving dotnet

    >>
    thanks for your reply and yes, i am invoking this from my asp.net application using C# language.  Would you like to share something?
    <<
    Yes,
    You can use client side dynamic sql. I'm not talking about concatenating strings. I'm talking about using Runtime Text Tamplates (preprocesed templates in Visual Studio 2010).
    Add a new "Runtime Text Template" item to your VS project. Be "MyReportTemplate.tt" the file name of the runtime text template.  The content of this file should be something like the following:
    <#@ template language="C#" #>
    <#@ assembly name="System.Core" #>
    SELECT
    -- part of your query goes here
    -- the interesting part come next
    FROM
    SalaryReport SR
    WHERE
    SR.IDMainCompany = @IDMainCompany
    <# if (IDSubCompany.HasValue && IDSubCompany.Value > 0) { #>
    AND SR.IDSubCompany = @IDSubCompany
    <# } #>
    AND
    DATEPART(MM, SR.SalaryDate) = DATEPART(MM, @Process_Date)
    GROUP BY
    IDMainCompany, DATEPART(MM, SalaryDate)
    Add a new c# code file named MyReportTemplate.partial.cs closed to MyReportTemplate.tt with the following code:
    public partial class MyReportTemplate
    public int? IDSubCompany { get; set; }
    Then, to execute the query you can write a code similar to the following:
    public DataTable ExecuteReport(int mainCompanyId, int? subCompanyId, DateTime processDate )
    using (var cn = CreateConnection())
    using (var cmd = new SqlCommand())
    using (var adapter = new SqlDataAdapter(cmd))
    cmd.Connection = cn;
    var template = new MyReportTemplate
    IDSubCompany = subCompanyId
    cmd.CommandText = template.TransformText();
    cmd.Parameters.AddWithValue("@IDSubCompany", subCompanyId == null ? (object) DBNull.Value : subCompanyId.Value);
    cmd.Parameters.AddWithValue("@IDMainCompany", mainCompanyId);
    cmd.Parameters.AddWithValue("@Process_Date", processDate);
    var table = new DataTable();
    adapter.Fill(table);
    return table;
    EntityLite: A Lightweight, Database First, Micro ORM

  • Help needed  in writing a Query/Procedure

    Hello All,
    Need all ur help in writing a query or procedure
    Lets say the Table name is DEMO
    There i have one column like num it has values
    1
    2
    3
    4
    5
    8
    9
    10
    my query output should be
    1-5
    8-10
    i,e .. if the diff between two rows is greater than 1 then it result should be in a separate group
    I need a query/Procedure for this. Kindly help
    Regards,
    Chandra

    Tried obtaining the output using SQL and the result is as follows:
    SQL> WITH T AS
      2  (
      3  SELECT 1 COL1 FROM DUAL
      4  UNION
      5  SELECT 2 COL1 FROM DUAL
      6  UNION
      7  SELECT 3 COL1 FROM DUAL
      8  UNION
      9  SELECT 4 COL1 FROM DUAL
    10  UNION
    11  SELECT 5 COL1 FROM DUAL
    12  UNION
    13  SELECT 8 COL1 FROM DUAL
    14  UNION
    15  SELECT 9 COL1 FROM DUAL
    16  UNION
    17  SELECT 10 COL1 FROM DUAL
    18  UNION
    19  SELECT 13 COL1 FROM DUAL
    20  UNION
    21  SELECT 14 COL1 FROM DUAL
    22  UNION
    23  SELECT 15 COL1 FROM DUAL
    24  UNION
    25  SELECT 16 COL1 FROM DUAL
    26  UNION
    27  SELECT 23 COL1 FROM DUAL
    28  UNION
    29  SELECT 24 COL1 FROM DUAL
    30  )
    31  SELECT OUTPUT FROM
    32  (
    33  SELECT DECODE(COL3,NULL,COL1, COL2)  || '-' || LEAD(DECODE(COL3,NULL,COL3, COL1)) OVER (ORDER BY DECODE(COL3,NULL,COL1, COL2)) OUTPUT  FROM
    34  (
    35  SELECT COL1, LEAD(COL1) OVER (ORDER BY COL1) COL2, LAG(COL1) OVER (ORDER BY COL1) COL3 FROM T
    36  )
    37  WHERE
    38  (COL2 - COL1 > 1 OR COL2 IS NULL OR COL3 IS NULL)
    39  )
    40  WHERE OUTPUT != '-';
    OUTPUT                                                                         
    1-5                                                                            
    8-10                                                                           
    13-16                                                                          
    23-24

  • Help needed in a SQL

    Hi,
    We run a heavy batch load in many of our tables. Prior to the load we need to drop the indexes and then re create the indexes.
    I worte a dynamic sql like
    SELECT 'create index '||owner||'.'||a.index_name||' on '||owner||'.'||a.table_name||'('||column_name||');'
    from dba_indexes a, dba_ind_columns b
    where a.owner=b.index_owner
    and a.table_name=b.table_name
    and a.index_name=b.index_name
    and a.owner='owner_name'
    and a.table_name='table_name';
    The problem with this query is that it is giving wrong result for composite indexes.
    How to write a query that would pick up composite indexes as well.
    Any help will be highly appreciated.
    Thanks

    SID3 wrote:
    Are you referring to making the indexes unusable. In this case we have to rebuild them and index rebuilding is a big performance issue especially when millions of rows are involved.
    Our DB is 10g R2.And recreating the indexes isn't rebuilding them? ?:|

  • Help needed in PL/SQL for updating the column for multiple records

    Hi,
    I am new to PL/SQL and need some help. What is the most effiecient way to update some field in a table as I may need to update thousands of records. I have a coulmn groupid can have multiple records tied to it. All the records attached to some groupid have a priority field also.
    How can I update the prorityfield value for all the groupids in a profiecient way. Here is a sample data
    GroupId     Priority
    1            1
    1            2
    1            3
    1            4
    1            5
    2            1
    2            2
    2            3
    3            1Here I have three groups 1, 2, 3. Now if any group contains only one record the priority remains same e.g. groupid=3 on top. If any group contains more than one record e.g. groupid=1 & 2 I want to re-arrange the priority fields e.g. If I want to update groupid=1 now if I change the priority of 2 to 5 (make it the last) I want to rearrange the remaing records priority i.e. if 2 becomes 5 as I have 5 rows for groupid=1 then 5 becomes 4, 4 becomes 3, 3 becomes 2 and 1 remains the same.
    Same wya if I want to make the priority 1 to 3 for groupid=2 then need 2 to become 1 and 3 to become 2 etc....
    Any help is appreciated.
    Thanks

    Hi,
    You don't need PL/SQL to do this (though you can put the following in PL/SQL if you want to):
    UPDATE     table_x
    SET     priority = CASE
                   WHEN  groupid     = 1
                   AND   priority = 2
                        THEN  5
                   WHEN  groupod     = 1
                   AND   priority     BETWEEN 3 AND 5
                        THEN  priority - 1
                   WHEN  groupid = 2
                   THEN
                        CASE
                             WHEN  prioity = 1
                             THEN  3
                             ELSE  priority - 1
                        END
                 END
    WHERE     groupId          IN (1, 2)
    AND     (     priority     BETWEEN 2 AND 5
         OR     groupid          = 2
         );There are lots of different techniques that can reduce your coidng: for example, the nested CASE statement used for groupid=2 above.
    You could do several smaller UPDATEs (for example, one just for groupid=1). Execution will be slower, but coding and testing will be faster.
    You could make the "magic numbers" 2 (for groupid=1) and 1 (for groupid=2) variables, even outside of PL/SQL.
    If you need more help, post the information that Satyaki requested.

  • Help needed in writing installers for swing application

    Hi ,
    I want to write an installer for one of our home grown profiler tool. I need to write the installer for different platforms such as windows,linux,solaris,HP-UX.
    Does anybody have any idea of how to go ahead in writing installations. Share if there is any good links such as tutorials as well is thr any opensource tool (similar to installsheild) to write installers . As well following is the tentative algorithm for my install sheild
    1. Create a home dir for the tool and put all the application files in tht.
    2. Installing a 3rd party jar and make a home for it.
    3. Option for user to select the features(i hv 2 features. user can either select both or select individual feature) to be installed.
    4. Select the appserver home if any. On selection i hv to update the classpath in the startup batch file for the application(This is the toughest step i beleive bcoz each appserver have different folder structures and different startup batch files).

    Tried obtaining the output using SQL and the result is as follows:
    SQL> WITH T AS
      2  (
      3  SELECT 1 COL1 FROM DUAL
      4  UNION
      5  SELECT 2 COL1 FROM DUAL
      6  UNION
      7  SELECT 3 COL1 FROM DUAL
      8  UNION
      9  SELECT 4 COL1 FROM DUAL
    10  UNION
    11  SELECT 5 COL1 FROM DUAL
    12  UNION
    13  SELECT 8 COL1 FROM DUAL
    14  UNION
    15  SELECT 9 COL1 FROM DUAL
    16  UNION
    17  SELECT 10 COL1 FROM DUAL
    18  UNION
    19  SELECT 13 COL1 FROM DUAL
    20  UNION
    21  SELECT 14 COL1 FROM DUAL
    22  UNION
    23  SELECT 15 COL1 FROM DUAL
    24  UNION
    25  SELECT 16 COL1 FROM DUAL
    26  UNION
    27  SELECT 23 COL1 FROM DUAL
    28  UNION
    29  SELECT 24 COL1 FROM DUAL
    30  )
    31  SELECT OUTPUT FROM
    32  (
    33  SELECT DECODE(COL3,NULL,COL1, COL2)  || '-' || LEAD(DECODE(COL3,NULL,COL3, COL1)) OVER (ORDER BY DECODE(COL3,NULL,COL1, COL2)) OUTPUT  FROM
    34  (
    35  SELECT COL1, LEAD(COL1) OVER (ORDER BY COL1) COL2, LAG(COL1) OVER (ORDER BY COL1) COL3 FROM T
    36  )
    37  WHERE
    38  (COL2 - COL1 > 1 OR COL2 IS NULL OR COL3 IS NULL)
    39  )
    40  WHERE OUTPUT != '-';
    OUTPUT                                                                         
    1-5                                                                            
    8-10                                                                           
    13-16                                                                          
    23-24

  • Help on converting query with case into decode

    Hi Can anyone help me to revise my plsql query? Below is a portion og the procedure I am changing to meet Oracle 8i.
    SELECT SUM(NVL(CASE WHEN (weeks='wk1' ) THEN qty END, 0)) wk1,
    SUM(NVL(CASE WHEN (weeks='wk2' ) THEN qty END, 0)) wk2,
    SUM(NVL(CASE WHEN (weeks='wk3' ) THEN qty END, 0)) wk3,
    SUM(NVL(CASE WHEN (weeks='wk4' ) THEN qty END, 0)) wk4
    FROM TABLE1
    Thanks in advance.

    pls try this....(code not tested as no create table etc provided).
    select dt
    from (select decode(is_tbd,
    'yes',
    decode(is_tbd_order,
    'no',
    'tbd',
    decode(sign(ex_fac_date - (v_asofdate + 131)),
    1,
    'tbd',
    null),
    decode(sign(ex_fac_date - (v_asofdate + 131)),
    1,
    'tbd',
    null)),
    null) dt
    from dual
    union all
    select decode(sign(ex_fac_date - (v_asofdate - 1)),
    1,
    decode(sign(ex_fac_date - (v_asofdate + 5)),
    0,
    decode(is_tbd, 'no', 'wk1', null),
    null),
    null)
    from dual
    union all
    select decode(sign(ex_fac_date - (v_asofdate + 6)),
    1,
    decode(sign(ex_fac_date - (v_asofdate + 12)),
    0,
    decode(is_tbd, 'no', 'wk2', null),
    null),
    null)
    from dual
    select decode(sign(ex_fac_date - (v_asofdate + 13)),
    1,
    decode(sign(ex_fac_date - (v_asofdate + 19)),
    0,
    decode(is_tbd, 'no', 'wk3', null),
    null),
    null)
    from dual
    union all
    select decode(sign(ex_fac_date - (v_asofdate - 1)),
    0,
    decode(is_tbd, 'no', 'past_due', null),
    null)
    from dual
    where dt is not null
    Regards

  • Help needed in pl sql code

    Hi,
    I want to find out a particular column value which has newline characters in that field.
    example:
    CREATE TABLE TEST_MASTER(TEST_NBR NUMBER(10),TEST_DESC varchar2(46));
    INSERT INTO TEST_MASTER VALUES(2345,'hsjhiq')
    INSERT INTO TEST_MASTER VALUES(235,'hsj
    hiq')
    IN this case the second record which has test_nbr has new line character in TESBegin
    so, i can find this using:
    SELECT TEST_NBR FROM TEST_MASTER WHERE INSTR(TEST_DESC,CHR(10))>0
    It will give the test_nbr;
    My requirement is to send those test_nbr whichever have newline character to a mail id:
    I have tried the below code:
    But it says UTL_MAIL.SEND must be declared.
    i am using Oracle 10g XE.
    is there any other package i need to use?
    And one more thing is in case of one test_nbr we can store in a integer variable,
    In case of lot of test_nbrs how to store them and send in a mail:
    create or replace procedure findnewlinechar as
    test_nbr number(12);
    BEGIN
    SELECT TEST_nbr into test_nbr from test_master where instr(test_desc,chr(10))>0;
    SYSMAN.UTL_MAIL.send(sender => '[email protected]',
    recipients => '[email protected]',
    subject => 'Test Mail',
    message => ':test_nbr is having issue',
    mime_type => 'text; charset=us-ascii');
    END
    Any help will be appreciated.
    Thanks

    Pandeesh wrote:
    Hi,
    I want to find out a particular column value which has newline characters in that field.
    example:
    CREATE TABLE TEST_MASTER(TEST_NBR NUMBER(10),TEST_DESC varchar2(46));
    INSERT INTO TEST_MASTER VALUES(2345,'hsjhiq')
    INSERT INTO TEST_MASTER VALUES(235,'hsj
    hiq')
    IN this case the second record which has test_nbr has new line character in TESBegin
    so, i can find this using:
    SELECT TEST_NBR FROM TEST_MASTER WHERE INSTR(TEST_DESC,CHR(10))>0
    It will give the test_nbr;
    My requirement is to send those test_nbr whichever have newline character to a mail id:
    I have tried the below code:
    But it says UTL_MAIL.SEND must be declared.
    i am using Oracle 10g XE.
    is there any other package i need to use?UTL_SMTP is older alternative.
    Are you sure that you have a Mail Transport Agent (MTA) that can be configured to relay your messages?

  • Help needed in writing a procedure

    Guys, i need some more help.
    I am selecting one value using select by passing a parameter to that select statement which are stored in a file using utl_file package.
    Now, I want to use the output of that query and use that value to update a column in the same table.
    for ex:-
    select comm from emp where empno = &empno1;
    I want to use the comm value and update the comm value.
    update emp
    set comm = comm + 10
    where empno = &empno1
    Help Appreciated
    Thanks

    SQL> desc emp
    Name Null? Type
    EMPLOYEE_ID NOT NULL NUMBER(6)
    FIRST_NAME VARCHAR2(20)
    LAST_NAME NOT NULL VARCHAR2(25)
    EMAIL NOT NULL VARCHAR2(25)
    PHONE_NUMBER VARCHAR2(20)
    HIRE_DATE NOT NULL DATE
    JOB_ID NOT NULL VARCHAR2(10)
    SALARY NUMBER(8,2)
    COMMISSION_PCT NUMBER(2,2)
    MANAGER_ID NUMBER(6)
    DEPARTMENT_ID NUMBER(4)
    NET_SALARY NUMBER(12,2)
    SQL> select salary,COMMISSION_PCT,net_salary from emp where employee_id = 198;
    SALARY COMMISSION_PCT NET_SALARY
    2600 .1
    SQL> update emp
    2 set net_salary = salary + (select COMMISSION_PCT from emp where employee_id = &&empno)*salary
    3 where employee_id = &&empno
    4 /
    Enter value for empno: 198
    old 2: set net_salary = salary + (select COMMISSION_PCT from emp where employee_id = &&empno)*salary
    new 2: set net_salary = salary + (select COMMISSION_PCT from emp where employee_id = 198)*salary
    old 3: where employee_id = &&empno
    new 3: where employee_id = 198
    1 row updated.
    SQL> select salary,COMMISSION_PCT,net_salary from emp where employee_id = 198;
    SALARY COMMISSION_PCT NET_SALARY
    2600 .1 2860
    Hope this helps;

Maybe you are looking for

  • Can Apple TV play content purchased with two different Apple IDs (but on one computer)?

    I have one iMac with content in my iTunes from two different Apple IDs. All of this content is perfectly accessible on my computer. Before I ran the most recent software upgrade on my Apple TV 2, I was able to access all of this content (from both Ap

  • In Boot Camp assistant no network connection

    My network works fine, but error message appears "Can't download Windows Support Software because of a network problem." I am trying to use Boot Camp to partition my MacBook into a Windows PC. Also download of Windows Support Software is very slow.

  • Downgrade multiple .pdf files to ver 5 compatibility

    I'm looking for a way to script or at least manually in bulk convert multiple .pdf files created using Acrobat pro V9 down to a Acrobat V5 compatible format. I have an automated OCR application that can't yet read higher than that version. We have se

  • ITunes folder bigger then what is in itunes.

    i Recently noticed that the TVS shows folder on my computer is saying that it's 130GB (which is probably would be I have a lot) but when I check it on iTunes cause I have it all there it's only 55Gb on iTunes.  theres no duplicates either and no hidd

  • Help! Can't use scroll button (to select) when online

    Hi!  If anyone could help me, I would be eternally grateful. Just recently, when I go online on my BlackBerry Curve (not sure of the #, but I have a scroll button and not a trackball), I can't push the scroll button to select things.  For example, I