Manipuilate joins dynamically.

Hi All,
I would need an help on the query.
I have a table x and column a, b,c, y and z in them.I am joining this table with another table c
IF the column y is not NULL and if z='M' THEN I have to join table c with d
IF the column y is not NULL and if z='N' THEN I have to join table c with e
IF the column y is not NULL and if z='O' THEN I have to join table c with f
Can anubody help me in how to build this join in SQL level???
Thanks in advance.

Generally speaking if you can use UNION(ALL)s for a table(or a view), it is easy to rewrite it with WHERE ... OR ... OR ...
For example:
SELECT select-list
  FROM Table_x
WHERE some_predicates
UNION
SELECT select-list
  FROM Table_x
WHERE aother_predicates
UNION
SELECT select-list
  FROM Table_x
WHERE somemore_predicates
;It would be able to rewrite to:
SELECT select-list
  FROM Table_x
WHERE some_predicates
    OR aother_predicates
    OR somemore_predicates
;Returning to your original problem, my question is that with what column in table x be joined a column(d,e or f) of table c?
Although I assumed temporarily to join table c with column y in table x,
it is easy to change joined column in table x.
I don't know the performance of this, but I thought that it would work:
SELECT *.x, *.c
  FROM table_x x
       LEFT OUTER JOIN
/*  or INNER JOIN      */
       table_c c
         ON  y IS NOT NULL
         AND
           ( z = 'M' AND c.d = x.y
             OR
             z = 'N' AND c.e = x.y
             OR
             z = 'O' AND c.f = x.y
;

Similar Messages

  • How to make a outer join dynamically

    I need to make a a dynamic join based on column values ie I want to do the following for ex. IF a.column1='A' and a.column2='B' then my where clause should be a.job_num=b.job_num(+) and a.po_num=b.po_num(+)
    ELSE my join caluse should be
    a.po_num=b.po_num(+).
    Has anyone ideas?.
    I do not want to check conditions and concatenate the string to make the appropriate sql

    It doesn't necessarily have to be dynamic SQL.
    begin
      select column1, column2 into var1, var2 from table1 ;
      if var1 = 'A' and var2 = 'B'
      then
        select more_columns into var_columns
        from table2 a, table 3 b
        where a.job_num=b.job_num(+) and a.po_num=b.po_num(+) ;
      else
        select more_columns into var_columns
        from table2 a, table 3 b
        where a.po_num = b.po_num(+). ;
    end ;

  • Dynamic Inner Join in 4.6c

    Requirement is dynamic specification of  Table name in inner join. The table names to be used in join would be derived in a variable using select statement. These names to be supplied to join dynamically. The other join conditions and where conditions will remain same.
    For example :
    On the basis of 1st select statement tables names are fetched in 2 variables tab1 & tab2.
    Now want to use these two variables in inner join statement.
    Searched and as per few example tried to do in following manner but its not working
    data: tab1(10) type c value 'MARA',
            tab2(10) type c value 'MAKT'.
    data: dbtab1(10) type c,
             dbtab2(10) type c .
    dbtab1 = tab1. 
    dbtab2 = tab2. 
    DATA: BEGIN OF itab occurs 0,
               matnr TYPE mara-matnr,
               maktx type makt-maktx,
    END OF itab.
    DATA: column_syntax TYPE string,
                dbtab_syntax TYPE string.
    PARAMETERS: p_matnr TYPE mara-matnr.
    dbtab_syntax = '( (dbtab1) AS t1 '
    &' INNER JOIN (dbtab2) AS t4 ON t1~MATNR = t4~MATNR )'.
    SELECT  matnr maktx
    FROM (dbtab_syntax)
    INTO TABLE itab  WHERE t4~matnr   = p_matnr.
    Got the following error:
    "A table name, specified in an SQL command, is unknown"
    It seems not able to identify table name dynamiccaly in dbtab_syntax.
    thanks
    anya
    Edited by: Thomas Zloch on Nov 29, 2010 10:18 AM - please use code tags

    Hi Anya,
    Following code will be work
    CONCATENATE dbtab1 ' as t1 INNER JOIN ' dbtab2 ' as t4 ON t1MATNR = t4MATNR ' INTO dbtab_syntax RESPECTING BLANKS.
    TRANSLATE dbtab_syntax TO UPPER CASE.
    SELECT  t1~matnr maktx
    FROM (dbtab_syntax)
    INTO TABLE itab  WHERE t4~matnr   = p_matnr.
    Note the following point
    1) Don't used un-necessary bracket inside the SQL.
    2) Specify alias name or table name when fields exit in both table while projection.
        i.e. SELECT  matnr maktx will be now SELECT  t1~matnr maktx

  • Approach to searching

    Hi Everyone
    We're building a web site here that implement both basic and advanced searching functionality. Basic searching is essentially searching on various attributes of on table and advanced searching is across many tables (even possibly 20-30 tables).
    We're using ODP.NET to access the Oracle database and I'm required to come up with a strategy to implement this search functionality.
    My first question is Stored Procs vs. Inline SQL? Which to use? I'd like to use procs but given the potential for a huge number of search parameters, I just don't know whether store procs can take that many input params? Inline SQL would be ok since we could build some SQLBuilder code to assemble the various components of the statement (to avoid SQL injection, errors etc) but I'm not sure if this is best practice of if the performance on this is just gonna kill the app.
    The other alternative i was thinking was making views of common search joins (say employee with department or something) so that these kind of joins are already done for the user so that can improve performance.. is this also common practice?
    We don't have the resources to build another searching database with denormalised views of the entire database but any input into things that I should/shouldn't do would be greatly appreciated.
    cheers

    Hmmm. So basically what you are doing is re-writing the functionality of something like Business Objects or Oracle Discoverer. Have you got a business case to prove that you can write something cheaper than the cost of licencing one of those products?
    Next on the list: performance. Dynamically assembling oodles of queries is likely to knacker your system because:
    (1) dynamic queries take resource to assemble;
    (2) your users don't know SQL or how the database is assembled and consequently will "write" bad queries.
    I think it's significant that tools like BO and OD now insist on us building a meta-model or universe. They don't let us inflict the raw database structure on the users, and vice versa.
    Almost every project I've ever worked on has had as a requirement "we must be able to write our own reports". How many users actually avail themselves of this facility? Almost none. And those that do usually have one or two bespoke reports that they run once a month. In short, it would be much cheaper to seek out those troublemakers and put their darlings on the developers' To Do list.
    But, if you must, and of course, we all know what users are like...
    Start with the Basic Search. Don't build it in the middle tier, put it in the database. Use parameterised functions to return REF CURSORs; the limit on parameters is well over 1000 and you don't want to handle more than that! Make sure your generated code uses bind variables.
    Once you've got that working correctly, move on to More Advanced Search. Don't allow the users to search any combination of tables they fancy. Present them with choices, which map to more parameterised functions returning REF CURSORs. Use views or build the joins dynamically, as you wish. Add a button to your application that says, "Is there a report missing from this list? Tell us what you want to see!"
    This may not be what you wanted to hear, nor what your users think it is they want, but it is a proven, reliable approach.
    "The enemy," retorted Yossarian with weighted precision, "is anybody who's going to get you killed, no matter which side he's on." Joseph Heller, Catch-22
    Good luck, APC

  • Dynamic SQL Joining between tables and Primary keys being configured within master tables

    Team , Thanks for your help in advance !
    I'm looking out to code a dynamic SQL which should refer Master tables for table names and Primary keys and then Join for insertion into target tables .
    EG:
    INSERT INTO HUB.dbo.lp_order
    SELECT *
    FROM del.dbo.lp_order t1
    where not exists ( select *
    from hub.dbo.lp_order tw
    where t1.order_id = t2.order_id )
    SET @rows = @@ROWCOUNT
    PRINT 'Table: lp_order; Inserted Records: '+ Cast(@rows AS VARCHAR)
    -- Please note Databse names are going to remain the same but table names and join conditions on keys
    -- should vary for each table(s) being configured in master tables
    Sample of Master configuration tables with table info and PK Info :
    Table Info         
    Table_info_ID    Table_Name    
    1        lp_order    
    7        lp__transition_record    
    Table_PK_Info        
    Table_PK_Info_ID    Table_info_ID    PK_Column_Name
    2                1    order_id
    8                7    transition_record_id
    There can be more than one join condition for each table
    Thanks you !
    Rajkumar Yelugu

    Hi Rajkumar,
    It is glad to hear that you figured the question out by yourself.
    There's a flaw with your while loop in your sample code, just in case you hadn't noticed that, please see below.
    --In this case, it goes to infinite loop
    DECLARE @T TABLE(ID INT)
    INSERT INTO @T VALUES(1),(3),(2)
    DECLARE @ID INT
    SELECT @ID = MIN(ID) FROM @T
    WHILE @ID IS NOT NULL
    PRINT @ID
    SELECT @ID =ID FROM @T WHERE ID > @ID
    So a cursor would be the appropriate option in your case, please reference below.
    DECLARE @Table_Info TABLE
    Table_info_ID INT,
    Table_Name VARCHAR(99)
    INSERT INTO @Table_Info VALUES(1,'lp_order'),(7,'lp__transition_record');
    DECLARE @Table_PK_Info TABLE
    Table_PK_Info_ID INT,
    Table_info_ID INT,
    PK_Column_Name VARCHAR(99)
    INSERT INTO @Table_PK_Info VALUES(2,1,'order_id'),(8,7,'transition_record_id'),(3,1,'order_id2')
    DECLARE @SQL NVarchar(MAX),
    @ID INT,
    @Table_Name VARCHAR(20),
    @whereCondition VARCHAR(99)
    DECLARE cur_Tabel_Info CURSOR
    FOR SELECT Table_info_ID,Table_Name FROM @Table_Info
    OPEN cur_Tabel_Info
    FETCH NEXT FROM cur_Tabel_Info
    INTO @ID, @Table_Name
    WHILE @@FETCH_STATUS = 0
    BEGIN
    SELECT @whereCondition =ISNULL(@whereCondition+' AND ','') +'t1.'+PK_Column_Name+'='+'t2.'+PK_Column_Name FROM @Table_PK_Info WHERE Table_info_ID=@ID
    SET @SQL = 'INSERT INTO hub.dbo.'+@Table_Name+'
    SELECT * FROM del.dbo.'+@Table_Name+' AS T1
    WHERE NOT EXISTS (
    SELECT *
    FROM hub.dbo.'+@Table_Name+' AS T2
    WHERE '+@whereCondition+')'
    SELECT @SQL
    --EXEC(@SQL)
    SET @whereCondition = NULL
    FETCH NEXT FROM cur_Tabel_Info
    INTO @ID, @Table_Name
    END
    Supposing you had noticed and fixed the flaw, your answer sharing is always welcome.
    If you have any question, feel free to let me know.
    Eric Zhang
    TechNet Community Support

  • What is a dynamic join in SAP HANA?

    What is a dynamic join in SAP HANA and how it works? Please explain me with the example , how to use it?
    Message was edited by: Tom Flanagan

    Hi Sree,
    In very simple and basic terms:
    If you have table A and B with columns C1, C2, and C3 used in multi-column join (with Dynamic join set to true) from both the tables, then depending upon which columns you select in the query, ONLY those columns will be used in the join.
    For ex. if you select C1, C2 in the select statement, then the join will happen only on C1 and C2, C3 will not be used in the join criteria, even if the join definition involves all the 3 columns.
    Regards,
    Ravi

  • Dynamic From statement in select query and/or outer join not working

    Dear Experts, I have a select query where the select columns are dynamic, the where condition is also dynamic. It is of the below format:
    Select (dynamic columns) INTO <wa>
    FROM a inner join b on af1 = bf1
    inner join c on af2 = cf2......
    WHERE (dynamic conditios)
    ORDER BY ( dynamic sort condition).
    Now I have to include some tables (dynamically depending on the user input) in the inner join statement which will give description for the selected fields. And these database tables may or may no be empty. So in this case, my select query will not return any data if these tables are empty. And I dont want that.
    I tried using outer join for the extra tables but it gave me a runtime error. I also tried forming the inner join statement dynamically but it was not supporting.
    Kindly give me pointers.
    Thanks

    Hey thanks for the reply, but the problem is not solved.
    I am already using  ( fileds, value) like table in my where condition and the select statement was working properly.
    the problem is that now I have to include some tables in the join statement which can be empty and so i want to use Outer join.
    But I am getting a runtime error as below:
    Error analysis
        An exception occurred that is explained in detail below.
        The exception, which is assigned to class 'CX_SY_DYNAMIC_OSQL_SYNTAX', was not
         caught in
        procedure "ZATSCSNG_RFC_READ_TABLE" "(FUNCTION)", nor was it propagated by a
         RAISING clause.
        Since the caller of the procedure could not have anticipated that the
        exception would occur, the current program is terminated.
        The reason for the exception is:
        The running ABAP program wanted to execute a SELECT statement whose
        WHERE condition was (partly) specified dynamically. The part that is
        specified in an internal table at runtime is compared to a field of the
        right table of an LEFT OUTER JOIN. Such comparisons are not supported by
         all database systems and are therefore not allowed.

  • How to construct Dynamic Join in ABAP?

    Hello ALL,
    I am typically faced with a situvation where in I need to write a dynamic JOIN SQL statement in ABAP.
    For example :
    REPORT ZTEST .
    PARAMETERS: TBLNAME(50) DEFAULT 'SPFLI'.
    DATA: TOTAL_ROWS TYPE P.
    SELECT COUNT(*) FROM (TBLNAME) INTO TOTAL_ROWS.
    WRITE: / TBLNAME, TOTAL_ROWS.
    In the above example, here the fetch from Table is dynamic.
    Where as if i have to conisder the following SQL statement which is a normal JOIN statement in ABAP,
    select
      mara~matnr
      marc~werks
      from mara
      join marc on maramatnr = marcmatnr
      into table it_join
      where mara~mtart = 'FERT' and
            marc~werks = '3000'.
    How do i convert this into DYNAMIC JOIN STATEMENT</b> .
    Looking forward to your responses.
    Thank you

    Hi,
    This is from the ABAP keyword help in 6.40, not sure if it works in previous releases or not.
    Example
    Dynamic specification of the inner joins. The column specification after SELECT is also dynamic.
    PARAMETERS: p_cityfr TYPE spfli-cityfrom,
                p_cityto TYPE spfli-cityto.
    DATA: BEGIN OF wa,
             fldate TYPE sflight-fldate,
             carrname TYPE scarr-carrname,
             connid   TYPE spfli-connid,
           END OF wa.
    DATA itab LIKE SORTED TABLE OF wa
                   WITH UNIQUE KEY fldate carrname connid.
    DATA: column_syntax TYPE string,
          dbtab_syntax TYPE string.
    column_syntax = `ccarrname pconnid f~fldate`.
    dbtab_syntax = `( ( scarr AS c `
      & ` INNER JOIN spfli AS p ON pcarrid  = ccarrid`
      & ` AND p~cityfrom = p_cityfr`
      & ` AND p~cityto   = p_cityto )`
      & ` INNER JOIN sflight AS f ON fcarrid = pcarrid `
      & ` AND fconnid = pconnid )`.
    SELECT (column_syntax)
           FROM (dbtab_syntax)
           INTO CORRESPONDING FIELDS OF TABLE itab.
    LOOP AT itab INTO wa.
      WRITE: / wa-fldate, wa-carrname, wa-connid.
    ENDLOOP.
    Regards
    Vilmos

  • DNS record is not dynamically created in DNS Zone, when joining to DNS domain

    hi
    in my test lab i have deployed two virtual machines (both are windows server 2008 R2 enterprise).
    on vm1 i have installed just DNS role (without Active directory) and created a primary non-ADintegrated zone.
    on this DNS zone, i have enabled dynamic update set to
    non-secure & secure .
    now in my vm2 (as a DNS client) , i set the ip address of this DNS server as preferred DNS server and then in system properties, on the primary DNS suffix field, i entered the name of my DNS domain (mydomain.lab)& rebooted VM2, but the a record of this
    client (vm2) is not registered (created ) in mydomain.lab zone.
    i respect the record be created like the situations which we join a client to AD domain 

    Hi  John ,
    When registering DNS record ,client will send a SOA query to find the primary server of the zone .Then send register message to the server .
    We can use nslookup to find the problem :
    Open Command Prompt
    type nslookup
    type set type=soa
    type zone name
        1. If there is positive response ,check the name of
    primary name server and the IP address of the server .
    Its name should be vm1.mydomain.lab .If not ,edit the SOA record in the zone .
    If no IP address ,edit NS record in the zone .
        2. If there is no response ,check the SOA record in the zone .
    We can manually delete and recreate the records to ensure there are right SOA and NS records .
    Here is the guide for using nslookup :
    Nslookup :
    https://technet.microsoft.com/en-us/library/cc940085.aspx
    Best Regards,
    Leo
    Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Support, contact [email protected]
    Hi Leo, thanks for reply.
    i did all steps you mentioned but still no result.
    i put an screenshot of my desktop here , everything is shown here:

  • Dynamic table name in an inner join - select statement

    Hi,
    Please can you let me know if is possible to use a Dynamic table name in an inner join?
    Something like the statement below? (It works in a simple select statement but not in an inner join)
    SELECT  *
         INTO CORRESPONDING FIELDS OF <t_itab>
          FROM <Dynamic table name> INNER JOIN pa0050 ON
          ( <Dynamic table name>pernr =  pa0050pernr )
           WHERE <Dynamic table name>~pernr = it_pernr-l_pernr
           AND pa0050~bdegr = f_bdegr.
    Any help would be apprecited very much.
    Thanks & Regards.

    Hi,
    Check this link.
    [http://help.sap.com/saphelp_nw04/helpdata/en/fc/eb39c4358411d1829f0000e829fbfe/frameset.htm]
    [Re: accessing dynamic internal table's fields??;
    hope it'll help u.
    Regards,
    Sneha.
    Edited by: sneha kumari on Jun 18, 2009 1:57 PM

  • Dynamic Table name in Inner Join in  4.6c

    data: tab1(10) type c value 'MARA',
            tab2(10) type c value 'MAKT'.
    data: dbtab1(10) type c,
             dbtab2(10) type c .
    dbtab1 = tab1. 
    dbtab2 = tab2. 
    DATA: BEGIN OF itab occurs 0,
               matnr TYPE mara-matnr,
               maktx type makt-maktx,
    END OF itab.
    DATA: column_syntax TYPE string,
                dbtab_syntax TYPE string.
    PARAMETERS: p_matnr TYPE mara-matnr.
    dbtab_syntax = '( (dbtab1) AS t1 '
    &' INNER JOIN (dbtab2) AS t4 ON t1MATNR = t4MATNR )'.
    SELECT  matnr maktx
    FROM (dbtab_syntax)
    INTO TABLE itab  WHERE t4~matnr   = p_matnr.
    Got the following error:
    "A table name, specified in an SQL command, is unknown"
    It seems not able to read dynamic table name in dbtab_syntax.
    thanks
    anya
    Moderation Message: Duplicate Post.
    Edited by: kishan P on Nov 29, 2010 11:17 AM

    Hi,
    Check this link.
    [http://help.sap.com/saphelp_nw04/helpdata/en/fc/eb39c4358411d1829f0000e829fbfe/frameset.htm]
    [Re: accessing dynamic internal table's fields??;
    hope it'll help u.
    Regards,
    Sneha.
    Edited by: sneha kumari on Jun 18, 2009 1:57 PM

  • Absolute dynamic select query with dynamic join and where

    Has anyone ever tried creating an absolutely dynamic SELECT query with dynamic Join and Where conditions.
    I have a requirement of creating such a query in an Utility Class, and i have written the code. But its throwing my sysntax errors.
    Please let me know where am I going wrong OR is it really possible to create such a dynamic Query??
        SELECT (FIELDS) INTO TABLE IT_TABLES
          FROM ( (ME->TABLE1)  inner join ( me->table2 )
          on ( on_condition ) )
          WHERE (me->where_fields).
    Ags.

    It worked for me in a following way:
    select * into corresponding fields of table <result_table>
            from (join_string)
            where (l_where).
    Where the contents of join_string were dynamically build using concatenation. So it will be something like
    concatenate ME->TABLE1 'as a INNER JOIN' me->table2 'as b ON (' into join_string separated by space.
    <...>
    add here matching/reference colums, something like
    concatenate 'a~' me->TABLE1_JOIN_COL into temp1.
    concatenate 'b~' me->TABLE2_JOIN_COL into temp2.
    concatenate join_string temp1 '=' temp2 into join_string separated by space.
    <...>
    concatenate join_string ')' into join_string separated by space.
    And then use similar approach for l_where variable.

  • Using JOIN Function with NULL Dynamic Parameters

    I have a report with utilizes dynamic parameters but will not run if any of the parameters are null.  I am also using the JOIN function to print out the values of these parameters. If the user doesn't enter in all the parameters, can the report still run?

    Hi eburton 
    In CR 2008 we have optional parameter functionality, this will allow the report to run without parameter values.
    If you are not using CR2008 then the functionality is not available.
    Thanks,
    Sastry

  • INNER join with dynamic table name ?

    Hi,
    I have a problem with this statement.
    DATA: g_dso_bic_dofr TYPE tabname.
    SELECT t1~/bic/ziparomr
           t2~/bic/zifremom
    INTO (wa_rater_paromr-/bic/ziparomr,
           wa_rater_paromr-/bic/zifremom)
    *   FROM /bic/azd0bfr5100 AS t1     "equivalent to the dynamic statement below
    " this is the  problem
        FROM (g_dso_bic_dofr )AS t1
        INNER JOIN /bic/pzifremom AS t2
          ON t1~/bic/ziparomr = t2~/bic/ziparomr
    " --- to here
        WHERE t1~/bic/zikom     =  v_kommune
    The compile check doesnt work when i use the variable table name.
    I get
    "Wrong expression "INNER" in FROM clause. WHERE condition."
    Can anyone help me.
    Br Rasmus.

    " this is the  problem
    *    FROM (g_dso_bic_dofr )AS t1   "<<--- check spaces in here
        FROM (g_dso_bic_dofr) AS t1    "<<--- and here
        INNER JOIN /bic/pzifremom AS t2
          ON t1~/bic/ziparomr = t2~/bic/ziparomr
    " --- to here
    I think there's the problem, the space behind the parenthesis.
    Regards

  • Dynamic Split Join:Parallel flow using OSB

    Hi,
    I am implementing a dynamic split join in OSB,where in the for -loop i am invoking a database adapter.
    If I select parallel='yes' in the for-loop settings, I get a random number of records from the database as an output.
    While on the other hand, on running the for-loop sequentially, i get the exact number of records i am expecting.
    Could anybody figure out why is this happening?
    Regards,
    Tarun

    If I understand correctly, this is what you are doing:
    Configure a For loop based on a repeating element in source XML (for ex. for each customer id in xml message).
    Inside each loop you are making a DB lookup and getting one record for each element (for ex. customer details of each customer id)
    Finally you are aggregating them in the same variable (join)
    The problem that you see is that if you do it in parallel then you do not see details of all customers in the out variable?
    If yes, then can you please let me know how you are updating the details of each record in the out variable.

Maybe you are looking for

  • Every single clip needs to be rendered suddenly

    Hello, I am a photographer that has now been thrust into shooting a lot of video due to my 5dmkii. I have been converting my footage with mpeg streamclip to pro res 422 and then editing it in fcp with no problems. Suddenly, final cut is requiring me

  • Query on PO report

    Hi Experts! I have one query.. Is there a report which can provide us with the following: -All POs for over £1000 raised between a range of dates     -The PO Numbers     - The Value of the PO     - Vendor Name and Number     - Who raised the orders  

  • My iPad keeps telling me I am not connect to the internet when trying to install iOS 7.1

    My iPad keeps telling me I am not connected to the internet (which I am) when I am trying to download ios 7.1 (it will just not verify the update) & keeps coming up with that message.... It has however installed on my iPhone with no problems!!

  • Saving CSV file on Share Point folder

    Hi, When trying to save a project map to a csv file on a Share Point folder we got this error: "Project does not support resource pooling on a web server". can anyone help me with this? thanks, Yuval

  • Help in USER EXIT in  ME21N

    Hai Friends, My clients requirement is as follows:- While creating a PO if Gross weigth is more then 10 kgs, it has to throw error message as "Purchase Requisition is madatory" if it is less then 10 Kgs it should allow saving the PO without PR refere