Function query

hi,
Using function need to find the student id is present in the table or not.
Is this right or i need to change the code. Please advice me
create or replace function stud_exist
(id in number)
return number
is
cnumber number;
cursor c1 is
select stu_id,stud_name from student_tb
where stud_id = id;
begin
open c1;
fetch c1 into cnumber;
if c1%found then
dmbs_output.put_line ("exist")
else
dbms_output.put_line ("notexist")
end if
close c1;
return cnumber;

Ramin Hashimzadeh wrote:
why you want to use function? if there is no way then i think this method is correct one:I DO NOT think, this is the CORRECT method..
CREATE OR REPLACE FUNCTION STUD_EXIST(ID IN NUMBER) RETURN NUMBER IS
CNUMBER NUMBER;
BEGIN
--"Why to use DUAL, EXISTS and all? Just select from the STUDENT_TAB"
--"Just add  one more filter( and rownum = 1) if you want to get rid of multiple records
SELECT ID
INTO CNUMBER
FROM DUAL
WHERE EXISTS
(SELECT STU_ID, STUD_NAME  --"Why two columns are selected here? What is the purpose?
FROM STUDENT_TB WHERE STUD_ID = ID);
RETURN CNUMBER;
EXCEPTION
WHEN NO_DATA_FOUND THEN
RETURN NULL;
END;

