Dynamic SQL - Inner Join

I just starting to Learn and use Dynamic SQL. 
I am trying use a inner join query in dynamic SQL 
for Example say 'Select A.id as Itemid , A.name as Itemname from TableA A inner join TableB B On A.ID = B.ID where B.ID typeid = 1 '
for some reason this is not working . i for sure know the query works as when i run the query it works fine. when i try to run it dynamically it give me blank values.
Please let me know if you need more information.
Appreicate Your help!!
Thanks,
Chaitanya 

Here is an example for dynamic SQL from BOL:
DECLARE @IntVariable int;
DECLARE @SQLString nvarchar(500);
DECLARE @ParmDefinition nvarchar(500);
/* Build the SQL string one time.*/
SET @SQLString =
N'SELECT BusinessEntityID, NationalIDNumber, JobTitle, LoginID
FROM AdventureWorks2012.HumanResources.Employee
WHERE BusinessEntityID = @BusinessEntityID';
SET @ParmDefinition = N'@BusinessEntityID tinyint';
/* Execute the string with the first parameter value. */
SET @IntVariable = 197;
EXECUTE sp_executesql @SQLString, @ParmDefinition,
@BusinessEntityID = @IntVariable;
/* Execute the same string with the second parameter value. */
SET @IntVariable = 109;
EXECUTE sp_executesql @SQLString, @ParmDefinition,
@BusinessEntityID = @IntVariable;
Basically any query can be run as dynamic SQL.  However, static SQL is the first choice. Use dynamic SQL if needed.
Dynamic SQL examples:
http://www.sqlusa.com/bestpractices/dynamicsql/
Kalman Toth Database & OLAP Architect
SQL Server 2014 Design & Programming
New Book / Kindle: Exam 70-461 Bootcamp: Querying Microsoft SQL Server 2012

