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

Similar Messages

  • Table and Primary Key Case Sensitive in Automated Row Fetch

    Why are the table and primary key fields case sensitive in the Automated Row Fetch process? I'm debugging an error in this process and I'm not sure what the case should be.

    Russ - It's a defect of sorts. Use upper case in the process definition. I don't think these processes will work with tables or columns whose names are not known to the database as upper-case values, i.e., defined using double-quoted non-upper case.
    Scott

  • Difference between Unique key and Primary key(other than normal difference)

    Hello,
    1).Can any one tell me any other difference between Unique key and Primary key other than it having NULLs.
    2). What is the difference the words 'DISTINCT' and 'UNIQUE' in a sql query.
    Thanks in advance.

    Hi
    If you don't believe me than see the documentation in
    OTN.
    Ott Karesz
    http://www.trendo-kft.hu
    SQL> create table scott.tbl_clob
      2  (sss CLOB)
      3  /
    Tabelle wurde angelegt.
    SQL> insert into scott.tbl_clob values('wrwrwrw')
      2  /
    1 Zeile wurde erstellt.
    SQL> insert into scott.tbl_clob values('wrwrwrw')
      2  /
    1 Zeile wurde erstellt.
    SQL> select distinct sss from scott.tbl_clob
      2  /
    select distinct sss from scott.tbl_clob
    FEHLER in Zeile 1:
    ORA-00932: nicht übereinstimmende Datentypen
    SQL> select unique sss from scott.tbl_clob
      2  /
    select unique sss from scott.tbl_clob
    FEHLER in Zeile 1:
    ORA-00932: nicht übereinstimmende Datentypen
    SQL> select distinct to_char(sss) from scott.tbl_clob
      2  /
    TO_CHAR(SSS)
    wrwrwrw
    SQL> select unique to_char(sss) from scott.tbl_clob
      2  /
    TO_CHAR(SSS)
    wrwrwrw
    SQL>

  • How to know primary key column name form a table name in sql query

    Suppose I only know the table name. How to get its primary key column name from the table name?
    Thanks

    Views don't have primary keys though their underlying tables might. You'd need to pick apart the view to determine where it's columns are coming from.
    You can select the text of the view in question from user_views.

  • Logical standby and Primary keys

    Hi All,
    Why primary keys are essential for creating logical standby database? I have created a logical standby database on testing basis without having primary keys on most of the tables and it's working fine. I have not event put my main DB in force logging mode.

    I have not event put my main DB in force logging mode. This is because, redo log files or standby redo logfiles transforms into set of sql statements to update logical standby.
    Have you done any DML operations with nologging options and do you notice any errors in the alert.log? I just curious to know.
    But I wanted to know that, while system tablespace in hot backup mode,In the absence of both a primary key and a nonnull unique constraint/index, all columns of bounded size are logged as part of the UPDATE statement to identify the modified row. In other words, all columns except those with the following types are logged: LONG, LOB, LONG RAW, object type, and collections.
    Jaffar

  • Null value in detail table's primary key

    I use Business Components Data Form to define a master-detail java panel.
    I don't display the primary key column in the detail grid control.
    Then I click on "+" to add a row, enter a value (the 2nd part of the detail table's primary key) and click commit.
    I get an error saying that the primary key column that's not displayed is null and the row cann't be committed.
    How do I fix this error?

    My fields are varchar2's.
    -- simplified to protect the guilty:
    -- (made up from memory, so sql keywords may --be misspelled, but you get the idea)
    create table proj (
    proj varchar2(10) not null,
    constraint proj_pk
    primary key(proj)
    insert into proj values ('abc');
    commit;
    -- this table has legal values for -- the master.legal field.
    -- in master, legal was changed to a -- ComboBoxControl control from -- TextFieldControl that the wizard -- generated.
    create table legal_values (
    proj varchar2(10) not null,
    legal varchar2(10) not null,
    display_order integer not null,
    constraint legal_values_pk
    primary key (proj, legal)
    insert into legal_values
    values ('abc', 'one', 1);
    insert into legal_values
    values ('abc', 'two', 2);
    insert into legal_values
    values ('abc', 'three', 3);
    commit;
    create table master (
    proj varchar2(10) not null,
    masterKey varchar2(15) not null,
    legal varchar2(10) not null,
    constraint master_pk
    primary key (proj, masterKey)
    create table detail (
    proj varchar(10) not null,
    masterKey varchar(15) not null,
    detailkey varchar(10) not null,
    display_order integer not null,
    status varchar2(12) not null, -- user can only update this field
    constraint detail_pk
    primary key(proj, masterkey, detailkey)
    -- legal rows for detail table
    create table detail_values (
    proj varchar2(10) not null,
    detailkey varchar2(10) not null,
    display_order integer not null,
    constraint detail_values_pk
    primary key(proj, detailkey)
    insert into detail_values values
    ('abc', 'status a', 1);
    insert into detail_values values
    ('abc', 'status b', 2);
    commit;
    -- if their is a foriegn key on details back
    -- to master, then you get the
    -- "mutating table" error when trigger
    -- occurs.
    create or replace trigger master_tr
    after insert on master
    for each row
    begin
    insert into detail
    (masterKey, detailKey, status, display_order, status)
    select :new.masterkey, detail_key, display_order, ' '
    from detail_values;
    end;
    -- detail.status is a comboboxControl getting --its values of of another db table too.
    -- there's also "after update" triggers on master and detail tables that copy the record to master_history and "detail_history" tables if the corresponding table is modified. Thus we have a history of the changes made to the records. The 2 history tables have 2 additional fields than their parents, "modified_date date default sysdate not null" and "modified_by varchar2(30) default user not null" that record when and who made the change. There's also a change type field that records where the change is an insert, delete or update (there 3 triggers per table , so we can correctly record change type as being insert, delete or update into the change_type field).
    If you want to make it more real to life, the status value is initially blank, then can be changed to a legal status value (complete or not complete), but can not be changed back to blank.
    ***P.S. I have to have this ready for production by monday.****
    P.P.S After you reply and change to ComboBoxControls in 2 places, try changing the table names and/or the column names (say to follow the DBA's naming convention) or add another field to the composite primary key (and unstated foriegn key) (using drop table/create table). Now try getting the existing code to run. No writing down the old/new table (or column) name pair names. Just run the code and try to fix the code based on the error messages. Are the error messages giving you adequate information to find the problem?

  • NULL in primary keys NOT logged to exceptions table

    Problem: Inconsistent behavior when enabling constraints using the "EXCEPTIONS INTO" clause. RDBMS Version: 9.2.0.8.0 and 10.2.0.3.0
    - NULL values in primary keys are NOT logged to exceptions table
    - NOT NULL column constraints ARE logged to exceptions table
    -- Demonstration
    -- NULL values in primary keys NOT logged to exceptions table
    TRUNCATE TABLE exceptions;
    DROP TABLE t;
    CREATE TABLE t ( x NUMBER );
    INSERT INTO t VALUES ( NULL );
    ALTER TABLE t
    ADD ( CONSTRAINT tpk PRIMARY KEY (x) EXCEPTIONS INTO exceptions );
    SELECT * FROM exceptions; -- returns no rows
    -- NOT NULL column constraints logged to exceptions table
    TRUNCATE TABLE exceptions;
    DROP TABLE t;
    CREATE TABLE t ( x NUMBER );
    INSERT INTO t VALUES ( NULL );
    ALTER TABLE t MODIFY ( X NOT NULL EXCEPTIONS INTO EXCEPTIONS );
    SELECT * FROM exceptions; -- returns one row
    I would have expected all constraint violations to be logged to exceptions. I was not able to find any documentation describing the behavior I describe above.
    Can anyone tell me if this is the intended behavior and if so, where it is documented?
    I would also appreciate it if others would confirm this behavior on their systems and say if it is what they expect.
    Thanks.
    - Doug
    P.S. Apologies for the repost from an old thread, which someone else found objectionable.

    I should have posted the output. Here it is.
    SQL>TRUNCATE TABLE exceptions;
    Table truncated.
    SQL>DROP TABLE t;
    Table dropped.
    SQL>CREATE TABLE t ( x NUMBER );
    Table created.
    SQL>INSERT INTO t VALUES ( NULL );
    1 row created.
    SQL>ALTER TABLE t ADD ( CONSTRAINT tpk PRIMARY KEY (x) EXCEPTIONS INTO exceptions );
    ALTER TABLE t ADD ( CONSTRAINT tpk PRIMARY KEY (x) EXCEPTIONS INTO exceptions )
    ERROR at line 1:
    ORA-01449: column contains NULL values; cannot alter to NOT NULL
    SQL>SELECT * FROM exceptions;
    no rows selected
    SQL>
    SQL>TRUNCATE TABLE exceptions;
    Table truncated.
    SQL>DROP TABLE t;
    Table dropped.
    SQL>CREATE TABLE t ( x NUMBER );
    Table created.
    SQL>INSERT INTO t VALUES ( NULL );
    1 row created.
    SQL>ALTER TABLE t MODIFY ( X NOT NULL EXCEPTIONS INTO EXCEPTIONS );
    ALTER TABLE t MODIFY ( X NOT NULL EXCEPTIONS INTO EXCEPTIONS )
    ERROR at line 1:
    ORA-02296: cannot enable (MYSCHEMA.) - null values found
    SQL>SELECT * FROM exceptions;
    ROW_ID OWNER TABLE_NAME CONSTRAINT
    AAAkk5AAMAAAEByAAA MYSCHEMA T T
    1 row selected.
    As you can see, I get the expected error message. But I only end up with a record in the exceptions table for the NOT NULL column constraint, not for the null primary key value.

  • Diff b/w surragate keys and primary keys

    Can any one of u pls explain the difference between primary key and surragate keys,pls explain me with simple example

    Hi rajesh,
    surrogate key: For every master data record, system create a SID (Surrogate ID). If that particular master data record is used in infocube, system store the SID corresponding to that master data in dimension table and the dimension id of the dimension table is stored in infocube Fact 'F' table.
    Primary key: while creating a table we will select unique field and create as primary key..for eg empid acts as a unique key (primary key) for emp table. through this primary key we can identify the table to get the data from the table.
    i hope this helps u.
    regards
    anil

  • How to add a new data element for existing table filed(Primary key field)

    Hi Experts,
    How to add a new data element for existing table field(Primary key field)
    For this filed ther is no foreign key relation ships and even check table.
    while activating table it is giving message like below.
    can you help any one to solve this and wil steps to add new dataelement for existing primary key filed of a table.
    Check table (NAMING SPACE/TABLE NAME(EX:/TC/VENDOR)) (username/19.02.10/03:29)           
    Primary key change not permitted for value table /TC/VENDOR
    Check on table  /TC/VENDOR resulted in errors              
    Thanks
    Ravi

    Hi,
    Easiest way is to download the table eg into an Excel table (if possible) or text table. Drop the table from the database. Build your table with the new key field. Build the database table again and fill it.
    You can do it also over the database into a new table. Drop the old one. Build the enhanced one and fill it. Afterwards drop your (temporary) table.
    Maybe there are other ways, but this works.
    Success,
    Rob

  • Problem with type conversion and primary key during row fetch

    [Note, this error occurs in Oracle XE, APEX 2.1.0.00.39]
    I have been having a problem with Automatic Row Fetch:
    ORA-01460: unimplemented or unreasonable conversion requested
    So in an effort to resolve this, I created a PL/SQL process with the query below and was able to isolate the same error. The problem seems to come from one of the primary keys being a "number" type (APP_ID). The error occurs on the line:
    where u.app_id=:P5_APP_ID
    I have tried the following variations on this line in an effort to resolve this, but all generate the same error:
    1) where to_char(u.app_id) = :P5_APP_ID
    2) where u.app_id = to_number(:P5_APP_ID)
    3) where to_char(u.app_id) = to_char(:P5_APP_ID)
    I've also tried the laternate syntax "&__." and "#__#", but these don't function in the Source field and show up as syntax errors.
    Any suggestions are welcome.
    begin
    for r in (
    select app_name, apptype, appcreator, appurl
    from application_users u, application_info i
    where u.app_id=:P5_APP_ID
    and i.app_id=u.app_id
    and u.username=:P5_USERNAME)
    loop
    begin
    :P5_APP_NAME := r.app_name;
    :P5_APPURL := r.appurl;
    exception
    when others then
    raise_application_error(-20000,'In Loop Failure',true);
    end;
    end loop;
    exception
    when others then
    raise_application_error(-20000,'Out of Loop Failure',true);
    end;
    Thanks in advance,
    Barney

    I found a prior post referencing a similar issue and it was solved by using the "v(__)" syntax. This did resolve my issue, however, I have a quick follow-on which I'm hoping someone can answer quickly...
    Since the "v(__)" syntax won't work for the Automatic Row Fetch (at least to the best of my knowledge), I have to do a manual process. However, the manual query as shown above doesn't actually populate any of the form values through the bind variables. They all remain at their cached values from prior data entry on the form.
    Is using the bind variables for assignment incorrect, or is there something that must be done to get the updates to show up in the form (ordering of processes, etc.).
    My manual process is running in the Load: Before Header state so I would have expected it to update all of the fields.
    Thanks in advance,
    Barney

  • Adding 2 new fields as Primary Key field in a Z Table which is existing PRD

    Hi Friends,
    I have to add two new fields as primary key fields in a Z TABLE, which is existing in Quality and Production Systems with Data.
    If I incorporate these two new fields (Primary Key fields) in development and if the TR is moved to Quality and Production sytems, is there any possibility of loss in data will happen at Quality and Prd systems?
    At present, Table is having 20 fields with 2 primary key fields and i have to add 2 more primary key fields.
    I have checked in SCN and not find relevant threads.
    Please help me out.
    Regards,
    Suresh.

    NO . It wont be a problem .
    For ex :
    If you have VBELN  , POSNR are key fields now , you have an unique reord with that combination .
    If you add one other field in it  fo ex  VKBUR  then records will be like this
    VBELN     POSNR     VKBUR   MATERIAL   QTY
    10020      10                            abcxyz      1
    10020      10            1234        abcxyz     1
    So your previous records before adding new primary keys , will have new fields balnk , and the new records will have data filled up in all primary key fields .
    However , if you try to update the existing records that will be in existing PRIMARYKEY combination only .
    for example if you try update record 1 above with VKBUR value 85858 , it creates a new record , it wont be updated in existing record.
    Hope this helps , Pls let me know if u have any more doubts.

  • Unique and primary key

    column with unique constraint + not null constraint = primary key! (to some extent) Is it correct?
    I invite your ideas

    http://www.techonthenet.com/oracle/unique.php
    http://www.allapplabs.com/interview_questions/db_interview_questions.htm#q13
    Difference between Unique key and Primary key(other than normal difference)

  • Join Between W_PERSON_F and W_POSITION_D

    Hi,
    I want to join W_PERSON_F fact table and W_POSITION_D dimension table. Database: Siebel DB.
    Is there any direct join or we want to join through some other table?
    Thanks,
    Satheesh

    As per my knowledge there is no direct join between w_person_f and w_position_d
    but you can create an alisa of w_person_d as contact(w_person_d) and join with w_person_f
    as below
    contact(w_person_d).row_wid = w_person_f.contact_wid
    please mark the ans if it is correct.
    Thanks

  • Knowing the primary key columns of the given table

    Hi,
    How can I get the primary key columns of the given table?
    Regards,
    Sachin R.K.

    You can find the constraint_name from all_constraints/user_constraints for constraint_type = 'P' (which is the primary key constraint).
    And then see which columns are in for the constriant_name
    in all_cons_columns/user_cons_columns view.
    Below is the example
    select acc.column_name from
    all_cons_columns acc, all_constraints ac
    where acc.constraint_name = ac.constraint_name
    and acc.table_name = 'DEPT' AND acc.owner = 'SCOTT'
    and ac.constraint_type = 'P'
    Hope this helps
    Srinivasa Medam

  • Primary key constraint for index-organized tables or sorted hash cluster

    We had a few tables dropped without using cascade constraints. Now when we try to recreate the table we get an error message stating that "name already used by an existing constraint". We cannot delete the constraint because it gives us an error "ORA-25188: cannot drop/disable/defer the primary key constraint for index-organized tables or sorted hash cluster" Is there some sort of way around this? What can be done to correct this problem?

    What version of Oracle are you on?
    And have you searched for the constraint to see what it's currently attached to?
    select * from all_constraints where constraint_name = :NAME;

Maybe you are looking for

  • Creating a Sales Order using Web Dynpro

    Hi SDN,   I want to create a Sales Order using Web Dynpro application. For that i have used "Bapi_Salesorder_Createfromdat2" as a adaptive RFC model. Every thing is fine and i could able to create a sales order for a single line item. But my intensio

  • Inserting or embed and image into cfmail output from a database-stored path to an actual image.

    I am trying to insert or embed and image into cfmail from a database-stored path to an actual image. The actual JPEG image is stored in a folder called "images_personnel". The path to the image under the column titled photopath is stored in my databa

  • Podcasts disappear after having had them on iPod already

    Hey all, I have an iPod 5G 60GB Video. I have got two problems which only occurr with specific podcasts (my favorite podcast, in my case TikiBarTV): Problem One: 1. a.) I had the first 9 episodes on my iPod. b.) Then I downloaded the remaining ones (

  • Elementary question on Logical SQL subquery

    Hello. I am a newbie using Oracle Business Intelligence Product Version 10.1.3.4.1 (Build 090414.1900). I am trying (and failing) to get something such as this accepted by Answers -> Set SQL - SELECT      A.saw_1     saw_0,      SUM(1)     saw_1 FROM

  • Building a block based on query

    Hi, I've to build a block containing empnumbers from emp table for the emp names entered by the user. EX: If emp enters SMITH,KING in a text item ,I've to build a mutlirecord block containing emp numbers of these emp names. I know I've to use EXEC_SQ