PL/SQL Function Syntax help please...

Can someone help me with the syntax here please? I am sure i am doing something wrong in my LOOP.
create or replace FUNCTION fcn_chk_dec(p_date number)
return NUMBER
as
--DECLARE
v_date NUMBER;
v_active NUMBER;
v_prev NUMBER;
v_delta NUMBER;
v_perc_delta NUMBER:
CURSOR c_prev_active IS
     select date,people,
lag(people,1) over (order by date)
     from stats
where date between to_date(p_date, 'YYYYMMDD')-2 and to_date(p_date, 'YYYYMMDD')-1
     order by date desc
BEGIN
     OPEN c_prev;
loop
     FETCH c_prev INTO v_date,v_active,v_prev;
     exit when c_prev%NOTFOUND;
     v_delta:=v_active-v_prev;
v_perc_delta:=trunc((v_delta/v_active*100),2)
end loop;
close c_prev;
return v_perc_delta;
END fcn_chk_dec;

what i am trying to do is create a funtion that will return one value for the first row that comes back.
here is my initial query. the reason i did not go with this query is because there are too many selects and i was told that's not good and slows down the system. Plus, i need to have a function call in another program that will access this function to compare it's output to a value in a table.
here was my initial start:
select date,people,delta,trunc((delta/people*100),2) as perc_delta
from (select date, people,people-prev_dly_people as delta
from
(select date,people,
lag(people,1) over (order by date) as prev_dly_people
from stats
where date between to_char(sysdate-2,'YYYYMMDD') and to_char(sysdate-1,'YYYYMMDD')
order by date desc))
basically, i have a table that has a total number of people. I want to get the percentage growth and decline from the most recent date and the date before it. This will give me a day to day percentage of people population change as of the most recent date.
I need this to be a function becaus i want to be able to pass any date i want into it and get the given delta percentage at the time for the people's population.
hope this makes sense.