Similar Messages

  • PL/SQL Inner Join

    Hello.
    I'm trying to join 2 tables. The problem is one record in 1st table is in simple latin (f.e. MODIFIED) and the second one in 2nd table includes polish symbols (f.e. MÓDIFIĘD). I want to ignore polish symbols and simplify them into latin coding. Since today I used to join tables with COLLATE (sql). Is there any equivalent of COLLATE function in PL/SQL?
    In summary.
    1st in:
    1234 MODIFIED NAME SURNAME PRODUCT
    2nd in:
    1 MÓDIFIĘD DATA ADRESS
    3rd - results:
    MODIFIED NAME SURNAME ADRESS
    I'm using Oracle SQL Developer. Database version - latest.
    Thanks. Sincerely - Marcin.
    Edited by: 888729 on 2011-09-30 03:17

    Thanks for quick response, but the problem is not solved. I'll try to show you my objective more clearly.
    888729 wrote:
    SELECT DISTINCT nt.id, nt.priority, nt.determined_on, nt.assigned_group, assigned.email, FROM notifications nt
    INNER JOIN ASSIGNED ON ASSIGNED.ASSIGNED_GROUP = nt.ASSIGNED_GROUP
    WHERE nt.DETERMINED_ON > (SYSDATE-10)
    So, I have two tables: notifications and assigned. In the first table (notifications) I have column ASSIGNED_GROUP and in the second one (assigned) the same column ASSIGNED_GROUP (both the same type). If I join those two tables there will be a problem with coding. For example:
    table notifications, cell ASSIGNED_GROUP:
    ABC_MAGIC
    table assigned, cell ASSIGNED_GROUP:
    ĄBĆ_MĄGIĆ
    I need those rows to be joined together. So I need to ignore polish symbols in 2nd line of my script (INNER JOIN).

  • INNER JOIN, MX 7, column name error

    I am running or attempting to run the att'd query in CF MX
    7.0 and getting an error because I then run:
    <CFOUTPUT QUERY="getNutes" group="NUTR_NO">
    <CFSET VALUE = 0>
    <CFOUTPUT>
    <CFIF Day EQ "T">
    <CFSET VALUE = VALUE + (getNutes.Total_WT *
    getNutes.NUTR_VAL/100) / getDays.RecordCount>
    <CFELSE>
    <CFSET VALUE = VALUE + (getNutes.Total_WT *
    getNutes.NUTR_VAL/100)>
    </CFIF>
    </CFOUTPUT>
    To sum the nutrient contents...
    This worked fine under CF 5... but I am getting a 'NUTR_NO
    does not specify a column name in the query'.
    Any thoughts???
    Query follows:

    > Yep... it's worse... it appears that MX does not support
    the sql inner join or
    > outer join... sigh...
    Don't be ridiculous. You're showing a fundamental lack of
    understanding of
    how CF handles database interaction. When you use
    <cfquery> to "create" a
    recordset, all CF does is resolve any embedded CF (tags,
    functions,
    variables, etc), and passes the resulting string to the DB.
    The DB then
    processes it and returns a recordset. So CF doesn't "support"
    any sort of
    SQL syntax. Now does it claim to; nor does it try to; nor is
    it
    appropriate for it to.
    If you're having problems with your returned recordset, the
    first thing you
    should do is <cfdump> it (or part of it) and check that
    you're getting back
    what you're *assuming* you're getting back.
    The second thing you should do is lose the SELECT *. Specify
    the columns
    you want back. This is nothing to do with CF, it's just
    standard SELECT
    query advice. When you're joining tables, you hardly ever
    want ALL the
    columns back, and if it's one of those rare occasions you DO
    want all of
    them, you should still specify a SELECT clause so you can
    distinguish
    between same-named columns (which seems to be your problem
    here).
    Adam

  • 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

  • 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

  • Want to create dynamic SQL with table join

    I want to create a dynamic SQL query so that the user can enter any two table names on the selection screen and two field names that he wants to join. After which i should be able to dynamically generate the SQL (native or open) and show the result as report. I have already read the forum threads and know how to create dynamic SQL for single table, what i m struggling with is how to do inner join. I know i can use nested select but that will make the query very slow because i want to extend it to more than 2 tables later.
    Will give points to useful answer for sure, thanks for reading.

    Hi,
    Following is a piece of code which I have used in my program.
    DATA: ws_flds(72)   TYPE c.
    DATA: ftab  LIKE TABLE OF ws_flds.
    ws_flds = 'rbukrs rprctr racct ryear '.
      APPEND ws_flds TO ftab.
       SELECT (ftab)
        INTO CORRESPONDING FIELDS OF TABLE it_grp_glpca
        FROM glpca FOR ALL ENTRIES IN i_cert_item
        WHERE kokrs = c_kokrs
            AND rldnr = '8A'
            AND rrcty IN ('0','2')
            AND rvers  = '000'
            AND rbukrs = i_cert_item-bukrs
            AND ryear  = p_ryear
            AND rprctr = i_cert_item-prctr
            AND racct  = i_cert_item-saknr
            AND ( poper BETWEEN '001' AND ws_poper )
            AND aufnr IN s_aufnr
            AND kostl IN s_kostl
            AND rfarea IN s_fkber
            AND rmvct IN s_rmvct
            AND sprctr IN s_sprctr
            AND ( racct BETWEEN c_low AND c_high ).
    You can now pass your table name as (p_table) or append fieldnames to the internal table (ftab). if it is join then you can append this table like abukrs asaknr..etc.
    Regards
    Subramanian

  • 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

  • Help with Inner Join query in SQL

    Hope someone can help with this, as this is quite an involved project for me, and I'm just about there with it.
    My table structure is :
    table_packages
    packageID
    package
    packageDetails
    etc
    table_destinations
    destinationID
    destination
    destinationDetails
    etc
    table_packagedestinations
    packageID
    destinationID
    ..so nothing that complicated.
    So the idea is that I can have a package details page which shows the details of the package, along any destinations linked to that package via the packagedestinations table.
    So this is the last part really - to get the page to display the destinations, but I'm missing something along the way....
    This is the PHP from the header, including my INNER JOIN query....
    PHP Code:
    <?php
    $ParampackageID_WADApackages = "-1";
    if (isset($_GET['packageID'])) {
      $ParampackageID_WADApackages = (get_magic_quotes_gpc()) ? $_GET['packageID'] : addslashes($_GET['packageID']);
    $ParamSessionpackageID_WADApackages = "-1";
    if (isset($_SESSION['WADA_Insert_packages'])) {
      $ParamSessionpackageID_WADApackages = (get_magic_quotes_gpc()) ? $_SESSION['WADA_Insert_packages'] : addslashes($_SESSION['WADA_Insert_packages']);
    $ParampackageID2_WADApackages = "-1";
    if (isset($_GET['packageID'])) {
      $ParampackageID2_WADApackages = (get_magic_quotes_gpc()) ? $_GET['packageID'] : addslashes($_GET['packageID']);
    mysql_select_db($database_connPackages, $connPackages);
    $query_WADApackages = sprintf("SELECT packageID, package, costperpax, duration, baselocation, category, dateadded, agerange, hotel, educational_tours, field_trips, corporate_outings, plant_visits, budget_package, rollingtours, teambuilding, description, offer FROM packages WHERE packageID = %s OR ( -1= %s AND packageID= %s)", GetSQLValueString($ParampackageID_WADApackages, "int"),GetSQLValueString($ParampackageID2_WADApackages, "int"),GetSQLValueString($ParamSessionpackageID_WADApackages, "int"));
    $WADApackages = mysql_query($query_WADApackages, $connPackages) or die(mysql_error());
    $row_WADApackages = mysql_fetch_assoc($WADApackages);
    $totalRows_WADApackages = mysql_num_rows($WADApackages);
    $colname_educationalDestinations = "1";
    if (isset($_GET['PackageID'])) {
      $colname_educationalDestinations = (get_magic_quotes_gpc()) ? packageID : addslashes(packageID);
    mysql_select_db($database_connPackages, $connPackages);
    $query_educationalDestinations = sprintf("SELECT * FROM destinations INNER JOIN (packages INNER JOIN packagedestinations ON packages.packageID = packagedestinations.packageID) ON destinations.destinationID = packagedestinations.destinationID WHERE packages.packageID = %s ORDER BY destination ASC", GetSQLValueString($colname_educationalDestinations, "int"));
    $educationalDestinations = mysql_query($query_educationalDestinations, $connPackages) or die(mysql_error());
    $row_educationalDestinations = mysql_fetch_assoc($educationalDestinations);
    $totalRows_educationalDestinations = mysql_num_rows($educationalDestinations);
    ?>
    And where I'm trying to display the destinations themselves, I have : 
    <table>
            <tr>
                     <td>Destinations :</td>
                </tr>
               <?php do { ?>
            <tr>
                 <td><?php echo $row_educationalDestinations['destination']; ?></td>
            </tr>
            <?php } while ($row_educationalDestinations = mysql_fetch_assoc($educationalDestinations)); ?>
    </table>
    If anyone could have a quick look and help me out that would be much appreciated - not sure if its my SQL at the top, or the PHP in the page, but either way it would be good to get it working. 
    Thanks.

    First off, you need to get the database tables so that there is a relationship between them.
    In fact, if there is a one to one relationship, then it may be better to store all of your information in one table such as
    table_packages
    packageID
    package
    packageDetails
    destination
    destinationDetails
    etc
    If there is a one to many relationship, then the following would be true
    packages
    packageID
    package
    packageDetails
    etc
    destinations
    destinationID
    packageID
    destination
    destinationDetails
    etc
    The above assumes that there are many destinations to one package with the relationship coloured orange.
    Once you have the above correct you can apply your query as follows
    SELECT *
    FROM packages
    INNER JOIN destinations
    ON packages.packageID = destinations.packageID
    WHERE packages.packageID = %s
    ORDER BY destination ASC
    The above query will show all packages with relevant destinations

  • Why can't i use "INNER JOIN" in a query for SQL Server with JDBC??????

    Hi,
    I'm trying to execute some SQL queries and I just don't understand what's wrong.
    I�m using Tomcat and SQL Server in order to do this, but when I�m try to execute a query with a INNER JOIN statements Tomcat raise a SQL exception... at the very first time I thought there was a problem with database connection but I realize that a simple query to a table works pretty well. then I found out some problems with JDBC:ODBC.... so I install JDBC for SQL Server 2000 and test with the same simple query and works..... so, I come to a conclusion.... INNER JOIN or JOIN statements can't be used in JDBC..... please... somebody tell I�m wrong and give me a hand...
    I'm using TOMCAT 4 and JDK 1.4 SQL Server 2000
    Error occurs when executeQuery() is called.... not prepareStatement().... ??????
    Driver DriverRecResult = (Driver)Class.forName(driver).newInstance();
    Connection ConnRecResult = DriverManager.getConnection(DSN,user,password);
    PreparedStatement StatementRecResult = ConnRecResult.prepareStatement(query);
    ResultSet RecResult = StatementRecResult.executeQuery(); <---- Exception raise here
    So much tahnks in advance,

    That's exactly what I think, driver it's raising the exception, but I don't know why.... i test the same query with INNER JOIN directly from SQL Query Analyser and it's works perfectly, my problem ain't SQL, but JSP and JDBC 'cause i'm a newbie about these issues.
    Common sense tell me possible problems lie in SQLServer drivers 'cause i run the same pages on JRUN through jdbc:odbc and do works well, but by now i just depend on Tomcat.....
    I've installed SQL Server drivers for JDBC but i just find it doesn't work fully... could be the version of JDK i've installed? what version do i need?
    ( I'm running Tomcat 4 with JDK 1.4 & SQL Server 2000 W2K )
    thanks for reply.

  • 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

  • Please tell me the  Three table INNER JOIN Sql statement

    Hi experts,
      I got requirement like by using INNER JOIN i have to write the code in MY program i.e using 3 tables VBAK VBAP and VBUK.And the common field is VBELN .SO please give the  INNER JOIN SQL statement for above three tables...
    vbak-vbeln,erdat
    vbap-vbeln,posnr
    vbuk-vbeln,RFSTK
    Thanks in Advance

    hi guglani  please see my total code b.caus DATA is not extracting...once see the code  correct error.
    DATA:V_VBELN TYPE VBAK-VBELN.      "VBAK,VBAP AND VBUK
    SELECT-OPTIONS SORDER FOR V_VBELN.
    TYPES:BEGIN OF T_VBAK,
         VBELN TYPE VBELN_VA,
         ERDAT TYPE ERDAT,
      END OF T_VBAK.
    TYPES:BEGIN OF T_VBAP,
           VBELN TYPE VBELN_VA,
            POSNR TYPE POSNR_VA,
      END OF T_VBAP.
    TYPES:BEGIN OF T_VBUK,
        VBELN TYPE VBELN,
      RFSTK TYPE RFSTK,
      END OF T_VBUK.
    TYPES:BEGIN OF FS,
       VBELN TYPE VBELN_VA,
         ERDAT TYPE ERDAT,
    POSNR TYPE POSNR_VA,
      RFSTK TYPE RFSTK,
      END OF FS.
    DATA:WA1 TYPE T_VBAK,
         WA2 TYPE T_VBAP,
         WA3 TYPE T_VBUK,
         WA TYPE FS.
    DATA:ITAB1 TYPE TABLE OF T_VBAK,
          ITAB2 TYPE TABLE OF T_VBAP,
          ITAB3 TYPE TABLE OF T_VBUK,
          ITAB TYPE TABLE OF FS.
    select a~vbeln a~erdat b~posnr c~rfstk
           from vbak as a inner join vbAP as b on a~vbeln = b~vbeln
                          inner join vbuk as c on a~vbeln = c~vbeln
    into table itab
    where A~vbeln eq SORDER.
    IF NOT ITAB IS INITIAL.
      SORT ITAB BY VBELN.
    ENDIF.
    LOOP AT ITAB INTO WA.
       WRITE:/ WA-VBELN,WA-ERDAT,WA-rfstk.
       ENDLOOP.
       CLEAR WA.
       REFRESH ITAB.

  • 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

  • Inner Join for Dynamic Select statement

    Hi All,
      Can some one please help me in rewriting the below select statement where i have to remove the existing table1 by putting a dynamic table name which has the same table structure.
      select a~zfield1
               a~zfield2
          from ztab1 as a
           inner join ztab2 as b
               on b~ztab1-zfield3 = a~ztab2-zfield3
         where a~zfield4 = 'A'.
    I am looking something as below. But encountering an error when using the below statement
      select a~zfield1
               a~zfield2
          from (v_ztab1) as a
           inner join ztab2 as b
               on b~ztab1-zfield3 = a~ztab2-zfield3
         where a~zfield4 = 'A'.
      No Separate selects please. Please help me in rewriting the same select statement itself.
    Regards,
    PSK

    hi,
    What error you are getting ?
    Also INTO is missing from the statement.
    SELECT  pcarrid pconnid ffldate bbookid
      INTO  TABLE itab
      FROM  ( spfli AS p
                INNER JOIN sflight AS f ON pcarrid = fcarrid AND
                                           pconnid = fconnid    )
      WHERE p~cityfrom = 'FRANKFURT' AND
            p~cityto   = 'NEW YORK' .
    thanks

  • Dynamic BD table name with inner join.

    Hi experts,
    I'm trying to do something like  this:
    if syst-datum(4)   > s_budat-high(4) or
       syst-datum4(2) > s_budat-high4(2).
      tabname = 'MBEWH'.
    else.
      tabname = 'MBEW'.
    endif.
    select m1matnr m1mtart m3~bwkey
      from ( mara as m1
          inner join marc as m2
            on m1matnr = m2matnr
          inner join (tabname) as m3
            on m1matnr = m3matnr and
               m2werks = m3bwkey )
      where m1~matnr in s_matnr and
            m1~lvorm in s_lvorm and
            m1~mstae in s_mstae and
            m2~werks in s_werks.
    endselect.
    I get the following error: Incorrect expression "1000  %_#T953" in WHERE condition.          
    Should I forget the inner join with one dynamic table or is it possible to do?
    Thanks in advance, best regards,
    André Costa

    Hi experts,
    I'm trying to do something like  this:
    if syst-datum(4)   > s_budat-high(4) or
       syst-datum4(2) > s_budat-high4(2).
      tabname = 'MBEWH'.
    else.
      tabname = 'MBEW'.
    endif.
    select m1matnr m1mtart m3~bwkey
      from ( mara as m1
          inner join marc as m2
            on m1matnr = m2matnr
          inner join (tabname) as m3
            on m1matnr = m3matnr and
               m2werks = m3bwkey )
      where m1~matnr in s_matnr and
            m1~lvorm in s_lvorm and
            m1~mstae in s_mstae and
            m2~werks in s_werks.
    endselect.
    I get the following error: Incorrect expression "1000  %_#T953" in WHERE condition.          
    Should I forget the inner join with one dynamic table or is it possible to do?
    Thanks in advance, best regards,
    André Costa

  • How to use Inner join of table as Source in Merge statement in SQL

    Hi All,
        I am trying to make source as multiple tables output using Join while coding there is no any syntax error but when i am executing this statement is giving following error
    Following is the query 
    Merge Into EmpDept Target
    Using (select E.Address,e.Design,e.EmailId,e.EmpId,e.Ename,e.ManagerId, e.Salary,D.DeptId,D.DeptName,D.Location from Employee E Inner join Dept D on E.DeptId=D.DeptId )As Source (Address,Design,EmailId,EmpId,EName,ManagerId,Salary,DeptId,DeptName,Location)
    On Source.EmpId=Target.EmpId
    when not matched then
    Insert (Target.Address,Target.Design,Target.EmailId,Target.EmpId,Target.Ename,Target.ManagerId, Target.Salary,Target.DeptId,Target.DeptName,Target.Location)
    values
    (Address,Design,EmailId,EmpId,EName,ManagerId, Salary,DeptId,DeptName,Location)
    When matched then 
    Update set Target.Address = Source.Address ,Target.Design = Source.Design,Target.EmailId      = Source.EmailId     ,Target.Ename       = Source.Ename      ,Target.ManagerId = Source.ManagerId , Target.Salary        = Source.Salary       ,Target.DeptId      = Source.DeptId      ,Target.DeptName = Source.DeptName ,Target.Location    = Source.Location;
    This is error while executing the above merge statement 
    The insert column list used in the MERGE statement cannot contain multi-part identifiers. Use single part identifiers instead.
    Please suggest me where i am wrong.. 
    Niraj Sevalkar

    MERGE INTO EmpDept Target
    Using (SELECT E.Address,
    e.Design,
    e.EmailId,
    e.EmpId,
    e.Ename,
    e.ManagerId,
    e.Salary,
    D.DeptId,
    D.DeptName,
    D.Location
    FROM Employee E
    INNER JOIN Dept D
    ON E.DeptId = D.DeptId) AS Source (Address, Design, EmailId, EmpId, EName, ManagerId, Salary, DeptId, DeptName, Location)
    ON Source.EmpId = Target.EmpId
    WHEN NOT matched THEN
    INSERT (Address,
    Design,
    EmailId,
    EmpId,
    Ename,
    ManagerId,
    Salary,
    DeptId,
    DeptName,
    Location)
    VALUES (Address,
    Design,
    EmailId,
    EmpId,
    EName,
    ManagerId,
    Salary,
    DeptId,
    DeptName,
    Location)
    WHEN matched THEN
    UPDATE SET Address = Source.Address,
    Design = Source.Design,
    EmailId = Source.EmailId,
    Ename = Source.Ename,
    ManagerId = Source.ManagerId,
    Salary = Source.Salary,
    DeptId = Source.DeptId,
    DeptName = Source.DeptName,
    Location = Source.Location;

Maybe you are looking for