Conditional DDL

Does anyone have some samples of Conditional DDL execution, for eg create an object if it does not exist in any of the DBA views .

Hi,
Use EXECUTE IMMIDIATE For Conditional DDL.
Bye
Chitta

Similar Messages

  • ORA-00001 - Unique Constraint on R5TRANSLINES

    Hello,
    I get the following error when i am inserting into R5TRANSLINES "2009-06-23 14:44:51,698 DEBUG [com.dstm.mp.MPDBException] **!!Error Code:|1|, Msg:|ORA-00001: unique constraint (REMPLOY.R5PRIK_TRL) violated"
    I have a flex trigger in the system which is envoked when inserting parts into my warehouse:
    Declare
    cursor c_palletparts( pallet varchar2) is
    select obj_part from r5objects
    where
    obj_parent = pallet;
    v_pallet varchar2(255);
    v_evtcode varchar2(255);
    v_transcode varchar2(255);
    v_line number :=0;
    v_store varchar2(255);
    v_trltype varchar2(4);
    v_trlrtype varchar2(4);
    v_trlio number;
    v_bin VARCHAR2(15);
    v_binin VARCHAR2(15);
    ncounter number;
    cur_message varchar2(200);
    begin
    select trl_part, trl_trans, trl_line into v_pallet, v_transcode, v_line from r5translines
    where rowid = :rowid;
    select count(*) into ncounter from r5objects where obj_code = v_pallet and obj_class = 'PALLET';
    if ncounter = 1 then
    select trl_part, trl_trans, trl_line, trl_store, trl_type, trl_rtype, trl_io, trl_bin into v_pallet, v_transcode, v_line, v_store, v_trltype, v_trlrtype, v_trlio, v_binin
    from r5translines
    where trl_trans = v_transcode
    and trl_line = v_line;
    IF v_trlrtype = 'RECV' THEN
    update r5objects set obj_store = v_store where obj_code = v_pallet;
    UPDATE R5PROPERTYVALUES SET PRV_VALUE = v_store WHERE prv_code = v_pallet||'#*' AND PRV_PROPERTY = 'RMP231' AND PRV_RENTITY = 'OBJ';
    END IF;
    -- update r5parts set par_byasset = '+' where par_code = v_pallet;
    for r_palletparts in c_palletparts(v_pallet) loop
    IF v_trlrtype = 'I' then
    select count(*) into ncounter from r5stock
    where sto_part = r_palletparts.obj_part
    and sto_store = v_store
    and sto_part_org = '*';
    IF ncounter = 0 then
    INSERT INTO R5STOCK (STO_PART, STO_STORE, STO_STOCKTAKE, STO_QTY, STO_CONSIGNMENT, STO_PART_ORG, STO_PRICETYPE, STO_ONDEMAND, STO_REPAIRQTY, STO_VENDORQTY, STO_SHOPQTY, STO_REPAIRTYPE, STO_REPSTOCKMETHOD, STO_REPAUTOASSIGN, STO_LABELDEFAULT)
    VALUES (r_palletparts.obj_part, v_store, SYSDATE, 1, '-', '*', 'A', '-', 0, 0, 0, '-', '-', '-', 0);
    END IF;
    select count(*) into ncounter from r5binstock
    where bis_part = r_palletparts.obj_part
    and bis_store = v_store
    and bis_part_org = '*';
    IF ncounter = 0 then
    INSERT INTO R5BINSTOCK(BIS_PART, BIS_STORE, BIS_BIN, BIS_LOT, BIS_QTY, BIS_PART_ORG, BIS_REPAIRQTY)
    VALUES (r_palletparts.obj_part, v_store, '*', '*', 1, '*', 0);
    END IF;
    select min(bis_bin) into v_bin from r5binstock
    where bis_part = r_palletparts.obj_part
    and bis_store = v_store
    and bis_part_org = '*';
    update r5binstock set bis_qty = 1 where bis_part = r_palletparts.obj_part
    and bis_store = v_store
    and bis_bin = v_bin;
    else
    update r5objects set obj_store = v_store where obj_code = r_palletparts.obj_part;
    -- UPDATE R5PROPERTYVALUES SET PRV_VALUE = v_store WHERE prv_code = r_palletparts.obj_part||'#*' AND PRV_PROPERTY = 'RMP231' AND PRV_RENTITY = 'OBJ';
    IF r_palletparts.obj_part NOT IN ('X') THEN
    cur_message := r_palletparts.obj_part||'|'||v_trltype||'|'||v_store||'|'||ncounter;
    -- raise_application_error(-20000,cur_message);
    END IF;
    v_bin := v_binin;
    end if;
    v_line := v_line + 1;
    insert into r5translines
    (trl_trans,trl_type, trl_rtype, trl_line, trl_date,
    trl_part, trl_lot, trl_bin, trl_store, trl_price,
    trl_qty, trl_io, trl_part_org)
    values
    (v_transcode, v_trltype, v_trlrtype, v_line, sysdate,
    r_palletparts.obj_part, '*', v_bin, v_store, 0,
    1, v_trlio, '*' );
    end loop;
    end if;
    Exception
    when no_data_found then
    Null;
    end;
    Can someone please tell me how to make this key unique.
    Many Thanks
    Chris

    Hi,
    You can create rule for truncate using below:
    BEGIN
    DBMS_RULE_ADM.CREATE_RULE(
    rule_name => 'TRUNCATE_RULE',
    condition => '(:ddl.get_object_owner() = ''HR'' AND ' ||
    ':ddl.get_object_name() = ''TEST'') AND ' ||
    ':ddl.get_command_type() = ''TRUNCATE TABLE'' ');
    END;
    Thanks,
    Reena

  • Truncate, then reload causes ora-00001 unique constraint on apply side

    I setup schema level replication using the maintain_schema procedure. Its replicating DML and not DDL.
    I have a source side process that truncates a table then reloads it every day. Since DDL is not replicating, the reload produces generates an ora-00001 errors in apply process.
    I don't want to replicate all DDL because of apply errors it creates
    I've added a DDL schema rule to replicate truncate statements on the capture and apply rule, but the truncate is still not replicating. Here are the rules I'm using:
      dbms_streams_adm.add_schema_rules(
        schema_name => 'PRODUCT',
        streams_type => 'CAPTURE',
        streams_name => '&src_db$CAP',
        queue_name => 'STRMADMIN.&src_db$CAPQ',
        include_dml => TRUE,
        include_ddl => FALSE,
        include_tagged_lcr => TRUE,
        source_database => '&src_db..&gbl_nm',
        inclusion_rule => TRUE);
      DBMS_STREAMS_ADM.add_schema_rules (
        schema_name       => 'PRODUCT',
        streams_type      => 'CAPTURE',
        streams_name      => '&src_db$CAP',
        queue_name        => 'STRMADMIN.&src_db$CAPQ',
        include_dml       => FALSE,
        include_ddl       => TRUE,
        source_database   => '&src_db..&gbl_nm',
        inclusion_rule    => TRUE,
        and_condition     => '(:ddl.get_command_type() = ''TRUNCATE TABLE'')');Here's the capture rule_condition from dba_streams_rules:
    ((:dml.get_object_owner() = 'PRODUCT') and :dml.get_source_database_name() = 'PKIO.LOUDCLOUD.COM' )
    ((((:ddl.get_object_owner() = 'PRODUCT' or :ddl.get_base_table_owner() = 'PRODUCT') and :ddl.is_null_tag() = 'Y' and :ddl.get_source_database_name() = 'PKIO.LOUDCLOUD.COM' )) and ((:ddl.get_command_type() = 'TRUNCATE TABLE')))
    On the apply side I have the following
      dbms_streams_adm.add_schema_rules(
        schema_name => 'PRODUCT',
        streams_type => 'APPLY',
        streams_name => '',
        queue_name => 'STRMADMIN.&src_db$APPQ',
        include_dml => TRUE,
        include_ddl => FALSE,
        include_tagged_lcr => TRUE,
        source_database => '&src_db..&gbl_nm',
        inclusion_rule => TRUE);
      DBMS_STREAMS_ADM.add_schema_rules (
        schema_name       => 'PRODUCT',
        streams_type      => 'APPLY',
        streams_name      => '',
        queue_name        => 'STRMADMIN.&src_db$APPQ',
        include_dml       => FALSE,
        include_ddl       => TRUE,
        source_database   => '&src_db..&gbl_nm',
        inclusion_rule    => TRUE,
        and_condition     => '(:ddl.get_command_type() = ''TRUNCATE TABLE'')');And the corresponding rule_conditions look like:
    ((:dml.get_object_owner() = 'PRODUCT') and :dml.get_source_database_name() = 'PKIO.LOUDCLOUD.COM' )
    ((((:ddl.get_object_owner() = 'PRODUCT' or :ddl.get_base_table_owner() = 'PRODUCT') and :ddl.is_null_tag() = 'Y' and :ddl.get_source_database_name() = 'PKIO.LOUDCLOUD.COM' )) and ((:ddl.get_command_type() = 'TRUNCATE TABLE')))
    When the source side process that truncates and reloads the table, the apply process crashes. To workaround this I manually truncate the table on the target side and execute DBMS_APPLY_ADM.EXECUTE_ALL_ERRORS then restart apply.
    What do I need to do to replicate truncate statements with out replicating other DDL statements?
    Thanks!

    Hi,
    You can create rule for truncate using below:
    BEGIN
    DBMS_RULE_ADM.CREATE_RULE(
    rule_name => 'TRUNCATE_RULE',
    condition => '(:ddl.get_object_owner() = ''HR'' AND ' ||
    ':ddl.get_object_name() = ''TEST'') AND ' ||
    ':ddl.get_command_type() = ''TRUNCATE TABLE'' ');
    END;
    Thanks,
    Reena

  • About the Customized Ruleset and Rules

    Dear all,
    I am testing a 3 sites replication. If i use the add_schema_rules to create the capture, propagation and apply process with the auto-generated rulesets and rules, everything is OK. But now, i want to customize the propagation to achieve some of my goals. I use the DBMS_RULE_ADM.create_rule_set to create a rule set of my own, then use the DBMS_RULE_ADM.create_rule to create some rules like the following:
    DBMS_RULE_ADM.CREATE_RULE(
    rule_name => 'strmadmin.all_tab1_dml',
    condition => ' :dml.get_object_owner() = ''my'' AND ' ||
    ' :dml.get_object_name() = ''tab1'' AND ' ||
    ' :dml.is_null_tag() = ''Y'' AND ' ||
    ' :dml.get_source_database_name() = ''db1.world'' ' );
    DBMS_RULE_ADM.CREATE_RULE(
    rule_name => 'strmadmin.all_tab1_ddl',
    condition => ' (:ddl.get_object_owner() = ''my'' OR ' ||
    ' :ddl.get_base_table_owner() = ''my'') AND ' ||
    ' :ddl.get_object_name() = ''tab1'' AND ' ||
    ' :ddl.is_null_tag() = ''Y'' AND ' ||
    ' :ddl.get_source_database_name() = ''db1.world'' ');
    After creating the rules, i used the DBMS_RULE_ADM.add_rule to add these rules to the created rule_set and then assigned the rule_set to the propagation created by the DBMS_PROPAGATION_ADM.create_propagation.
    The capture and apply processes on the source and dest database are all OK. But the propagation process seemed not working. As i selected the view dba_streams_rules, i have seen that the fields streams_type, streams_name, rule_set_owner, rule_set_name, rule_owner, rule_name, rule_set_type were all right, but the others were all NULL.It was so weird.
    Can anyone give me some hints?
    Appreciated for ur help
    BR,
    bartholo
    MSN:[email protected]

    Is the propagation process aborted with errors ?
    If so can you let me know the errors.

  • Oracle stream - How to exclude constraint to downstream database

    Hi,
    I have setup Oracle downstream database capture with the below rule.
    BEGIN
    DBMS_STREAMS_ADM.ADD_SCHEMA_RULES(
    schema_name => 'PCAT_NT_QA1',
    streams_type => 'CAPTURE',
    streams_name => 'DOWNSTRMQA1_CAPTURE',
    queue_name => 'STRMADMIN.STRMQA1_QUEUE',
    include_dml => true,
    include_ddl => true,
    source_database => 'PCATQA');
    END;
    BEGIN
    DBMS_RULE_ADM.ALTER_RULE (
    rule_name => 'PCAT_NBM_QA164',
    condition => '((:ddl.get_object_owner() = ''PCAT_NBM_QA1'' or :ddl.get_base_table_owner() = ''PCAT_NBM_QA1'') and
    :ddl.is_null_tag() = ''Y'' and
                        :ddl.get_source_database_name() = ''PCATQA'' and
    :ddl.get_object_type() = ''TABLE'') ',
    evaluation_context => NULL);
    END;
    But it still try to replicate ant constraint creation to downstream database. I only want "column change" and "truncate table" should go as DDL to downstream and nothing including index,constraint,package,procedure etc.
    Regards,

    Hi,
    In my current condition as DDL statement, I only want to capture "table structure changes like adding column or modifying column" to the downstream database.
    How I can do that. Apart from DDL i am capturing all DMLs.
    Regards,

  • How to create a column based on a condition ?

    Hi all,
    I am trying to create a stored procedure that will return ID,Name and a column of type bit called  called checked based on a condition 
    please review my code and tell me what is wrong with it 
    ALTER PROCEDURE [dbo].[SelectStoresNames]
    AS
    BEGIN
    WITH locations_CTE ( ID,  Name, Checked)
    AS
    select loc.ID,loc.Name,
    (case when loc. ID in (select distinct a.StoreId
    from mPromoteStores a
    inner join mPromote b
    on a.PromoteId=b.PromoteId
    where b.promoId=144120) then 1 else 0 end as [Checked])
    FROM [dbo].[mLocations] loc where SchedulePullEnabled=1 order by  Name
    Select *
    from locations_CTE
    END

    Please post DDL, so that people do not have to guess what the keys, constraints, Declarative Referential Integrity, data types, etc. in your schema are. Learn how to follow ISO-11179 data element naming conventions and formatting rules. You have no idea!
    Temporal data should use ISO-8601 formats. Code should be in Standard SQL as much as possible and not local dialect. 
    This is minimal polite behavior on SQL forums. 
    >> I am trying to create a stored procedure that will return store_id, store_name and a column of type bit called “checked” based on a condition <<
    I fixed the vague, useless, generic data elements, made wild guesses on the DDL you did not post and got rid of the assembly language bit flags (https://www.simple-talk.com/sql/t-sql-programming/bit-of-a-problem/)
    1. IN (SELECT DISTINCT ..) is redundant
    2. aliases in alphabetic order are no help for maintaining code
    3. What is that “m” prefix? Better not be metadata...
    4. We also do not use “-cte” postfixes; tell us what the table is and not how you got it. This is another version of the “vw-” or “Volkswagen” design flaw for views.
    5. “promote” is a verb, so how can it have an identifier? Entities have identifiers. A set of  “Promotions” could have a “promo_id”, but this might be a typo ..
    6. Is “schedule_pull_enabled” another assembly language flag? I have the horrible feeling your unseen schema is not in 1NF ...
    Since you did not post DDL here is as far as I can get ..
    CREATE PROCEDURE Select_Stores_Names
    AS
    SELECT PS.store_id, PS.store_name
      FROM Promote_Stores AS PS,
                 Promotes AS P
    WHERE PS.promote_id = P.promote_id 
      AND P.promo_id = 144120  -- promo vs promote? 
      AND ???; 
    Want to follow the forum rules and try again? 
    --CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
    in Sets / Trees and Hierarchies in SQL

  • Can I use NOT IN for 2 conditions

    My first SQL Query was written as so,
    INSERT [rscalc].[Processing_Log] (Source_nm, Log_Type,[Message],Log_dt)
    SELECT '[rscalc].[usp_Validate_Generation_Map]', @Log_Type_Id, 'Source Not Found =>' + tp.Source, GETUTCDATE()
    FROM [etag].[Tag_Processed] tp
    WHERE tp.Source NOT IN 
    (SELECT bamap.Name FROM [rscalc].[BA_Area_Source_Sink_Map] bamap
    INNER JOIN [rscalc].[VER_Generation_Map] ON Area_Source_Sink_Id = bamap.Id
    INNER JOIN [etag].[Endpoint_Type_Map] emap ON emap.Id = bamap.Endpoint_Type_Id
    WHERE emap.Endpoint_Type = 'Source' or emap.Endpoint_Type = 'Source/Sink')
    I now need to include 2 conditions,
    tp.Source NOT IN and tp.Source_CA NOT IN, I came up with something along the lines of below, but I don't think this is correct?
    INSERT [rscalc].[Processing_Log] (Source_nm, Log_Type,[Message],Log_dt)
    SELECT '[rscalc].[usp_Validate_Generation_Map]', @Log_Type_Id, 'Source:' + tp.Source + ',Source_CA:' +                              
                            tp.Source_CA + '=>Not Found', GETUTCDATE()
    FROM [etag].[Tag_Processed] tp, [rscalc].[BA_Area_Source_Sink_Map] bamap
    INNER JOIN [rscalc].[BA_Areas] bareas ON bamap.BA_Area_Id = bareas.Id
    INNER JOIN [rscalc].[VER_Generation_Map] ON Area_Source_Sink_Id = bamap.Id
    INNER JOIN [etag].[Endpoint_Type_Map] emap ON emap.Id = bamap.Endpoint_Type_Id
    WHERE  
    emap.Endpoint_Type = 'Source' or 
    emap.Endpoint_Type = 'Source/Sink' AND
    tp.Source <> bamap.Name AND
    tp.Source_CA <> bareas.ETAG_source_nm
    Greg Hanson

    >> I now need to include 2 conditions,
    tp.Source NOT IN and tp.Source_CA NOT IN, I came up with something along the lines of below, but I don't think this is correct?
    Sometimes the best option is to try it :-)
    In this case the syntax is correct but we have no way to check in practice, unless you post the DDL+DML (queries to create the relevant tables and insert some sample data). In any case those not the same queries. You changed the logic of the query
    and not just add 2 conditions. Most likely the execution plan will show you differance solution.
    Can you please post DDL+DML?
      Ronen Ariely
     [Personal Site]    [Blog]    [Facebook]

  • How to show a value in column when condition is true?

    Assume I have the following simplified SELECT statement:
    SELECT a, b, ???
    FROM tab;
    In the third column a value of "yes" should appear when the following condition is true:
    tab.c = tab.d
    Otherwise the value should be "no" (or even blank).
    How can I achieve this?
    The solution should be more general for situation if many tabs are involved,....
    Peter

    How can I achieve this?
    The solution should be more general for situation if many tabs are involved,....So do you expect a generalized SQL statement that handles are arbitrary number of tables with arbitrary column names?
    It would be helpful if you provided DDL (CREATE TABLE ...) for tables involved.
    It would be helpful if you provided DML (INSERT INTO ...) for test data.
    It would be helpful if you provided expected/desired results & a detailed explanation how & why the test data gets transformed or organized.

  • Update data automatically in sql server 2005 based on condition proplem

    Hi guys i have problem I have two table
    First one is
    Second One is Vacation
    as relation one to many (vacation has foreign key of Contract No OF Table Contract) 
    what i need is to update Contract table with field status =Finish where start vacation date >end contract Date
    How i do that in sql server 2005 to make update automatically
    Ex
    contract table
    status             nvarchar(20)
    end contract    date time
    vacation table
    start vacation date time
    end vacation date time
    start vacation date is 23/10/2014
    and End
    is 26/10/2014
    Now not update status in contract table to finish because vacation date start is less from end contract
    but when date today is 27/10/2014 update contract table field status to finish
    automatically with sql server 2005 
    How i do that condition to make update to data automatically based on changing on date
    Update statement i need is 
    update Contract set status = finish where start vacation>end contract
    but problem how i write this statement to update data automatically based on date today

    Please post DDL, so that people do not have to guess what the keys, constraints, Declarative Referential Integrity, data types, etc. in your schema are. Learn how to follow ISO-11179 data element naming conventions and formatting rules. Temporal data should
    use ISO-8601 formats. You failed again. Code should be in Standard SQL as much as possible and not local dialect. 
    This is minimal polite behavior on SQL forums. Now we have to write the DDL that you did not bother with! What you did post was wrong! There is no key or constraints. There is no generic “status” in RDBMS; a "<something in particular>_status"
    is a state of being, so it needs a temporal duration. The correct idiom for this data model is: 
    CREATE TABLE Vacations
    (vacation_contract CHAR(15) NOT NULL PRIMARY KEY,
     vacation_start_date DATE NOT NULL,
     vacation_end_date DATE,
     CHECK(vacation_start_date < vacation_end_date),
    Oh, a field is nothing like a column. You need to read a basic SQL or RDBMS book; you do not know the basics. 
    --CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
    in Sets / Trees and Hierarchies in SQL

  • Oracle SQL template to create re-usable DDL/DML Scripts for Oracle database

    Hi,
    I have a requirement to put together a Oracle SQL template to create re-usable DDL/DML Scripts for Oracle databases.
    Only the Oracle DBA will be running the scripts so permissions is not an issue.
    The workflow for any DDL is as follows:-
    1) New Table
    a. Check if the table exists from the system/admin views.
    b. If table exists then give message "Table Exists"
    c. If table does not exist then execute DDL code
    2) Add Column
    a. Check if Column exists for a given table from system/admin views
    b. If column exists in the specified table,
    b1. backup table.
    b2. alter table to make changes to the column
    b3. verify data or execute dml script convert from backup to the new change.
    c. If Column does not exist
    c1. backup table
    c2. alter table to add column
    c3. execute dml to populate column with default value.
    The DML scripts are for populating base tables with data required for business operations.
    3) Add new row
    a. check if row exists by comparing old values of each column with new values to be added for the new record.
    b. If exists, give message row exists
    c. If not exists, add new record.
    4) Update existing record (We have createtime columns in these tables so changes can be tracked)
    a. check if row exists using primary key.
    b. If exists,
    b1. deactivate the record using the "active" column of the table
    b2. Add new record with the changes required.
    c. If does not exist, add new record with the changes required.
    Could you please help with some ideas which can get this done accurately?
    I have tried several ways, but I am not able to put together something that fulfills all requirements.
    Thank you,

    First let me address your question. (This is the easy part.)
    1. The existence of tables can be found in DBA_TABLES. Query it and and then use conditional logic and execute immediate to process the DDL.
    2. The existence of table columns is found in DBA_TAB_COLUMNS. Query it and then conditionally execute your DDL. You can copy the "before picture" of the table using that same dba view, or even better, use DBMS_METADATA.
    As for your DML scripts, they should be restartable, reversible, and re-run-able. They should "fail gracefully" on error, be written in such a way that they can run twice in a row without creating duplicate changes.
    3. Adding appropriate constraints can prevent invalid duplicate rows. Also, you can usually add to the where clause so that the DML does only what it needs to do without even relying on the constraint (but the constraint is there as a safeguard). Look up the MERGE statement to learn how to do an UPSERT (update/insert), which will let you conditionally "deactivate" (update) or insert a record. Anything that you cannot do in SQL can be done with simple procedural code.
    Now, to the heart of the matter...
    You think I did not understand your requirements?
    Please be respectful of people's comments. Many of us are professionals with decades of experience working with databases and Oracle technology. We volunteer our valuable time and knowledge here for free. It is extremely common for someone to post what they feel is an easy SQL or PL/SQL question without stating the real goal--the business objective. Experienced people will spot that the "wrong question" has been asked, and then cut to the chase.
    We have some good questions for you. Not questions we need answers from, but questions you need to ask yourself and your team. You need to reexamine this post and deduce what those questions are. But I'll give you some hints: Why do you need to do what you are asking? And will this construct you are asking for even solve the root cause of your problems?
    Then ponder the following quotations about asking the right question:
    Good questions outrank easy answers.
    — Paul Samuelson
    The only interesting answers are those which destroy the questions.
    — Susan Sontag
    The scientific mind does not so much provide the right answers as ask the right questions.
    — Claude Levi-Strauss
    You can tell whether a man is clever by his answers. You can tell whether a man is wise by his questions.
    — Mahfouz Naguib
    One hears only those questions for which one is able to find answers.
    — Friedrich Nietzsche
    Be patient towards all that is unresolved in your heart and try to love the questions themselves.
    — Rainer Maria Rilke
    What people think of as the moment of discovery is really the discovery of the question.
    — Jonas Salk
    Judge a man by his questions rather than his answers.
    — Voltaire
    The ability to ask the right question is more than half the battle of finding the answer.
    — Thomas J. Watson

  • Problem selecting uniqueness and last ddl from two tables

    I need to select uniqueness from user_indexes, and last_ddl_time from user_objects to determine the last ddl on all indexes within a schema.
    I have this code
    select a.object_name,a. object_type ,to_char(last_ddl_time, 'DD-MON-YYYY HH24:MI:SS'
    ) Last_Used , b.uniqueness
    from user_objects a, user_indexes b
    where object_type ='INDEX'
    and uniqueness = 'NONUNIQUE';Schema name not included beacuse i have it setup in my unix script.
    Is this correct?????

    SELECT a.object_name,
        a.object_type,
        to_char(last_ddl_time,     'DD-MON-YYYY HH24:MI:SS') last_used,
        b.uniqueness
    FROM user_objects a,
        user_indexes b
    WHERE object_type = 'INDEX'
    AND uniqueness = 'NONUNIQUE
    and a.object_name = b.index_name';  ------------------------------ missed joined condition.You are missing a join condtion..

  • Get DDL of objects in another schema without access to their content

    Hi,
    is there any object privilege which could be granted to a user A so that he can get only the user's B object definitions (DDL) but without accessing their content or executing them (in case of packages/procedures/functions)? E.g. to get the user B's tables DDL, user A should have at least the SELECT privilege on them (at least I think so), so he has access also to the table's data. To get stored procedure DDL, I don't want to give user A the ability to also run them with EXECUTE privileges, etc.
    I checked the Security Model section of DBMS_METADATA http://docs.oracle.com/cd/E11882_01/appdev.112/e25788/d_metada.htm#i1016867. The SELECT_CATALOG_ROLE role is mentioned there, which would allow me to to what I need, but it would also give a user access to all dba_* views which I don't think is ok.
    Any thoughts?
    Thanks in advance and regards,
    Jure

    If you want userA to be able to see the dictionary information for userB and no others other than him or her-self then there is another potential option. Create a sys owned view based on the Oracle user_source code that changes the filter condition to allow seeing UserB. Now if your developer is using Toad or some other tool this will likely not be suitable since the tool makes use of specific dictionary views, but for access via SQLPlus it works fine. My developers have a view that provides the same information as DBA_SOURCE but do not have access to any other dicitonary views outside the expected all_ views which work as normal.
    This may also not be practical if you want to provide access to all the views but if you actually only need a few such as tables, indexes, and _source then this is another option for you to consider.
    HTH -- Mark D Powell --

  • Sum based on group by and one condition

    I have a tableof following structure
    Group SubGroup sequence length 
    A         x               1            10
    A         X        
        2            20
    A         X               2            30
    A         X               3            50 
    B         Y               4  30
    B         Y               5            40
    I needa new column with a sum of lengths grouping Group,sub group and sequence but the condition is sum should be calculated based on the sequence of each row.Sum is sum of lengths where sequence is greater than the current row sequence number and grouping
    group nad sub group
    following is the output i am looking for
    Group SubGroup sequence length   Sum
    A         x               1            10          100(Sum of all the lengths where sesquence > current rows sequence
                                                             and group by group,sub
    group and sequnce) 
    A         X               2            20          50
    A         X   3 30 NULL
    B         Y               4  40 50
    B         Y      5 50 NULL

    Please follow basic Netiquette and post the DDL we need to answer this. Follow industry and ANSI/ISO standards in your data. You should follow ISO-11179 rules for naming data elements. You should follow ISO-8601 rules for displaying temporal data. We need
    to know the data types, keys and constraints on the table. Avoid dialect in favor of ANSI/ISO Standard SQL. 
    And you need to read and download the PDF for: 
    https://www.simple-talk.com/books/sql-books/119-sql-code-smells/
    >> I have a table of following structure <<
    Your posting is crap! Did you know that GROUP and SEQUENCE are reserved words in SQL? Did you really want to use a CREATE SEQUENCE? Did you know a table has a name and key?? That having a separate “<something>_sub_group” column is so bad a design flaw
    it has a name (attribute splitting)? That “<something>_length” cannot exist without being the length of something in particular? 
    CREATE TABLE Rude_Postings
    (rudeness_grp CHAR(2) NOT NULL
     CHECK (rudeness_grp LIKE '[A-Z][A-Z]'),
     foobar_seq INTEGER NOT NULL
     CHECK (foobar_seq > 0),
     PRIMARY KEY (rudeness_grp, foobar_seq),
     foobar_length INTEGER NOT NULL
     CHECK (foobar_length > 0)
    The foobar_seq simply looks wrong. It was not unique, so it could not be a sequence by definition. I will guess that it is unique within a rudeness_grp. 
    INSERT INTO Rude_Postings
    VALUES
    ('AX', 1, 10),
    ('AX', 2, 20),
    ('AX', 3  30),
    ('AX', 4,  50),
    ('BY', 1 , 30),
    ('BY', 2 , 40);
    >> I need a new column with a sum of lengths grouping Group,sub group and sequence but the condition is sum should be calculated based on the sequence of each row. Sum [sic: SUM is a reserved word!] is sum of lengths where sequence is greater than the
    current row [sic: tables are sets not files, so there is no ordering and no concept of a current row] sequence number and grouping group and sub group << 
    Here is my guess:
    SELECT rudeness_grp, foobar_seq, foobar_length 
       SUM( foobar_length) 
           OVER (PARTITION BY  rudeness_grp 
                   ORDER BY  foobar_seq DESC
                   ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
         AS foobar_length_running_tot
      FROM Rude_Postings;
    --CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
    in Sets / Trees and Hierarchies in SQL

  • How to Disable Syntax Checker for DDL Generation

    Would like to include shell script commands before a create table statement. Modified the .xdb but PowerDesigner does not recognize this code as it is not native to the database. Is there a way to disable the syntax check so that the create table script can include these statements rather than a number of errors? Running v15.2 of PowerDesigner. Any feedback would be appreciated!

    Hello. Yes. To be more specific, want to be able to run the create table DDL for Teradata from BTEQ. I added the following statements to a customized version of the Terada .xdb for the table BeforeCreate:
    .logon ${TD_SERVER}/${TD_USERNAME},${TD_PASSWORD}
    select 1
    from dbc.tables
    where DatabaseName =  [%QUALIFIER%]
    and TableName = '%TABLE%'
    .if errorcode > 0 then .goto error
    .if activitycount <> 1 then .goto create_tbl
    drop table %TABLE%;
    .if errorcode > 0 then .goto error
    .label create_tbl
    The DDL shows up with syntax errors as follows. So clearly, there is something that is attempting to validate the code:
    3 error(s), 0 warning(s)
    (1) (Table "DATE_DIM"):
       [syntax error] unknown macro: logon ${TD_SERVER}/${TD_USERNAME},${TD_PASSWORD}
    (8) (Table "DATE_DIM"):
       [syntax error] condition parsing error
    (16) (Table "DATE_DIM"):
       [syntax error] expecting .endif

  • Checking multiple IF conditions

    I'm working on a stored procedure and having issues.  I want to check two conditions and is none of them are met, Insert a new record. In the first 2 checks, If I find a match I will hold that value and update later in the script.  If I can't
    find a match, the 3rd step will add a new record to the location table and I will hold that value and use it to update later in the script.  Any help would be appreciated.
    IF @Is_Flag = 'N'
    BEGIN
    IF EXISTS (select * from Location where Institution_Nm = @Institution_Nm )
    BEGIN
    Set @Location_Id = (Select Location_id from Location where Institution_Nm = @Institution_Nm)
    END
    ELSE
    BEGIN
    set @Location_Id = (Select Location_Id from Research_Project_Detail Where Research_Project_Id=@Research_Project_Id and Term_Id=@Term_Id and Is_flag = 'N')
    END;
    Update Location Set State_Id=@State_Id, Country_Id=@Country_Id, Institution_Nm=@Institution_Nm,ModifiedBy=@ModifiedBy,Modified_Dt=GETDATE() Where Location_Id=@Location_Id
    END
    ELSE --CAN'T FIND ONE...INSERT NEW ONE and hold the ID
    BEGIN
    Insert into Location ( State_Id, Country_Id, Institution_Nm,CreatedBy,Created_Dt) Values (@State_Id, @Country_Id, @Institution_Nm,@ModifiedBy,GETDATE())
    set @Location_Id = Scope_Identity( )
    select Scope_Identity( ) Location_Id
    END

    >> I'm working on a stored procedure and having issues. <<
    Yes; you have no idea how to write SQL, so you write COBOL or BASIC in SQL. Your code is not declarative, but classic procedural programming. 
    You do not even know that rows are not records! This is fundamental. You are using IDENTITY because it looks like a record number on a 1950's magnetic tape. Your files had singular names because the unit of work in files is a record; in RDBMS, we use plural
    names to show that tables are sets. 
    You use flags because that is how you wrote in assembly language or COBOL. 
    But worse, you keep audit information in the same table! This is illegal. 
    >> I want to check two conditions and is none of them are met, Insert a new record [sic]. In the first 2 checks, If I find a match I will hold that value and update later in the script. <<
    No, in a declarative language; we have no local variables and no concept of later sequential execution. 
    >> If I can't find a match, the 3rd step [sic] will add a new record [sic] to the Locations table and I will hold that value and use it to update later in the script. <<
    Do you know about the SAN (Standard Address Number) used in several industries? ISO country codes, state codes are NOT ids. The old Sybase GETDATE() is now the ANSI/ISO Standard CURRENT_TIMESTAMP in T-SQL; you did an illegal act with bad code. 
    >> Any help would be appreciated. <<
    You need a major education, not just a kludge. The schema needs to be thrown out and done correctly. Without DDL, we can only guess, but I think that once you fixed the schema, the statement would be something like this skeleton: 
    MERGE INTO Locations AS L
    USING 
       (SELECT X.* 
          FROM (VALUES (@in_state_code, @in_country_code, @in_institution_name))
    AS X (state_code, country_code, institution_name)) AS N 
    ON @in_research_project_id = L.research_project_id
       AND @in_term_id = L.term_id  
    WHEN MATCHED
    THEN UPDATE
      SET state_code = N.state_code, 
          country_code = N.country_code,
          institution_name = N.institution_name
    WHEN NOT MATCHED
    THEN INSERT  state_code, country_code, institution_name
         VALUES (@in_state_code, @in_country_code, @in_institution_name);
    --CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
    in Sets / Trees and Hierarchies in SQL

Maybe you are looking for

  • Error message when re-installing itunes "Apple Mobile Device" failed to start

    I am getting an error message: "Apple Mobile Device" failed to start. Verify that you have sufficient priveleges to start system.

  • PO creation wrt PR only

    I want to make PR creation madatory for PO creation; PO shall always be created when a PR exists for it. Is there any std functionality or development is required. Thanx, Suz

  • Cannot diplay chinese properly.

    My application need to display chinese , eng and korea etc. The situation is it cannot display chinese character properly. I have a set of properties file(s) - message.properties, message_zh_TW.properties....etc So, I just want to make sure how can I

  • Parent constructor calls abstract method

    Hi everybody! I'm wondering if there is something wrong with java or if the idea is just too ill? Anyway, I think it would be great if this hierachy would work... Two classes A and B. Class A defines an astract method. In A's constructor this abstrac

  • CPU usage 100%  when WLS 10.3.3 is idle on OS X 10.6.4 (Snow Leopard)

    I've installed WLS 10.3.3 on OS X 10.6.4 and executed using the instructions in the README (including setting the MEM_ARGS). Upon startup, the CPU usage spikes to ( then stays ) around *104%* ( dual-core CPU ); this, of course cripples the computer t