Similar Messages

  • LOOP in PL/SQL Function Body Help Needed

    I have a PL/SQL function that I'm trying to run and use a LOOP but I'm having some problems. I know the loop works since it output's two commas for me, which is how many records the query used for the LOOP returns, but I can't seem to find the right syntax to reference the column.
    DECLARE
    str VARCHAR2(2000) := "";
    BEGIN
    IF :P21_GLOBAL_ID IS NOT NULL THEN
    FOR q IN (
    SELECT
    ID,
    DRAW_DATE,
    ENTERED_BY
    FROM
    SAMPLE_T
    WHERE
    ID = :P21_GLOBAL_ID
    ORDER BY
    DRAW_DATE
    LOOP
    str := str || q.ID || ',' ;
    END LOOP;
    END IF;
    RETURN STR
    END;

    I just sent you the credentials.
    Interestingly, I have this same code for the source of a textarea on the page and the source for a report. I then modified the PL/SQL code as follows:
    DECLARE
         varSelect VARCHAR2(32767) := ''; --hold query SELECT definition
         varFrom VARCHAR2(32767) := ''; --hold query FROM clause definition
         varWhere VARCHAR2(32767) := ''; --hold query WHERE clause definition
         varOrderBy VARCHAR2(32767) := ''; --hold query ORDER BY clause definition
         varQuery VARCHAR2(32767) := ''; --hold query definition
    BEGIN
         IF TRIM(LOWER(TO_NUMBER(:P21_GLOBAL_TEMPLATE_ID))) IS NOT NULL THEN
              varSelect := 'SELECT SUBJECT_ID';
              varSelect := varSelect || ', SUBJECT_ID AS PHI';
              varSelect := varSelect || ', SUBJECT_ID AS ENTER_DATA';
              varSelect := varSelect || ', SUBJECT_ID AS LOGISTICA';
    for varTempQuery IN (
    SELECT
    stc.question_name as field_name,
    sti.read_security,
    sti.write_security,
    nvl(sti.validation_type,decode(stc.validation_rules,'None','TEXT_FIELD')) as validation_type,
    sti.html_caption,
    nvl(upper(sti.html_display_type),'TEXTFIELD') as html_display_type,
    sti.html_table_row,
    sti.html_table_column
    FROM
    rix.study_subject_templates sst,
    rix.study_subject_Template_items sti,
    rix.questions stc
    WHERE
    TRIM(LOWER(TO_NUMBER(sst.ss_template_Id))) = TRIM(LOWER(TO_NUMBER(:P21_GLOBAL_TEMPLATE_ID)))
    AND TRIM(LOWER(TO_NUMBER(sst.ss_Template_id))) = TRIM(LOWER(TO_NUMBER(sti.ss_Template_id)))
    AND TRIM(LOWER(TO_NUMBER(sti.phi_qid))) = TRIM(LOWER(TO_NUMBER(stc.qid)))
    AND TRIM(LOWER(TO_CHAR(sti.template_item_Status))) <> TRIM(LOWER(TO_CHAR('RETIRED')))
    ORDER BY
    sti.html_Table_row,
    sti.html_table_column
    LOOP
    varSelect := varSelect || ', ' || varTempQuery.field_name;
    END LOOP;
              varFrom := 'FROM     RIX.SUBJECTS';
              varWhere := 'WHERE STUDY_ID = ' || TRIM(LOWER(TO_NUMBER(:P21_STUDY_ID )));
              varOrderBy := 'ORDER BY';
              varOrderBy := varOrderBy || ' subject_label ';
    varQuery := varSelect || ' ' || varFrom || ' ' || varWhere || ' ' || varOrderBy;
         ELSE
    varQuery := 'SELECT SUBJECT_ID FROM SUBJECTS WHERE study_id = :P21_STUDY_ID;';
         END IF;
    RETURN varQuery;
    END;
    When I run the page now, the textarea has the SQL statement generated from the first IF block, but the report using the statement from the ELSE block. I thought it maybe was a timing issue, but both blocks reference other fields on the page, so it doesn't seem to be a timing issue. Shouldn't be a condition issue either with the IF block as the textarea and report use the same source, but are evaluating differently.
    Very odd (to me at least).

  • Debugging PL/SQL Functions - Aaghh help!

    Hi. this is driving me nutz.
    here is my function:
    CREATE OR REPLACE FUNCTION MYPROC_GETCOMPID
    COMPNAME IN VARCHAR2,
    SITEID IN INTEGER
    RETURN NUMBER IS
    RVAL INTEGER;
    LOCALVAR INTEGER;
    BEGIN
    SELECT COMPUTERID INTO LOCALVAR
    FROM DATAUPLOAD.COMPUTER_LIST WHERE
    COMPUTERNAME = COMPNAME AND
    SITE = SITEID;
    EXCEPTION
    WHEN NO_DATA_FOUND THEN
    LOCALVAR := 0;
    RVAL:=LOCALVAR;
    RETURN RVAL;
    dbms_output.put_line('Local var');
    dbms_output.put_line(LOCALVAR);
    END MYPROC_GETCOMPID;
    It gets created fine. My question is, how the F can I create a bit pl/SQL to debug this?
    I tried:
    begin
    declare localin integer;
    localin := MYPROC_GETCOMPID('MYPC1',1);
    dbms_output.put_line('LOCALINT');
    dbms_output.put_line(LOCALINT);
    END;
    ... and I tried
    begin
    declare localin integer;
    localin = MYPROC_GETCOMPID('MYPC1',1);
    dbms_output.put_line('LOCALINT');
    dbms_output.put_line(LOCALINT);
    END;
    but boy does neither of these work.
    Could someone please tell me whats going wrong??
    AND can you see that exception in the function? thats there because for some reason a simple is null statement fails. any guesses as to why that is happening?
    many thanks for your time
    I

    Hi John,
    Sorry, I didn't include the error output because I thought that it would be obvious to people what was wrong with how I was attempting to call the function. I'm a bit of an oracle newbie (I'm sure thats more than obvious)
    Thanks for your help on the exception. I was just looking for reassurance that I was needing to handle the error like that. The data structure means that I shouldn't get too many rows (1:1 relationship between computername and computerID, thankfully!)
    Heres the responses from SQL*Plus (this is Oracle8i by the way). The responses are the same whether 'MYPC1' exists in the computer_list or not, so I am guessing that there is just something I am doing not quite right in the syntax for calling this function. (infact, see below for a hello world example that also fails).
    --here we see I have set up for screen output okay:-
    SQL> BEGIN
    2 dbms_output.put_line('Hello World!');
    3 END;
    4 /
    Hello World!
    PL/SQL procedure successfully completed.
    SQL>
    -- first failure:
    SQL> begin
    2 declare localin integer;
    3 localin = MYPROC_GETCOMPID('MYPC1',1);
    4 dbms_output.put_line('localin' );
    5 dbms_output.put_line(localin );
    6 END;
    7 /
    localin = MYPROC_GETCOMPID('MYPC1',1);
    ERROR at line 3:
    ORA-06550: line 3, column 9:
    PLS-00103: Encountered the symbol "=" when expecting one of the following:
    constant exception <an identifier>
    <a double-quoted delimited-identifier> table LONG_ double ref
    char time timestamp interval date binary national character
    nchar
    --- so I figure, this is a declarative syntax issue ( = as opposed to := ), so I try the following:
    SQL> begin
    2 declare localin integer;
    3 localin := MYPROC_GETCOMPID('MYPC1',1);
    4 dbms_output.put_line('localin' );
    5 dbms_output.put_line(localin );
    6 END;
    7 /
    localin := MYPROC_GETCOMPID('MYPC1',1);
    ERROR at line 3:
    ORA-06550: line 3, column 9:
    PLS-00103: Encountered the symbol "=" when expecting one of the following:
    constant exception <an identifier>
    <a double-quoted delimited-identifier> table LONG_ double ref
    char time timestamp interval date binary national character
    nchar
    The symbol "<an identifier>" was substituted for "=" to continue.
    ORA-06550: line 4, column 12:
    PLS-00103: Encountered the symbol "." when expecting one of the following:
    constant exception <an identifier>
    <a double-quoted delimited-identifier> table LONG_ double ref
    char time timestamp interval date binary national charac
    ORA-06550: line 5, column 12:
    PLS-00103: Encountered the symbol "." when expecting one of the following:
    constant exception <an identifier>
    <a double-quoted delimited-identifier> table LONG_ double ref
    char time timestamp interval date binary national charac
    ORA-06550: line 6, column 1:
    PLS-00103: Encountered the symbol "END" when expecting one of the following:
    begin function package pragma
    --- finally , 'hello world' failure :
    SQL> begin
    2 declare localst varchar(11);
    3 localst = 'hello world';
    4 dbms_output.put_line('localst');
    5 dbms_output.put_line(localst);
    6 END;
    7 /
    localst = 'hello world';
    ERROR at line 3:
    ORA-06550: line 3, column 9:
    PLS-00103: Encountered the symbol "=" when expecting one of the following:
    constant exception <an identifier>
    <a double-quoted delimited-identifier> table LONG_ double ref
    char time timestamp interval date binary national character
    nchar

  • Analytical function syntax help

    The following query sorts by most occuring hesid descedning and requires TWO full table scans of the episodes_full_test table :
    create table episodes_full_test (epikey number, hesid number, dob date) tablespace analysis_ip_d;
    insert into episodes_full_test values (100, 20, to_date('31-07-1975','DD-MM-YYYY'));
    insert into episodes_full_test values (101, 20, to_date('31-07-1975','DD-MM-YYYY'));
    insert into episodes_full_test values (102, 20, to_date('31-07-1975','DD-MM-YYYY'));
    insert into episodes_full_test values (103, 20, to_date('31-07-1975','DD-MM-YYYY'));
    insert into episodes_full_test values (104, 10, to_date('31-07-1985','DD-MM-YYYY'));
    insert into episodes_full_test values (105, 30, to_date('31-07-1995','DD-MM-YYYY'));
    insert into episodes_full_test values (106, 30, to_date('31-07-1995','DD-MM-YYYY'));
    insert into episodes_full_test values (107, 30, to_date('31-07-1995','DD-MM-YYYY'));
    commit;
    select eft.hesid, eft.epikey, eft.dob
    from episodes_full_test eft
    join (select hesid, count(hesid) count_hesid
    from episodes_full_test
    group by hesid) v1
    on eft.hesid = v1.hesid
    order by v1.count_hesid desc, eft.epikey;     
    HESID EPIKEY DOB
    20 100 31/07/1975
    20 101 31/07/1975
    20 102 31/07/1975
    20 103 31/07/1975
    30 105 31/07/1995
    30 106 31/07/1995
    30 107 31/07/1995
    10 104 31/07/1985
    I'm sure there's a way to use analytical functions such that Oracle only needs to perform ONE full table scan of episodes_full_test, but I can't figure out the syntax
    Can anyone advise please ?
    (Oracle 9r2)
    Thanks, Gus

    Thank you for providing the create table, insert commands and required output as it makes answering the question much easier (once I'd removed the tablespace specification)
    SQL> select hesid, epikey, dob
      2  from
      3      (
      4      select eft.hesid, eft.epikey, eft.dob,
      5          count(*) over (partition by eft.hesid) count_hesid
      6      from episodes_full_test eft
      7      )
      8  order by count_hesid desc;
         HESID     EPIKEY DOB
            20        100 31-JUL-75
            20        101 31-JUL-75
            20        102 31-JUL-75
            20        103 31-JUL-75
            30        105 31-JUL-95
            30        106 31-JUL-95
            30        107 31-JUL-95
            10        104 31-JUL-85
    8 rows selected.
    SQL>

  • I can't figure out how to parametrize my SQL statement - lil help please?

    Hi all,
    I was deleting records via the string-concatenation method, which I've come to understand is bad, due to security any possibly other issue. I want very much to parametrize my delete statement, but I just can't see to get it to work
    The code below is my best shot at it - it returns an Oracle exception about "invalid table name". I assume that means the the substitution of the parameter for the value simply hasn't been performed, so the database is trying to process literally ":oracleTable", and the like.
    Can someone please set me straight with this?
    Thanks for any help,
    cdj
              public static void DeleteTest(DateTime start, DateTime end)
                   ParentFormStatusBar.Text = "Deleting records...";
                   string oracleStart = start.ToString("dd-MMM-yyyy");
                   string oracleEnd = end.ToString("dd-MMM-yyyy");
                   string strConn = "CONNECTSTRING";
                   OracleConnection dc_UAT = new OracleConnection(strConn);
                   string oracleTable = "DATABASETABLE";
                   OracleCommand oc = new OracleCommand();
                   oc.BindByName = true;
                   oc.CommandText = "delete from :oracleTable where as_of_date between :oracleStart and :oracleEnd";
                   oc.Connection = dc_UAT;
                   OracleParameter tableParam = new OracleParameter();
                   tableParam.ParameterName = "oracleTable";
                   tableParam.Value = oracleTable;
                   tableParam.OracleDbType = OracleDbType.Varchar2;
                   tableParam.Direction = ParameterDirection.Input;
                   OracleParameter startParam = new OracleParameter();
                   startParam.ParameterName = "oracleStart";
                   startParam.Value = start;
                   startParam.OracleDbType = OracleDbType.Date;
                   startParam.Direction = ParameterDirection.Input;
                   OracleParameter endParam = new OracleParameter();
                   endParam.ParameterName = "oracleEnd";
                   endParam.Value = end;
                   endParam.OracleDbType = OracleDbType.Date;
                   endParam.Direction = ParameterDirection.Input;
                   oc.Parameters.Add(tableParam);
                   oc.Parameters.Add(startParam);
                   oc.Parameters.Add(endParam);
                   MessageBox.Show(tableParam.Value.ToString()+ "\n" + oc.CommandText+"\n" + "Params: " + oc.Parameters.Count);
                   int rowsAffected;
                   try
                        dc_UAT.Open();
                        rowsAffected = oc.ExecuteNonQuery();
                        dc_UAT.Close();
                        ParentFormStatusBar.Text = rowsAffected.ToString() + " records deleted.";
                   catch(Exception ex)
                        ParentFormStatusBar.Text = "Delete error: " + ex.Message;
              }

    It helped oodles - thanks a jillion!
    Is there a master list somewhere of things you can and cannot parametrize? That would be cool.
    I guess I was thinking of parameters oversimplistically as just a canned-search-and-replace-text function or something like that.
    Thanks again,
    cdj

  • SQL query - syntax help

    Hi All,
    I have a table that has 2 columns X, and Y.
    create table temp(
    x number(5);
    y number (5);
    );I am trying to write a query to check both columns, here is what I mean.
    SELECT CASE
                 IF X = 1 AND Y = 0 THEN 3
              IF X = 2 AND Y = 1 THEN 4
              IF X  = 4 AND Y IS NULL THEN 5
          END AS STATUS
    FROM .....temp ...etc.I know what I want but having problems with the syntax.
    Thanks in Advance for your help.
    I'm using Oracle 11g, SQL Dev 3.0

    select case when x = 1 and y = 0 then 3
                when x = 2 and y = 1 then 4
                when x = 4 and y is null then 5
                else null
            end ans
      from ...for more on the case syntax see either one of these links.
    http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14261/case_statement.htm
    http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/expressions004.htm

  • SQL INSERT problem - help please

    Hello,
    I'm having a problem with INSERT statement.
    There is a "ShowFinal.jsp" page, which is a list of candidates who selected from the second
    interview. The user picked some candidates from the list and conduct the 3rd interview. After
    he check suitable candidates(who are selected from the 3rd interview) from the list , enter
    basic salary for every selected candidate, enter date of interview and finally submit the form.
    These data should be save into these tables.
    FinalSelect(nicNo,date)
    EmpSalary(nicNo,basicSal)
    In this "ShowFinal.jsp" page, it validates the following conditions using JavaScript.
    1) If the user submit the form without checking at least one checkbox, then the system should be
    display an alert message ("Please select at least one candidate").
    2) If the user submit the form without entering the basic salary of that candidate which was
    checked, then the system should be display an alert message ("Please enter basic salary").
    These are working well. But my problem is how to wrote the "AddNewFinal.jsp" page to save these
    data into the db.
    Here is my code which I have wrote. But it points an error.
    "AddNewFinal.jsp"
    String interviewDate = request.getParameter("date");
    String[] value = request.getParameterValues("ChkNicno");
    String[] bs = request.getParameterValues("basicSal");
    String sql ="INSERT INTO finalselect (nicNo,date) VALUES(?,?)";
    String sql2 ="INSERT INTO EmpSalary (nicNo,basicSal) VALUES(?,?)";
    for(int i=0; i < value.length; i++){
         String temp = value;     
         for(int x=0; x < bs.length; x++){
              String basic = bs[x];
              pstmt2 = connection.prepareStatement(sql2);
              pstmt2.setString(1, temp);
              pstmt2.setString(2, basic);
              int RowCount1= pstmt2.executeUpdate();
         pstmt1 = connection.prepareStatement(sql);
         pstmt1.setString(1, temp);
         pstmt1.setString(2, interviewDate);
         int RowCount= pstmt1.executeUpdate();
    Here is the code for "ShowFinal.jsp".
    <form name="ShowFinal" method="POST" action="AddNewFinal.jsp" onsubmit="return checkEmpty() &&
    ValidateDate();">
    <%--  Loop through the list and print each item --%>
    <%
         int iCounter = 0; //counter for incremental value
         while (igroups.hasNext()) {
              Selection s = (Selection) igroups.next();
              iCounter+=1; //increment
    %>
    <tr>
         <td style="background-color:ivory" noWrap width="20">
         <input type="checkbox" name="<%= "ChkNicno" + iCounter %>"      
    value="<%=s.getNicno()%>"></td>
            <td style="background-color:ivory" noWrap width="39">
                 <%= s.getNicno() %>  </td>
         <td style="background-color:ivory" noWrap width="174">
              <input type="text" name="<%= "basicSal" + iCounter %>" size="10"> </td>
    </tr>
    <%
    %>
    Date of interview<input type="text" name="date" size="17"></td>
    <input type="submit" value="APPROVE CANDIDATE" name="B1" style="border: 1px solid #0000FF">
    </form>........................................................
    Here is the error generated by TOMCAT.
    root cause
    java.lang.NullPointerException
         at org.apache.jsp.AddNewFinal_jsp._jspService(AddNewFinal_jsp.java:70)
         at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:137)
    I have goto the file "AddNewFinal_jsp.java". The line 70 points to the following line.
    for(int i=0; i < value.length; i++){ [/b]
    Please can someone help me to solve this problem? Please help me to do this task.
    Thanks.

    Hi Casabianca ,
    It is clearly that your problem is not on the database end, more like a servlet/jsp issue.
    I will not comment on the javascript portion, but rather the 2 jsps.
    a simple way to trace what's go wrong is to check the final result (the html code) of the first jsp (showFinal.jsp), and compare against what is expected by the 2nd jsp (AddNewFinal.jsp). Most browser do provide "view source" on the page visited.
    the following code
    <input type="checkbox" name="<%= "ChkNicno" + iCounter %>" value="<%=s.getNicno() %>">
    <input type="text" name="<%= "basicSal" + iCounter %>"
    would likely to be "translated" to html code something as follow:
    <input type="checkbox" name=""ChkNicno0" value="nicNo>">
    <input type="text" name="basicSal0">
    the original code in "AddNewFinal.jsp" using
    request.getParameterValues("ChkNicno");
    which looking for a none exist http request parameter (sent as "ChkNicno0",etc but look for "ChkNicno"), which has explained before.
    the second attempt to use String[] value = request.getParameterValues("ChkNicno" + iCounter); give Cannot resolove symbol :iCounter. because iCounter never defined in the 2nd jsp!
    Most of the error message do give clue to cause of error... : )
    not too sure on your intension, assume you wish to update only those selected (checked) row to db.
    some suggestions:
    1) <input type="text" name="ChkNicno" size="10"> </td>...
    <input type="text" name="basicSal" size="10"> instead.
    then use javascript to based on checked element index (refer to javascript spec for more details), for those index not checked, clear off the correspond index "basicSal" field value.
    e.g. ChkNicno[1] is not checked, empty basicSal[1] value before submission.
    This will give us only selected rows values.
    2) retain the code
    String[] value = request.getParameterValues("ChkNicno");
    String[] bs = request.getParameterValues("basicSal");at 2nd jsp, as now the http request will pass parameters using "ChkNicno" and "basicSal".
    3) some change to the code for optimization
    for(int i=0; i < value.length; i++){
         String temp = value;     
         for(int x=0; x < bs.length; x++){
              String basic = bs[x];
              pstmt2 = connection.prepareStatement(sql2);
              pstmt2.setString(1, temp);
              pstmt2.setString(2, basic);
              int RowCount1= pstmt2.executeUpdate();
         pstmt1 = connection.prepareStatement(sql);
         pstmt1.setString(1, temp);
         pstmt1.setString(2, interviewDate);
         int RowCount= pstmt1.executeUpdate();
    to
    pstmt1 = connection.prepareStatement(sql);
    pstmt2 = connection.prepareStatement(sql2);
    for(int i=0; i < value.length; i++){
         String temp = value;     
         for(int x=0; x < bs.length; x++){
              String basic = bs[x];
              pstmt2.setString(1, temp);
              pstmt2.setString(2, basic);
              int RowCount1= pstmt2.executeUpdate();
         pstmt1.setString(1, temp);
         pstmt1.setString(2, interviewDate);
         int RowCount= pstmt1.executeUpdate();
    preparestatement created once should be sufficient as we do not change the sql statement throughout the loop.
    there are better solutions out there, this just some ideas and suggestions.Do try out if you wish.
    Hope it helps. : )

  • SQL on CUIC help please!?

    Hi Everyone.
    We have recently had the outbound option put in and shortly identified a bug which was reported to Cisco (CSCud29354) which makes real time monitoring of abandoned rates very difficult.
    My SQL is very limited but I managed to write 2 queries, one that would give me the amount of connected calls by campaign and one that would give me the amount of abandoned calls by campaign.
    I got in touch with the company that implemented the system and asked them to combine the 2 queries and add a formula for working out the abandon rate. Whilst they couldn't give me something that was tested on CUIC they sent me the below which gives an error of:
    "Create the parameters or correct the query syntax and  recreate the parameters. Incorrect syntax near ' '
    If someone could help that would be great as I can't get my head around how the query works - below is what I was sent from the company:
    As you know, the solution requires the merging of the 2 queries.  The method used below is to embed the Abandoned call count query by CampaignName into a nested select or aka sub-query. The sub-query references back to the CampaignName to ensure it is fetching the count required for the CampaignName only. This is achieved via the names results sets X and Y.
    I’ve also included the syntax for calculating the Drop rate based on the retrieved values per CampaignName.
    There may be some tweaks required that are relevant to your appropriate SQL engine but the below should provide a good starting point.
    SELECT  CampaignName,
    SUM(Connected) AS Conn, (
    SELECT SUM(Abandoned) AS ABD
    FROM
    SELECT CampaignName, DateTime, COUNT(CallResult) as "Abandoned"
    FROM Dialer_Detail(nolock), Campaign
    WHERE Dialer_Detail.CampaignID = Campaign.CampaignID AND
    CampaignName = Y.CampaignName
    AND CallGUID IS NOT NULL
    AND CallResult = 20
    GROUP BY CampaignName, DateTime
    UNION ALL
    SELECT CampaignName, DateTime, COUNT(CallResult) as "Abandoned"
    FROM Dialer_Detail(nolock), Campaign
    WHERE Dialer_Detail.CampaignID = Campaign.CampaignID AND
    CampaignName = Y.CampaignName
    AND CallGUID IS NOT NULL
    AND CallResult = 16
    GROUP BY CampaignName, DateTime
    ) X
    WHERE DateTime >= :StartDate
    And DateTime <= :EndDate
    And X.CampaignName = Y.CampaignName
    GROUP BY  CampaignName
    WITH ROLLUP) AS ABD2,
    ((ABD2/Conn)*100) as “Drop Rate”
    FROM
    SELECT CampaignName, DateTime, COUNT(CallResult) as "Connected"
    FROM Dialer_Detail(nolock), Campaign
    WHERE Dialer_Detail.CampaignID = Campaign.CampaignID
    AND CallGUID IS NOT NULL
    AND CallResult = 20
    GROUP BY CampaignName, DateTime
    UNION
    SELECT CampaignName, DateTime, COUNT(CallResult) as "Connected"
    FROM Dialer_Detail(nolock), Campaign
    WHERE Dialer_Detail.CampaignID = Campaign.CampaignID
    AND CallGUID IS NOT NULL
    AND CallResult = 16
    GROUP BY CampaignName, DateTime
    UNION
    SELECT CampaignName, DateTime, COUNT(CallResult) as "Connected"
    FROM Dialer_Detail(nolock), Campaign
    WHERE Dialer_Detail.CampaignID = Campaign.CampaignID
    AND CallGUID IS NOT NULL
    AND CallResult = 10
    GROUP BY CampaignName, DateTime
    UNION
    SELECT CampaignName, DateTime, COUNT(CallResult) as "Connected"
    FROM Dialer_Detail(nolock), Campaign
    WHERE Dialer_Detail.CampaignID = Campaign.CampaignID
    AND CallGUID IS NOT NULL
    AND CallResult = 14
    GROUP BY CampaignName, DateTime
    UNION
    SELECT CampaignName, DateTime, COUNT(CallResult) as "Connected"
    FROM Dialer_Detail(nolock), Campaign
    WHERE Dialer_Detail.CampaignID = Campaign.CampaignID
    AND CallGUID IS NOT NULL
    AND CallResult = 21
    GROUP BY CampaignName, DateTime
    UNION
    SELECT CampaignName, DateTime, COUNT(CallResult) as "Connected"
    FROM Dialer_Detail(nolock), Campaign
    WHERE Dialer_Detail.CampaignID = Campaign.CampaignID
    AND CallGUID IS NOT NULL
    AND CallResult = 23
    GROUP BY CampaignName, DateTime
    UNION
    SELECT CampaignName, DateTime, COUNT(CallResult) as "Connected"
    FROM Dialer_Detail(nolock), Campaign
    WHERE Dialer_Detail.CampaignID = Campaign.CampaignID
    AND CallGUID IS NOT NULL
    AND CallResult = 24
    GROUP BY CampaignName, DateTime
    ) Y
    WHERE DateTime >= :StartDate
    And DateTime <= :EndDate
    GROUP BY  CampaignName
    WITH ROLLUP
    Thanks a lot
    Russell Healey

    Sometimes, the most obvious things are the harder to see...
    The correct is 'order by', not 'order_by'!

  • SQL profile - need help please

    Hi folks
    Enterprise Manager suggested a better plan for me (Oracle 10.2.3 /
    Solaris64) and I went for it. However, it doesn't look like it's being
    used at all. EM still shows the SQL using the inefficient plan.
    So I reckoned the force_match was the issue (even tho the SQL uses all bind variables - that might not be right though?)
    SQL> l
    1 begin
    2 dbms_output.put_line(
    3 dbms_sqltune.accept_sql_profile(
    4 task_name => 'SQL_TUNING_1271147514497',
    5 name => 'SYS_SQLPROF_0149fdae48460004',
    6 replace => true,
    7 force_match => true)
    8 );
    9* end;
    SQL> /
    SYS_SQLPROF_0149fdae48460004
    PL/SQL procedure successfully completed.
    SQL> select force_matching from dba_sql_profiles where name =
    'SYS_SQLPROF_0149fdae48460004';
    FOR
    NO
    Can anyone advise why this might be please ? The Tuning ID in EM is
    correct (that's where I got it from).
    Basically, I have
    Operation Object Object Type Order Rows Size (KB) Cost Time (sec) CPU
    Cost I/O Cost
    SELECT STATEMENT
    11
    743
    NESTED LOOPS
    10 4 0.496 743 9 39626522 733
    NESTED LOOPS
    7 4 0.453 735 9 39563064 725
    VIEW
    4 4 0.254 730 9 39499102 720
    HASH UNIQUE
    3 4 0.156 730 9 39499102 720
    FILTER
    2
    INDEX RANGE SCAN
    HCREF.S436_IX1 INDEX (UNIQUE) 1 4 0.156 729 9 35552327 720
    TABLE ACCESS BY INDEX ROWID
    HCREF.F436 TABLE 6 1 0.050 2 1 16553 2
    INDEX UNIQUE SCAN
    HCREF.F436_UK1 INDEX (UNIQUE) 5 1
    1 1 9021 1
    TABLE ACCESS BY INDEX ROWID
    HCREF.MMLINE TABLE 9 1 0.011 2 1 16673 2
    INDEX UNIQUE SCAN
    HCREF.A436_IX1 INDEX (UNIQUE) 8 1
    1 1 9021 1
    MMLINE should be above F436 in the plan for optimum performance. All
    stats are up to date, and the TEST system does it the right way. I
    can't find anything to account for the different plan (sga, pga, IO,
    parameters, anything!).
    Any help as to how I can force LIVE to do what TEST is doing? If the
    force-match takes effect, I'd like to assume that would have sorted
    it ? We have no access to the underlying SQL.
    SELECT /*+ LEADING INDEX(S_ S436_IX1) INDEX(SHAPE F436_UK1)
    INDEX(MMLINE A436_IX1) */ HCREF.MMLINE.FEATCODE,
    HCREF.MMLINE.SHAPE ,S_.eminx,S_.eminy,S_.emaxx,S_.emaxy ,SHAPE.fid,SHAPE.numofpts,SHAPE.entity,SHAPE.points,SHAPE.rowid
    FROM (SELECT /*+ INDEX(SP_ S436_IX1) */ DISTINCT sp_fid, eminx, eminy,
    emaxx, emaxy FROM HCREF.S436 SP_ WHERE SP_.gx >= :1 AND SP_.gx <= :2
    AND SP_.gy >= :3 AND SP_.gy <= :4 AND SP_.eminx <= :5 AND SP_.eminy
    <= :6 AND SP_.emaxx >= :7 AND SP_.emaxy >= :8) S_ , HCREF.MMLINE ,
    HCREF.F436 SHAPE WHERE S_.sp_fid = SHAPE.fid AND S_.sp_fid =
    HCREF.MMLINE.SHAPE
    Thanks
    A

    Anyone got any suggestions ? Much appreciated, thanks.
    A

  • ForEach items syntax help please

    This shouldn't be a problem but it is. I have a JSP. I am sending it an attribute that is a collection by calling setAttribute() on the request and then dispatching to the JSP from my front controller servlet. I want to iterate through the collection. The name of the attribute is "changeRequets" and I have tried accessing it without any scope qualifiers and with scope qualifiers and no matter what, this forEach produces no data. I have verified that the JSP is receiving data, because I've accessed the request attribute separately without JSTL. What is wrong with the following please?
       <c:forEach var="chgRequest" items="${requestScope.request.changeRequests}">
                    <tr>
                        <td>
                            <input type="radio" name="crButton" value="<c:out value="${chgRequest.crChangeRequestID}"/>" <c:if test="${status.first}">checked</c:if> />
                        </td>
                    </tr>
    </c:forEach>This produces no data, no rows. I don't get it. I can't find anything in my JSTL book that helps. Thanks.
    Ken

    Ignore the previous reply
    change it to the following
    <c:forEach var="chgRequest" items="${changeRequests}">
                    <tr>
                        <td>
                            <input type="radio" name="crButton" value="<c:out value="${chgRequest.crChangeRequestID}"/>" <c:if test="${status.first}">checked</c:if> />
                        </td>
                    </tr>
    </c:forEach>

  • SQL problem URGENT help PLEASE

    SQL> select period_number, sum(gross_amt)
    2 from mpy_payslip_headers
    3 where payroll_year = 2001
    4 and business_group_id = 'E4'
    5 and employee_number = '366'
    6 and period_number between 12 and 13
    7 group_by period_number;
    group_by period_number
    ERROR at line 7:
    ORA-00933: SQL command not properly ended
    WHY THIS ERROR? As far as I know it is possible.
    Thanks in advance,
    Marija

    Sometimes, the most obvious things are the harder to see...
    The correct is 'order by', not 'order_by'!

  • SQL insert statement help please

    alternative is to have the table with field dateadd with default value of getdate()   - then do not include in your insert statement - then the modify date use and update - starting point - my two cetns

    Hi all I'm trying to go a little out of my comfort level here and was hoping for some advice. I have a sql table that has 2 date fields. an add and a modified. If the modified date is null then I want to calculate on the date added. Otherwise I'd like to calculate on the modified date.
    Here is a simplified version of what I'm trying to accomplish.
    Hope it makes sense what I'm trying to do.
    SQLSELECT field1,field2.... ,dateAdded , dateModifiedINTO tblOutputFROM tblInput/* some pseudo code here */WHERE (if dateModified not null then ( dateModified

  • SQL Functions Sintax

    LabVIEW 8.5 and Database Connectivity Toolkit and Microsoft Jet 4.0 OLE DB Provider
    I have built the DB structure using the MS ACCESS 2003. One of it´s fileds, I have defined as Short Date, as I had beleived that I was going to get just the date, for instance, 06/07/2007, but instead of this I get the day, 06/07/2007 plus the time, 12:24:34, all together 06/07/2007 12:24:34
    My two questions :
    1) how to store in the date base, just the date, no the time
    2) the SQL Function syntax to display just the date. I thought the correct sintax was : Select SUBSTR(xxx,0,10) from Table. Where xxx is the name of the field in the Table, 0 is the first character of the string xxx and it´s length
    Thanks
    Simbani

    To answer your direct questions:
    1) The "Date/Time" data type is similar to the smalldatetime data type in SQL Server. This stores time information. Can't change this. If you only want to store date information then you need to make your column's datatype to be of character-type. I think "Text" is what Access 2003 uses. Of course, this means you lose anything related to dealing with that column as a date.
    2) If Access 2003 follows the same syntax as SQL Server's T-SQL, the SUBSTR won't work with a column that is a date/time data type. That function would only work with strings. This means you have to first convert the column value to a string. I know that in SQL Server's T-SQL the CAST and CONVERT functions would be used. Have no idea what they would be in Access 2003, so you'll need to check the manual.

  • SQL Function for calculating IP Address

    Hi Experts ,
    I have an IP Range i need to find out the First Host detail for the IP using a SQL scalar function .
    Example : 11.30.10.40
    Subnet Mask is 26
    Output required
    First host: 11.30.10.1
    am confused how i can derive the first host  values from a sql function kindly help .
    Thanks
    Priya

    DECLARE @Mask TINYINT = 26;
    DECLARE @AddressIP VARCHAR(15)= '11.30.10.40';
    DECLARE @AddressValue BIGINT = PARSENAME(@AddressIP,4)*CAST(256*256*256 AS BIGINT)+PARSENAME(@AddressIP,3)*256*256+PARSENAME(@AddressIP,2)*256+PARSENAME(@AddressIP,1);
    WITH
    n0(n) AS (SELECT 0 UNION ALL SELECT 0)
    ,n1(n) AS (SELECT 0 FROM n0 a CROSS JOIN n0)
    ,n2(n) AS (SELECT 0 FROM n1 a CROSS JOIN n1)
    ,n3(n) AS (SELECT 0 FROM n2 a UNION ALL SELECT 0 g FROM n2)
    ,t (n) AS (SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM n3)
    ,bits(b,v) AS (SELECT n,POWER(CAST(2 AS BIGINT),32-n) FROM t)
    SELECT @AddressIP [Address]
    ,CAST((SUM(v) / 256 / 256 / 256) % 256 AS VARCHAR(3)) + '.' + CAST((SUM(v) / 256 / 256) % 256 AS VARCHAR(3)) + '.' + CAST((SUM(v) / 256) % 256 AS VARCHAR(3)) + '.' + CAST(SUM(v) % 256 AS VARCHAR(3)) [Netmask]
    ,CAST(((SUM(v) ^ 0xFFFFFFFF) / 256 / 256 / 256) % 256 AS VARCHAR(3)) + '.' + CAST(((SUM(v) ^ 0xFFFFFFFF) / 256 / 256) % 256 AS VARCHAR(3)) + '.' + CAST(((SUM(v) ^ 0xFFFFFFFF) / 256) % 256 AS VARCHAR(3)) + '.' + CAST(((SUM(v) ^ 0xFFFFFFFF)) % 256 AS VARCHAR(3)) [Wildcard]
    ,CAST(((@AddressValue & SUM(v)) / 256 / 256 / 256) % 256 AS VARCHAR(3)) + '.' + CAST(((@AddressValue & SUM(v)) / 256 / 256) % 256 AS VARCHAR(3)) + '.' + CAST(((@AddressValue & SUM(v)) / 256) % 256 AS VARCHAR(3)) + '.' + CAST(((@AddressValue & SUM(v))) % 256 AS VARCHAR(3)) + '/' + CAST(MAX(b) AS VARCHAR(2)) [NetworkAddress]
    ,CAST(((((SUM(v) ^ 0xFFFFFFFF)) | @AddressValue) / 256 / 256 / 256) % 256 AS VARCHAR(3)) + '.' + CAST(((((SUM(v) ^ 0xFFFFFFFF)) | @AddressValue) / 256 / 256) % 256 AS VARCHAR(3)) + '.' + CAST(((((SUM(v) ^ 0xFFFFFFFF)) | @AddressValue) / 256) % 256 AS VARCHAR(3)) + '.' + CAST(((((SUM(v) ^ 0xFFFFFFFF)) | @AddressValue)) % 256 AS VARCHAR(3)) [BroadcastAddress]
    ,CAST(((@AddressValue & SUM(v)) / 256 / 256 / 256) % 256 AS VARCHAR(3)) + '.' + CAST(((@AddressValue & SUM(v)) / 256 / 256) % 256 AS VARCHAR(3)) + '.' + CAST(((@AddressValue & SUM(v)) / 256) % 256 AS VARCHAR(3)) + '.' + CAST(((@AddressValue & SUM(v))) % 256 + 1 AS VARCHAR(3)) [FirstHost]
    ,CAST(((((SUM(v) ^ 0xFFFFFFFF)) | @AddressValue) / 256 / 256 / 256) % 256 AS VARCHAR(3)) + '.' + CAST(((((SUM(v) ^ 0xFFFFFFFF)) | @AddressValue) / 256 / 256) % 256 AS VARCHAR(3)) + '.' + CAST(((((SUM(v) ^ 0xFFFFFFFF)) | @AddressValue) / 256) % 256 AS VARCHAR(3)) + '.' + CAST(((((SUM(v) ^ 0xFFFFFFFF)) | @AddressValue)) % 256 - 1 AS VARCHAR(3)) [LastHost]
    ,(((SUM(v) ^ 0xFFFFFFFF)) | @AddressValue) - (@AddressValue & SUM(v)) - 1 [TotalHostCount]
    FROM bits WHERE @Mask BETWEEN 1 AND 32 AND b <= @Mask
    Jon

  • Calling pl/sql function in CKM...pls help

    Hi,
    I have made a call to PL/SQL function in CKM customization. The code is :
    declare
    L_PMG_VALUE VARCHAR(3);
    begin
    L_PMG_VALUE:='PMG';
    VALIDATE_PMG_VALUE(L_PMG_VALUE);
    end;
    When i run it, it throws error which says:
    6550 : 65000 : java.sql.SQLException: ORA-06550: line 1, column 64:
    PLS-00221: 'VALIDATE_PMG_VALUE' is not a procedure or is undefined
    ORA-06550: line 1, column 64:
    PL/SQL: Statement ignored
    Function is compiled in the database and its working. I have selected the Technology as Oracle and correct Schema Name.
    Please help

    Hi,
    try the following way. i have not tried ....i think it helps you.
    In which schema you have created that procedure.
    Does the ODI user mantioned in topology have execute permissions on the procedure? if the ODI user have execute previlage on the procedure then in CKM customisation call the procedure like <schema>.<procedure>.
    Please let me know any issues.
    Thanks,

Maybe you are looking for