Similar Messages

  • How to Create a Functiona Query

    Dear all,
    Could any body detail me how to create a functional query. Please give me step by step procedure to create a query.
    I would appreciate if you can give me a material with screen shots. Your help will be highly appreciated.
    Thank you
    Raghu Ram

    Hi Raghu,
               Go through this document it may help you,
    SAP Query
    Step 1: Create User Group – SQ03
    Follow the menu path – SAP Menu > Tools > ABAP Workbench > Utilities > SAP Query > User Groups
    a) In the User Group: Initial Screen -
    Enter User Group Code (self named)
    Click on “Create”
    b) In the User Group (Code): Create or Change pop-up window -
    Enter the User Group Description
    Click on “Save”
    c) In the Create Object Directory Entry pop-up window -
    Ö Click on “Local Object” button
    Ö The User Group Created is saved
    Step 2: Create User Group – SQ02
    Follow the menu path – SAP Menu > Tools > ABAP Workbench > Utilities > SAP Query > Infosets
    a) In the Infoset: Initial screen -
    Ö Enter Infoset Code (self named)
    Ö Click on “Create” button
    b) In the Infoset: Title & Database Screen -
    Ö Enter Description of Infoset in the “Name” field
    Ö In the Data Source selection: Select appropriate Data Source by clicking
    the radio button
    · Source the data can either be multiple tables OR single table. There are 4
    options for the user to select from
    Ö Click on “Continue” (Enter)
    Ö Selected Table gets displayed in the Infoset : Initial Screen
    c) In the Infoset: Initial Screen -
    Ö Click on “Insert Table” button
    d) In the Add Table Screen -
    Ö Enter the Table Name that is to be inserted
    Ö Click “Continue” (Enter)
    e) In the Infoset: Initial Screen -
    Ö Click on “Back” button
    f) In the Field Group Defaults pop-up Screen -
    Ö Select Appropriate Field Group Option by clicking on the radio button
    · there are 3 options to select from. User can select Empty Field Group
    option and then select the data fields in the steps explained further.
    Alternatively, User can select an option which clubs all the data fields
    From all the tables selected
    Ö Click “Continue” (Enter)
    g) In the Change Infoset Screen -
    · the left side lists the Tables that the user has selected in step b, c & d
    · In the right side, system creates field groups, one for each table listed in the
    left part. Initially, the Field Groups are empty
    Ö In the Left Side, Click on the arror next to the table name and expand and
    display all the data fields in the table
    Ö Select a Data Field from the expanded Table view, which is to be added to
    the Field Group on the right.
    Ö Select a Field Group on the right side, in which Data Field selected above
    has to be added
    Ö Right click on the Data Field selected and click on “Add Field to Field Group”
    Ö The selected Data Field gets added to the selected Field Group, which is
    indicated by an arrow next to the Field Group.
    Ö Carry out the steps above to add the required Data Fields to the respective
    Field Groups
    Ö After transferring Data Fields to Field Groups click on “Generate” button
    h) In the Create Object Directory Entry Screen -
    Ö Click on “Logical Object” button to generate the infoset
    i) In the Change Infoset Screen -
    Ö Click on the “Back” button
    j) User is taken back to the “Infoset: Initial Screen” which displays the
    created Infoset record.
    Step 3: Assigning User Group to Infoset – SQ03
    Follow the menu path – SAP Menu > Tools > ABAP Workbench > Utilities > SAP Query > User Groups
    a) In the User Groups: Initial screen -
    Ö Enter the User Group for which Infoset is to be assigned
    Ö Click on “Assign Users & Infosets” button
    b) In the User Group: Assign Users Screen -
    Ö Click on “Assign Infosets” button
    c) In the next screen, select the Infoset, which needs to be attached to the
    User Group selected
    d) Click on the “Back” button
    Step 4: Creating Query – SQ00 & SQ01
    Follow the menu path – SAP Menu > Tools > ABAP Workbench > Utilities > SAP Query > Queries
    a) In the “Query from User Group: Initial Screen -
    Ö Click on “Other User Groups” button
    Ö In the pop-up screen, User Groups, select the User Group for which the
    Query has to created. The pop-up screen closes.
    Ö Enter the Query Code in the “Query” field
    Ö Click on “Create” button
    b) A pop-up screen “Restrict Value Range” shows the list of Infosets assigned to
    the User Group
    Ö Select the Infoset for which Query has to be created
    c) In the new screen Create Query: Title, Format -
    Ö Enter the Description of the Query in the “Title” field
    Ö Click on the “Next Screen” button
    d) In the Select Field Group” screen
    Ö Select the Field Groups from which Data Fields have to be selected for the
    Output
    Ö Click on the “Next Screen” button
    e) In the “Select Field” screen -
    Ö Select the Data Fields, which should appear in the output
    Ö Click on the “Next Screen” button
    f) In the Screen “Selection” -
    Ö Select the Data Fields for the selection criteria
    Ö Enter the sequence in which the selected fields would appear in the input
    screen of the query.
    Ö Define if the selection criteria should be Single Value or Multiple Value Range
    by clicking in the appropriate check boxes
    Ö Click on the “Basic List’ button
    g) In the screen “Query Layout Design” -
    Ö Select the Output Fields from the Data Fields section by clicking the
    appropriate check box
    Ö Change the sequence of Data Field columns if required
    Ö Click on the “Test” button to test the query created
    h) On the “Test Query” screen click “Continue”
    i) In the “Query” screen -
    Ö Enter the selection criteria
    Ö Click on “Execute” button
    j) Save the Query created
    Step 5: Running the Query – SQ00
    a) In the Query From User Group: Initial screen –
    b) Click on “Other User Groups” button to select the User Group
    c) In the pop-up screen “User Groups” select the User Group
    d) System lists all the queries created for the User Group
    e) Select the appropriate Query
    f) Click on “Execute” button
    g) User is taken to the Selection screen
    h) Enter the selection criteria and click on “Execute” button
    i) System runs the query and gives the output
    Regards,
    Murali.

  • Error: [msnodesql] Invalid passed to function query

    i create a schedule. 
    I try to run this code:
    var todoItemtable = tables.getTable('TodoItem');
    var item = {text:"blahblah"};
    todoItemtable .insert(item, {
    success: function() {
    console.log('Inserted event: ', item);
    or this:
    var sql = "select * from TodoItem";
    mssql.query(sql, {
    success: function(results) {
    console.log('Success: ', results);
    }, error: function(err) {
    console.log('Error: ', err);
    but always get an error: [msnodesql] Invalid passed to function query. Type should be .
    What is the problem? What am I doing wrong?

    Mal,
    I think that need to provide more information about what you are doing when you get this error. This appears to be a LV error.
    1)What version of LV are you using? What are you doing in TestStand when you get this error?
    2)Is your TestStand sequence calling a VI from which this error is generated? If so what is this VI doing?
    3)Can you isolate the source of this error to a particular VI that is using queues?
    4)How often does the error occur?
    5)The path of Queue Core.vi is \vi.lib\Platform\synch.llb\Queue Core.vi. Can you put some probes on the input of this VI to determine what inputs are causing this error? What are all of the inputs to this VI when the error occurs?
    6)Is queue being created or destroyed? Is an element being added or removed from a que
    ue?
    7)Is this your queue or a queue used by one of LV's VIs?
    Unless someone has had this exact error, then it is going to be difficult to debug without more information. Clearly, the problem is easiest to solve if it is reproducible by others.

  • Self-join query to Analytical function query

    Hi All,
    I have converted a self-join query to Analytical function query due to the performance reasons.
    Query which is using Analytical function is giving the correct count as I compared it with query using Self-Join. Can you please tell what is wrong in the query.
    ==========================
    Query using Self-Join
    select count(1)
    From (select t1.*, max(t1.dw_creation_dt) over (partition by t1.empl_id) pers_max_date
    from ohr_pers_curr t1 ) pers
         , (select t2.*, max(t2.dw_creation_dt) over (partition by t2.empl_id, t2.empl_rcd) job_max_date
         from OHR_JOB_CURR t2) job
    where pers.empl_id = job.empl_id
    and pers.dw_creation_dt=pers.pers_max_date
    and job.dw_creation_dt=job.job_max_date
    and job.dummy_row_flag = 'N'
    and pers.dw_creation_rsn_cd in ('N', 'U')
    and job.dw_creation_rsn_cd in ('N', 'U')
    ================================================
    Query Using Analytical function
    select count(1)
    From (select t1.*, max(t1.dw_creation_dt) over (partition by t1.empl_id) pers_max_date
    from ohr_pers_curr t1 ) pers
         , (select t2.*, max(t2.dw_creation_dt) over (partition by t2.empl_id, t2.empl_rcd) job_max_date
         from OHR_JOB_CURR t2) job
    where pers.empl_id = job.empl_id
    and pers.dw_creation_dt=pers.pers_max_date
    and job.dw_creation_dt=job.job_max_date
    and job.dummy_row_flag = 'N'
    and pers.dw_creation_rsn_cd in ('N', 'U')
    and job.dw_creation_rsn_cd in ('N', 'U')
    ==================================

    Hi David,
    The base is same but the problem is different.
    As far as implementation concern these queries looks same, but when I see there counts, they do not match. I do not have any reason why this happening.
    Regards
    Gaurav

  • Select Into statement in db function - query from granted schema table

    problem with "select into" in db function in 10.2
    There are two schemas. 'mdbdev' is the master database and 'devusr' is granted SELECT table access to execute queries in mdbdev schema.
    with devusr, in SQL, I'm able to execute the following query
    select wm_concat(strConcatedCountryList)
    from (select country_name as strConcatedCountryList from mdbdev.country_master mdbcm
    where mdbcm.country_ship_status = <param?>
    order by country_name)
    but when I use the same query in function/procedure with "select into", the compilation failed with error *"table or view does not exist"*
    FUNCTION GETCOUNTRYLISTTOSHIP (SHIP_STATUS IN NUMBER)
    RETURN VARCHAR2
    IS
    var2CountryList VARCHAR2(1000);
    BEGIN
    select wm_concat(strConcatedCountryList) INTO var2CountryList
    from (select country_name as strConcatedCountryList from mdbdev.country_master mdbcm
    where mdbcm.country_ship_status = <value of SHIP_STATUS>
    order by country_name);
    return var2CountryList;
    END;
    Please advise/help/hint :)

    David, Justine, Thank you. The facts from this forum post helped a lot to get the solution.
    The query helped a lot (select * from all_tab_privs_recd where owner = 'MDBDEV' and table_name = 'COUNTRY_MASTER").
    there was a grant using ???(donno wht DBA said) and no direct SELECT grant on that country_master to "devusr". grant command executed. Now, it works :)

  • Position  function query in XSLT

    I have a query regarding XSLT mapping
    I have two E1EDK03 segments for the same qualifier. But I want the values based on posiotion
    Example:
    <E1EDK03 SEGMENT="1">
             <IDDAT>012</IDDAT>
             <DATUM>20110720</DATUM>
          </E1EDK03>
         <E1EDK03 SEGMENT="1">
             <IDDAT>012</IDDAT>
             <DATUM>20110905</DATUM>
          </E1EDK03>
    If position = 1, I need the 1st set of E1EDK03
    <E1EDK03 SEGMENT="1">
             <IDDAT>012</IDDAT>
             <DATUM>20110720</DATUM>
          </E1EDK03>
    If position = 2, I need the 2nd set of E1EDK03
    <E1EDK03 SEGMENT="1">
             <IDDAT>012</IDDAT>
             <DATUM>20110905</DATUM>
          </E1EDK03>
    How to achieve that using XSLT
    Thanks

    Hi,
    Since we have E1EDK03 with same qualifier 012, I don't have any other identifier to distinguish them, because at one instance I need 1st occurrence of E1EKD03 structure and another instance I need the 2nd occurrence of E1EDK03.
    If you observe, only DATUM will have different values. I was trying to do that using position function
    I have defined a variable to copy the segments and later trying to get the each segment based on position
    <!--copying all the E1EDK03 qualifier 012 segments -->
            <xsl:variable name="e1edk03_qual_012">
                   <xsl:for-each select="//IDOC/*">
                        <xsl:if test="starts-with(name(), 'E1EDK03') and IDDAT = '012'">
                             <xsl:copy-of select="."></xsl:copy-of>
                        </xsl:if>
                   </xsl:for-each>
            </xsl:variable>          
    Now the above code has
    <E1EDK03 SEGMENT="1">
             <IDDAT>012</IDDAT>
             <DATUM>20110720</DATUM>
          </E1EDK03>
         <E1EDK03 SEGMENT="1">
             <IDDAT>012</IDDAT>
             <DATUM>20110905</DATUM>
          </E1EDK03>
    I want to split these into two E1EDK03 segments and use further in the XSLT mapping and populate in the target
    Thanks

  • Pl/sql function querying 2 tables based on bind variable

    hey guys, I'm pretty new to pl/sql, but basically I just want to use a select statement based on a searchfield that pulls from 1 of 2 tables based on a bind variable. Here's what I've got so far, but I'm gettting an error message:
    declare
    q1 varchar2(32767); -- query
    q2 varchar2(32767); -- query
    begin
    q1 := 'select distinct(CBP_CONTENT_CATEGORY) CATEGORY, ' ||
    ' CBP_FIELDNAME FIELDNAME, ' ||
    ' CBP_CONTENT_DESC DESCRIPTION ' ||
    ' from CBP_METADATA_2005 ' ||
    ' WHERE UPPER(CBP_CONTENT_CATEGORY) LIKE '%' || UPPER(:CBP_SEARCHFIELD) || '%'
    ' or UPPER(CBP_CONTENT_DESC) LIKE '%' || UPPER(:CBP_SEARCHFIELD) || '%';
    q2 := 'select distinct(CBP_CONTENT_CATEGORY) CATEGORY, ' ||
    ' CBP_FIELDNAME FIELDNAME, ' ||
    ' CBP_CONTENT_DESC DESCRIPTION ' ||
    ' from CBP_METADATA_2004 ' ||
    ' WHERE UPPER(CBP_CONTENT_CATEGORY) LIKE '%' || UPPER(:CBP_SEARCHFIELD) || '%'
    ' or UPPER(CBP_CONTENT_DESC) LIKE '%' || UPPER(:CBP_SEARCHFIELD) || '%';
    if :CBP_YEAR = '1' THEN
    q1=q1
    RETURN q1
    ELSIF :CBP_YEAR = '0' THEN
    q2=q2
    end if;
    RETURN q1;
    end;
    and here's the error:
    failed to parse SQL query:
    ORA-06550: line 1, column 8:
    PLS-00103: Encountered the symbol "" when expecting one of the following:
    begin function package pragma procedure subtype type use
    form
    current cursor
    The symbol "" was ignored.
    ORA-06550: line 4, column 6:
    PLS-00103: Encountered the symbol "" when expecting one of the following:
    begin case declare exit for goto if loop mod null pragma
    raise return select update while with

    LDub,
    Your function is full of errors. First of all you didn't escape quotes and second, you didn't use the concatination operator properly. Beside that, there was a bit too much of code there. Here is the modified code that will work for you:
    DECLARE
    q1 VARCHAR2 (32767); -- query
    q2 VARCHAR2 (32767); -- query
    BEGIN
    q1 :=
    'select distinct(CBP_CONTENT_CATEGORY) CATEGORY, '
    || ' CBP_FIELDNAME FIELDNAME, '
    || ' CBP_CONTENT_DESC DESCRIPTION '
    || ' from CBP_METADATA_2005 '
    || ' WHERE UPPER(CBP_CONTENT_CATEGORY) LIKE ''%'' || UPPER(:CBP_SEARCHFIELD) || ''%'''
    || ' or UPPER(CBP_CONTENT_DESC) LIKE ''%'' || UPPER(:CBP_SEARCHFIELD) || ''%''';
    q2 :=
    'select distinct(CBP_CONTENT_CATEGORY) CATEGORY, '
    || ' CBP_FIELDNAME FIELDNAME, '
    || ' CBP_CONTENT_DESC DESCRIPTION '
    || ' from CBP_METADATA_2004 '
    || ' WHERE UPPER(CBP_CONTENT_CATEGORY) LIKE ''%''|| UPPER(:CBP_SEARCHFIELD) || ''%'''
    || ' or UPPER(CBP_CONTENT_DESC) LIKE ''%'' || UPPER(:CBP_SEARCHFIELD) || ''%''';
    IF :cbp_year = '1'
    THEN
    RETURN q1;
    ELSIF :cbp_year = '0'
    THEN
    RETURN q2;
    END IF;
    END;
    Denes Kubicek

  • Datatype issue in function query

    Hi,
    Below is my table
    create table dsource(
    prod varchar2(10),
    source_dt date,
    source_type varchar2(2),
    list_owner_nbr number);
    insert into dsource values('TOH','01-jul-2010','D',9);
    insert into dsource values('TOH','01-jul-2010','D',24);
    insert into dsource values('TOH','01-jul-2010','D',238);
    insert into dsource values('TOH','01-jul-2010','D',253);
    insert into dsource values('TOH','01-jul-2010','D',521);
    insert into dsource values('TOH','01-jul-2010','D',617);
    insert into dsource values('TOH','01-jul-2010','D',680);
    commit;
    I created one function
    create or replace function mark_camp (v_prod_abbr varchar2,source_dt varchar2,source_type varchar2,v_list_owner_nbr varchar2) return varchar2 as
    begin
    select *
    from dsource
    where prod_abbr=v_prod_abbr
    and to_char(source_start_dt,'MONYY')=source_dt and mke_mag_source_type_cd=source_type
    and list_owner_nbr in(v_list_owner_nbr) ;
    return(v_prod_abbr||','||source_dt||','||source_type||','||v_list_owner_nbr);
    end mark_camp;
    Now I am running one query
    select mark_camp('TOH','JUL2010','D','9, 24, 238, 253, 521, 617, 680') from dual;
    I am getting 0 rows returned
    if I execute
    select mark_camp('TOH','JUL2010','D',9, 24, 238, 253, 521, 617, 680) from dual;
    then error occurs ORA-06553: PLS-306: wrong number or types of arguments in call to 'MARK_CAMP'
    Here list_owner_nbr datatype is number in table and I am passing multiple values in function so I used varchar2 in function
    but this query is not working. can anybody please help because user will enter multiple values in list_owner_nbr.

    799301 wrote:
    Now I am running one query
    select mark_camp('TOH','JUL2010','D','9, 24, 238, 253, 521, 617, 680') from dual;
    I am getting 0 rows returnedThe reason why your first call to function succeed is that anything between single quotes in considered as a single string. so '9, 24, 238, 253, 521, 617, 680' is considered as a single varchar2 value. Your function expectes 4 varchar2 values and the same are being provided.
    if I execute
    select mark_camp('TOH','JUL2010','D',9, 24, 238, 253, 521, 617, 680) from dual;
    then error occurs ORA-06553: PLS-306: wrong number or types of arguments in call to 'MARK_CAMP'In second call you are passing 3 varchar2 and 7 numbers (9,24,238,...are being considered as individual paramerter) and hence the error.
    Coming to your actual problem :
    Here list_owner_nbr datatype is number in table and I am passing multiple values in function so I used varchar2 in function
    but this query is not working. can anybody please help because user will enter multiple values in list_owner_nbr.This is called varying in list and the forum FAQ page has a listing for it :
    {message:id=9360009}

  • [Function] -Query in result

    Hi,
    I write the below function to display the bonus of employees
    create or replace function Bonus_val (description in varchar2) return number
    is
    v_bonus number;
    cursor j1 is
    select description,salary from employee_290512;
    begin
    for v1 in j1 loop
    if v1.description='Tester' then
    v_bonus := v1.salary*15;
    elsif v1.description='Manager' then
    v_bonus := v1.salary*30;
    elsif v1.description='Programmer' then
    v_bonus := v1.salary*45;
    return v_bonus;
    end if;
    end loop;
    end;
    whose having a salary range like below
    6544.78
    1234.56
    6661.78
    2344.78
    2334.78
    4322.78
    7897.78
    1232.78
    But while testing the above function it's showing the same values for all category, i"m confused could any one clarify on this please.
    Regards
    Thelak

    I'm not entirely sure what you are trying to accomplish here, but the logic is definitely flawed.
    The function as written will attempt to read all of the rows from the employee_29051 table. since there is no predicate in the query, it will very likely do it through a full table scan. When the first row of the table is read from the cursor, it will assign a value to v_bonus based on the description field in the first row, and return that to the caller. given a full table scan every time, it is extremely likely that it will do that based on the same row everytime.
    Further, the passed parameter description, is never used. It is also a really bad idea to give parmeters the same name as the columns in your tables.
    If you post some sample data form the table, and the expected output from the function call based on that data, perhaps someone could sort you out.
    John

  • Soundex function query.....???

    Hi guys,
    Hope you all f9, I have a query regarding Soundex function in ORACLE 9i EE.
    I have a table STUDENTRESULT in which a column COURSENAME, and there are two records in that table.
    DATA:
    rec#1: BUSINESS MATHEMATICS
    rec#2: BUSINESS COMMUNICATION
    when i run this query :
    select coursename, soundex(coursename) from studentresult;
    Query result is :
    BUSINESS MATHEMATICS     B252
    BUSINESS COMMUNICATION     B252
    I know that Soudex function matches first 5 characters in the string but my questions is , Can we segregate the result in a manner that it gives diff value word by word in the whole string?
    regards
    qamar

    http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:1400328669393
    and search for "use Levenshtein distance formula" on this link; may be helpful to you.

  • Goto functionality (query to query)

    Hello,
    I created two queries. With transaction "rsbbs" I refer one query as sender-query and the other as receiver-query. If I execute sender-query, for most of characteristics the functionality "Goto" works fine. That means data will display in receiver-query. But there are some characteristics for which no applicable data will found in receiver-query, though they have data. If I execute receiver-query allone with same restrictions, data will found for these characteristics.
    What could be the problem? Is it possible to see which restrictions will really used in the background by using functionalíty "Goto" (e.g. debugging)?
    Many thanks in advance!
    Anne

    Hi,
    in the query tab select the receiver then click to 'Assignement details'.
    You should have to customize correspondance field.
    hope it help's

  • Analytical function Query

    Hi,
    I have below query with mentioned table and data setup. I always want the specific value (in this case 'CAR' or 'BIKE') record as result of this query and if i pass 'ALL' i need that record.
    So I use decode function and convert the 'ALL' value to NULL and made it to go last. so on the top always the specific value records will come and from the outer query i can get the 1st record alone.
    But the problem is when i run the inner query it works fine but along with outer query I am getting 'ALL' record as the result.
    My question is : is the ROW_NUMBER() fuction alias doesn't have scope outside of the inner query.
    Note : if i use rownum = 1 instead of rrn=1 it works fine.
    Is there anyother alternate solution or any bug in this query.
    Table1
    col1 col2
    A CAR
    A BIKE
    B ALL
    Query:
    SELECT indicator
    FROM (SELECT indicator, ROW_NUMBER() OVER( ORDER BY DECODE(col2, 'ALL', NULL) asc NULLS LAST) rrn
    FROM table1
    WHERE (col2 = <Input specific value>
    OR col2 = 'ALL')
    WHERE rrn = 1;
    Thanks in advance.

    you did not excatly what you ment to do:
    Naga wrote:
    So I use decode function and convert the 'ALL' value to NULL and made it to go last.You only specified the decode for 'ALL', but said nothiung about the other values. So just add a default.
    with table1 as (
    select 'A' col1, 'CAR' col2 from dual union all
    select 'A', 'BIKE' from dual union all
    select 'B', 'ALL' from dual )
    SELECT col1
    FROM (
    SELECT col1, ROW_NUMBER() OVER( ORDER BY DECODE(col2, 'ALL', NULL, 1) asc NULLS LAST) rrn
    FROM table1
    WHERE (col2 = 'CAR'
    OR col2 = 'ALL')
    WHERE rrn = 1
    COL1
    A    The "scope" of the row_number() is stable, so you can refer to it from the outer query.
    regards chris

  • Tricky count function query

    Hi All.
    I was trying to write a query for below result set but can not figure out if i can achieve below result set through T-SQL.
    Emplid FunctionId Count
    1 2
    1 3 1
    1 4 2
    1 4
    1 5 3
    1 6 4
    1 3
    2 3
    2 3
    2 1 1
    2 2 2
    Description
    When an Employee is changing from job/function, am struggling to get incremental number / count for that employ based on no. of funtionid changed.
    I need a count only when an employee is going to do something else (another function).
    The example above is showing how the count output should be.
    am not sure it i need to use any analytical function, any help would be appreciated.
    and many thanks in advance for reading my question

    Something like
    SQL> ed
    Wrote file afiedt.buf
      1  with x as (
      2    select 1 empid, 2 functionid, sysdate dt from dual union all
      3    select 1, 3, sysdate+1 from dual union all
      4    select 1, 4, sysdate+2 from dual union all
      5    select 1, 4, sysdate+3 from dual union all
      6    select 2, 3, sysdate+4 from dual union all
      7    select 2, 3, sysdate+5 from dual union all
      8    select 2, 1, sysdate+6 from dual
      9  )
    10  select empid,
    11         functionid,
    12         sum(case when functionid = prior_functionid
    13                  then 0
    14                  else 1
    15               end) over (partition by empid
    16                              order by dt)-1 cnt
    17    from (
    18  select empid,
    19         functionid,
    20         lag(functionid) over (partition by empid
    21                                   order by dt) prior_functionid,
    22         dt
    23    from x
    24* )
    SQL> /
         EMPID FUNCTIONID        CNT
             1          2          0
             1          3          1
             1          4          2
             1          4          2
             2          3          0
             2          3          0
             2          1          1
    7 rows selected.appears to work
    Justin

  • SQL Server Multiple JOINS with Table Value Function - query never ends

    I have a query with 4 joins using a table value function to get the data and when I execute it the query never ends.
    Issue Details 
    - Table value function 
        CREATE FUNCTION [dbo].[GetIndicator] 
          @indicator varchar(50),
          @refDate datetime
    RETURNS 
    TABLE
    AS
    RETURN
    SELECT
    T1.Id ,T1.ColINT_1, T1.ColNVARCHAR_1 collate DATABASE_DEFAULT as ColNVARCHAR_1 ,T1.ColNVARCHAR_2 ,T1.ColSMALLDATETIME_1, T1.ColDECIMAL_1, T1.ColDECIMAL_1
    FROM TABLE2 T2
    JOIN TABLE3 T3
    ON T2.COLFKT3 = T3.Id
    AND T3.ReferenceDate = @RefDate
    AND T3.State != 'Deleted'
    JOIN TABLE4 T4
    ON T2.COLFKT4 = T4.Id AND T4.Name=@indicator
    JOIN TABLE1 T1
    ON T2.COLFKT1=T1.Id
    - Query
        DECLARE @RefDate datetime
    SET @RefDate = '30 April 2014 23:59:59'
    SELECT DISTINCT OTHERTABLE.Id As Id
    FROM 
    GetIndicator('ID#1_0#INDICATOR_X',@RefDate) AS OTHERTABLE
    JOIN GetIndicator('ID#1_0#INDICATOR_Y',@RefDate) AS YTABLE  
    ON OTHERTABLE.SomeId=YTABLE.SomeId
    AND OTHERTABLE.DateOfEntry=YTABLE.DateOfEntry
    JOIN GetIndicator('ID#1_0#INDICATOR_Z',@RefDate) AS ZTABLE
    ON OTHERTABLE.SomeId=ZTABLE.SomeId
    AND OTHERTABLE.DateOfEntry=ZTABLE.DateOfEntry
    JOIN GetIndicator('ID#1_0#INDICATOR_W',@RefDate) AS WTABLE 
    ON OTHERTABLE.SomeId=WTABLE.SomeId
    AND OTHERTABLE.DateOfEntry=WTABLE.DateOfEntry
    JOIN GetIndicator('ID#1_0#INDICATOR_A',@RefDate) AS ATABLE  
    ON OTHERTABLE.SomeId=ATABLE.SomeId
    AND OTHERTABLE.DateOfEntry=ATABLE.DateOfEntry
    Other details:
    - SQL server version: 2008 R2
    - If I execute the table function code outside the query, with the same args, the execution time is less the 1s.
    - Each table function call return between 250 and 500 rows.

    Hi,
    Calling function in general is a costly query. And definitely joining with a function 5 times in not an efficient one.
    1. You can populate the results for all parameters in a CTE or table variable or temporary table and join (instead of funtion) for different parameters
    2. Looks like you want fetch the IDs falling to different indicators for the same @Refdate. You can try something like this
    WITH CTE
    AS
    SELECT
    T1.Id ,T1.ColINT_1, T1.ColNVARCHAR_1 collate DATABASE_DEFAULT as ColNVARCHAR_1 ,T1.ColNVARCHAR_2 ,T1.ColSMALLDATETIME_1, T1.ColDECIMAL_1, T1.ColDECIMAL_1, T4.Name
    FROM TABLE2 T2
    JOIN TABLE3 T3
    ON T2.COLFKT3 = T3.Id
    AND T3.ReferenceDate = @RefDate
    AND T3.State != 'Deleted'
    JOIN TABLE4 T4
    ON T2.COLFKT4 = T4.Id AND T4.Name=@indicator
    JOIN TABLE1 T1
    ON T2.COLFKT1=T1.Id
    SELECT * FROM CTE WHERE Name = 'ID#1_0#INDICATOR_X' AND Name = 'ID#1_0#INDICATOR_Y' AND Name = 'ID#1_0#INDICATOR_Z' AND Name = 'ID#1_0#INDICATOR_W' AND Name = 'ID#1_0#INDICATOR_A' AND ReferenceDate = @RefDate.
    Or you can even simplify more depends on your requirement.
    Regards,
    Brindha.

  • Please help about function query permformance

    Hi
    I have a j2ee web application with oracle database.
    I finish the function implementation by put all caculaton inside oracle query ( funciton (todayData - avg(historical data )) / std(historical data) and using group by and sub query .but performance is very slow about 3 minute whick is far from client's 10 second requirement.
    My question is if I take raw data from database and do the caculation part in Java will it be faster. Is there some other way to speed up the process?(historical data is big)
    Thanks for your time and help

    What does the function look like? How is it called? What is the query and explain plan? Are statistics up to date?
    My question is if I take raw data from database and do the caculation
    part in Java will it be faster.No.
    Is there some other way to speed up the process?(historical data is big)You should start by posting the explain plan and looking into the other questions above.

  • AppleTV functionality query

    Hi,
    it is said that AppleTV streams ONLY content purchased via either AppleTV or iTunes. Given this exclusivity, I cannot use AppleTV for streaming unrelated movies and music from my iMac to the HDTV even if it is contained in the iTunes library.  Is this correct? 
    As I understand the matter, I would have to use AirPlay to stream Apple-unrelated content to the HDTV.  If this is the case, it's probably worth waiting till November when a new model of AppleTV is supposed to feature integrated AirPlay functionality.  Am I getting all this right?  Feedback on these issues is greatly appreciated. Thank you!
    Frank 

    Welcome to the Apple Community.
    In addition to content from the iTunes store you can also view content from netflix (subject to it's availability in your location) directly from the Internet to the Apple TV. You also have access to YouTube.
    Aside from content you can obtain from the Internet, anything that is in iTunes and in a compatible format (720p h264 etc) can be streamed to the Apple TV, this not only includes purchases made from the iTunes store to your computer but your own movies as well as podcasts.
    The current Apple TV software and iPod/iPad/iPhone software already supports AirPlay, which allows content in iTunes on these devices as well as content in many apps and websites to be streamed to the Apple TV.
    There is a new iOS being released later this year, but you won't need a new Apple TV and indeed there is no mention of a new Apple TV at that time, although nothing can be guaranteed in that respect.

Maybe you are looking for

  • Trying to install nic drivers for solaris 10 on x86 machine

    i am trying to install nic drives for sis 900 downlaoded from http://homepage2.nifty.com/mrym3/taiyodo/eng/ i am following the instruction in the readme file but when i reach (5) Make links to correct binary directory and Makefile according to your c

  • Problem in new environment and in old environment.

    Hi gurus I have a problem in data loading we have two environments old and new The data flow in new environment is differ from old The data flow is like this In BW side i have ODS first and from  ODS the data is going to two Cubes But in these  two C

  • How to add a field in data entry section of cat2 transaction

    hi friends, i just want to know how i can add one more field in the data entry section of the cat2 transaction.would appreciate if u help me asap. thanks, sakshi

  • Database not connecting LV2014

    Hi All, Sorry I am new to databases but I've spent the day trying to get LabVIEW 2014 to connect to a Microsoft Access 2013 Database. I've tried a .mdb and .accdb but neither work. I tried to make a udl but it was 64 bit and wouldnt load, I tried the

  • X200 using iPhone personal hotspot failure

    I've got a friend with an X200. He is trying to use his iPhone 4s as a  personal hotspot. The phone is set up correctly because we can connect to it using my laptop (not an X200). My laptop connects using WPA2/AES. When we try connecting using Access