skip to main | skip to sidebar

SQL Tutorial with Examples

Pages

  • Home
 
  • RSS
  • Facebook
  • Twitter
Wednesday, October 24, 2012

Comparing data (rows)in two tables in PL/SQL

Posted by Raju Gupta at 12:06 PM – 3 comments
 

Pl/sql code have Cursors that will fetch table and columns that you want to compare and it will Iterate through all tables in the local database that match the specified table criteria.This Pl/Sql will Compare the data in this table only if it contains at least one column whose data type is supported by this script.If there is a discrepency between the data in the local table and the remote table,it will give a count of rows missing from each and Next give the user a query they could run to see all of the differing data between the two tables.


DECLARE
  CURSOR c_tables IS
    SELECT   table_name
    FROM     user_tables
    WHERE    table_name=<table name>
    ORDER BY table_name;
  CURSOR c_columns (cp_table_name IN VARCHAR2) IS
    SELECT   table_name,column_name, data_type
    FROM     user_tab_columns
    WHERE    table_name = cp_table_name
    ORDER BY column_id;
  TYPE t_char80array IS TABLE OF VARCHAR2(80) INDEX BY BINARY_INTEGER;
  v_column_list     VARCHAR2(32767);
  v_total_columns   INTEGER;
  v_skipped_columns INTEGER;
  v_count1          INTEGER;
  v_count2          INTEGER;
  v_rows_fetched    INTEGER;
  v_column_pieces   t_char80array;
  v_piece_count     INTEGER;
  v_pos             INTEGER;
  v_length          INTEGER;
  v_next_break      INTEGER;
  v_same_count      INTEGER := 0;
  v_diff_count      INTEGER := 0;
  v_error_count     INTEGER := 0;
  v_warning_count   INTEGER := 0;
  --
  --
  v_cursor          INTEGER := dbms_sql.open_cursor;
  --
BEGIN
  --
  -- Iterate through all tables in the local database that match the
  -- specified table criteria.
  --
  FOR r1 IN c_tables LOOP
    --
    -- Build a list of columns that we will compare (those columns
    -- that match the specified column criteria). We will skip columns
    -- that are of a data type not supported (LOBs and LONGs).
    --
    v_column_list := NULL;
    v_total_columns := 0;
    v_skipped_columns := 0;
    FOR r2 IN c_columns (r1.table_name) LOOP
      v_total_columns := v_total_columns + 1;
      IF r2.data_type IN ('BLOB', 'CLOB', 'NCLOB', 'LONG', 'LONG RAW') THEN
        --
        -- The column's data type is one not supported by this script (a LOB
        -- or a LONG). We'll enclose the column name in comment delimiters in
        -- the column list so that the column is not used in the query.
        --
        v_skipped_columns := v_skipped_columns + 1;
        IF v_column_list LIKE '%,' THEN
          v_column_list := RTRIM (v_column_list, ',') || 
                           ' /*, "' || r2.column_name || '" */,';
        ELSE
          v_column_list := v_column_list || ' /* "' || r2.column_name ||'" */ ';
        END IF;
      ELSE
        --
        -- The column's data type is supported by this script. Add the column
        -- name to the column list for use in the data comparison query.
        --
        v_column_list := v_column_list || '"' || r2.column_name || '",';
      END IF;
    END LOOP;
    --
    -- Compare the data in this table only if it contains at least one column
    -- whose data type is supported by this script.
    --
    IF v_total_columns > v_skipped_columns THEN 
      --
      -- Trim off the last comma from the column list.
      --
      v_column_list := RTRIM (v_column_list, ',');
      BEGIN
        --
        -- Get a count of rows in the local table missing from the remote table.
        --
        dbms_sql.parse 
        (
        v_cursor,
        'SELECT COUNT(*) FROM (' ||
        'SELECT ' || v_column_list || ' FROM "' || r1.table_name || '"' ||
        ' MINUS ' ||
        'SELECT ' || v_column_list || ' FROM "' || r1.table_name ||'"@ADE2.WORLD)',
        dbms_sql.native
        );
        dbms_sql.define_column (v_cursor, 1, v_count1);
        v_rows_fetched := dbms_sql.execute_and_fetch (v_cursor);
        IF v_rows_fetched = 0 THEN
          RAISE NO_DATA_FOUND;
        END IF;
        dbms_sql.column_value (v_cursor, 1, v_count1);
        --
        -- Get a count of rows in the remote table missing from the local table.
        --
        dbms_sql.parse 
        (
        v_cursor,
        'SELECT COUNT(*) FROM (' ||
        'SELECT ' || v_column_list || ' FROM "' || r1.table_name ||'"@ADE2.WORLD'||
        ' MINUS ' ||
        'SELECT ' || v_column_list || ' FROM "' || r1.table_name || '")',
        dbms_sql.native
        );
        dbms_sql.define_column (v_cursor, 1, v_count2);
        v_rows_fetched := dbms_sql.execute_and_fetch (v_cursor);
        IF v_rows_fetched = 0 THEN
          RAISE NO_DATA_FOUND;
        END IF;
        dbms_sql.column_value (v_cursor, 1, v_count2);
        --
        -- Display our findings.
        --
        IF v_count1 = 0 AND v_count2 = 0 THEN
          --
          -- No data discrepencies were found. Report the good news.
          --
          dbms_output.put_line 
          (
          r1.table_name || ' - Local and remote table contain the same data'
          );
          v_same_count := v_same_count + 1;
          IF v_skipped_columns = 1 THEN
            dbms_output.put_line
            (
            r1.table_name || ' - Warning: 1 LOB or LONG column was omitted ' ||
            'from the comparison'
            );
            v_warning_count := v_warning_count + 1;
          ELSIF v_skipped_columns > 1 THEN
            dbms_output.put_line
            (
            r1.table_name || ' - Warning: ' || TO_CHAR (v_skipped_columns) ||
            ' LOB or LONG columns were omitted from the comparison'
            );
            v_warning_count := v_warning_count + 1;
          END IF;
        ELSE
          --
          -- There is a discrepency between the data in the local table and
          -- the remote table. First, give a count of rows missing from each.
          --
          IF v_count1 > 0 THEN
            dbms_output.put_line 
            (
            r1.table_name || ' - ' ||
            LTRIM (TO_CHAR (v_count1, '999,999,990')) ||
            ' rows on local database missing from remote'
            );
          END IF;
          IF v_count2 > 0 THEN
            dbms_output.put_line 
            (
            r1.table_name || ' - ' ||
            LTRIM (TO_CHAR (v_count2, '999,999,990')) ||
            ' rows on remote database missing from local'
            );
          END IF;
          IF v_skipped_columns = 1 THEN
            dbms_output.put_line
            (
            r1.table_name || ' - Warning: 1 LOB or LONG column was omitted ' ||
            'from the comparison'
            );
            v_warning_count := v_warning_count + 1;
          ELSIF v_skipped_columns > 1 THEN
            dbms_output.put_line
            (
            r1.table_name || ' - Warning: ' || TO_CHAR (v_skipped_columns) ||
            ' LOB or LONG columns were omitted from the comparison'
            );
            v_warning_count := v_warning_count + 1;
          END IF;
          --
          -- Next give the user a query they could run to see all of the
          -- differing data between the two tables. To prepare the query,
          -- first we'll break the list of columns in the table into smaller
          -- chunks, each short enough to fit on one line of a telnet window
          -- without wrapping.
          --
          v_pos := 1;
          v_piece_count := 0;
          v_length := LENGTH (v_column_list);
          LOOP
            EXIT WHEN v_pos = v_length;
            v_piece_count := v_piece_count + 1;
            IF v_length - v_pos < 72 THEN
              v_column_pieces(v_piece_count) := SUBSTR (v_column_list, v_pos);
              v_pos := v_length;
            ELSE
              v_next_break := 
                GREATEST (INSTR (SUBSTR (v_column_list, 1, v_pos + 72),
                                 ',"', -1),
                          INSTR (SUBSTR (v_column_list, 1, v_pos + 72),
                                 ',/* "', -1),
                          INSTR (SUBSTR (v_column_list, 1, v_pos + 72),
                                 ' /* "', -1));
              v_column_pieces(v_piece_count) := 
                SUBSTR (v_column_list, v_pos, v_next_break - v_pos + 1);
              v_pos := v_next_break + 1;
            END IF;
          END LOOP;
          dbms_output.put_line ('Use the following query to view the data ' ||
                                'discrepencies:');
          dbms_output.put_line ('(');
          dbms_output.put_line ('SELECT ''Local'' "LOCATION",');
          FOR i IN 1..v_piece_count LOOP
            dbms_output.put_line (v_column_pieces(i));
          END LOOP;
          dbms_output.put_line ('FROM "' || r1.table_name || '"');
          dbms_output.put_line ('MINUS');
          dbms_output.put_line ('SELECT ''Local'' "LOCATION",');
          FOR i IN 1..v_piece_count LOOP
            dbms_output.put_line (v_column_pieces(i));
          END LOOP;
          dbms_output.put_line ('FROM "' || r1.table_name || '"@ADE2.WORLD');
          dbms_output.put_line (') UNION ALL (');
          dbms_output.put_line ('SELECT ''Remote'' "LOCATION",');
          FOR i IN 1..v_piece_count LOOP
            dbms_output.put_line (v_column_pieces(i));
          END LOOP;
          dbms_output.put_line ('FROM "' || r1.table_name || '"@ADE2.WORLD');
          dbms_output.put_line ('MINUS');
          dbms_output.put_line ('SELECT ''Remote'' "LOCATION",');
          FOR i IN 1..v_piece_count LOOP
            dbms_output.put_line (v_column_pieces(i));
          END LOOP;
          dbms_output.put_line ('FROM "' || r1.table_name || '"');
          dbms_output.put_line (');');
          v_diff_count := v_diff_count + 1;
        END IF;
      EXCEPTION
        WHEN OTHERS THEN
          --
          -- An error occurred while processing this table. (Most likely it 
          -- doesn't exist or has fewer columns on the remote database.)
          -- Show the error we encountered on the report.
          --
          dbms_output.put_line (r1.table_name || ' - ' || SQLERRM);
          v_error_count := v_error_count + 1;
      END;
    END IF;
  END LOOP;
  --
  -- Print summary information.
  --
  dbms_output.put_line ('-------------------------------------------------');
  dbms_output.put_line 
  (
  'Tables examined: ' || TO_CHAR (v_same_count + v_diff_count + v_error_count)
  );
  dbms_output.put_line 
  (
  'Tables with data discrepencies: ' || TO_CHAR (v_diff_count)
  );
  IF v_warning_count > 0 THEN
    dbms_output.put_line 
    (
    'Tables with warnings: ' || TO_CHAR(v_warning_count)
    );
  END IF;
  IF v_error_count > 0 THEN
    dbms_output.put_line 
    (
    'Tables that could not be checked due to errors: ' || TO_CHAR(v_error_count)
    );
  END IF;
  dbms_sql.close_cursor (v_cursor);
END;

[ Read More ]
Read more...
Tuesday, October 23, 2012

Serial Number Related Query

Posted by Raju Gupta at 11:41 AM – 0 comments
 
This query will let us know the corresponding Sales Order number associated with a given serial number installed in Installed Base.

-- get sales order associated with serial number
SELECT msn.serial_number,
  ool.line_id,
          ooh.order_number,
         ool.inventory_item_id
FROM     mtl_serial_numbers      msn,
          oe_order_lines_all      ool,
          oe_order_headers_all    ooh,
          mtl_system_items        msi,
          wip_discrete_jobs       wdj,
          wip_entities            we
WHERE    msn.serial_number = '&Serial_Number'
AND       ool.header_id = ooh.header_id
AND       wdj.source_line_id = ool.line_id
AND       we.wip_entity_id = wdj.wip_entity_id
AND       wdj.wip_entity_id = msn.original_wip_entity_id
AND       msi.inventory_item_id = msn.inventory_item_id
AND       msi.organization_id = ool.ship_from_org_id
AND       msn.current_status = 4
UNION
SELECT   wdd.serial_number,
          ool.line_id,
          ooh.order_number,
          ool.inventory_item_id
FROM     wsh_delivery_details    wdd,
          oe_order_lines_all      ool,
          oe_order_headers_all    ooh
WHERE    wdd.serial_number = '&Serial_Number'
AND       ool.header_id = ooh.header_id
AND       wdd.source_line_id = ool.line_id
AND       wdd.serial_number IS NOT NULL


[ Read More ]
Read more...

SQL tips

Posted by Raju Gupta at 12:00 AM – 0 comments
 

Re-usable SQL Queries useful in day-to-day scenario.

COMMON QUERIES
***************

SELECT instance_name FROM v$instance;

Find the locked_objects
-----------------------
SELECT object_name FROM all_objects
WHERE object_id in(SELECT object_id FROM v$locked_object);
SELECT object_name, object_id FROM 
all_objects a WHERE exists (SELECT 1 FROM v$locked_object b WHERE
a.object_id = b.object_id);

Find the nls_parameters values
--------------------------------
SELECT * FROM v$nls_parameters;

Find the valid nls_parameter values
------------------------------------
SELECT * FROM v$nls_valid_values ;

Check the parameter settings for optimizer
-------------------------------------------
SELECT * FROM v$parameter WHERE
lower(name) like '%optimizer%'

Enable parallel dml
-------------------
ALTER session enable parallel dml;

Check for table creation details
---------------------------------
SELECT
owner,object_name,object_type,CREATEd,last_ddl_time
FROM all_objects WHERE object_name =
upper('<table_name>');

Find the time remaining for a query. (Also to check if it is running properly)
------------------------------------------------------------------------------
SELECT
sid,time_remaining,elapsed_seconds,message
FROM v$session_longops WHERE sid in
(SELECT sid FROM v$session a,v$sqltext b
WHERE a.sql_address = b.address
and username = 'bdm'
and upper(sql_text) like 'CREATE
table%'
and a.status = 'active' )
and time_remaining!=0
ORDER BY sid
Find numrows
------------
SELECT table_name , num_rows FROM
all_tables WHERE  table_name = '&table_name';
Find the dependencies
------------------------
SELECT name , type , dependency_type
FROM all_dependencies;

Find data dictionary tables available
--------------------------------------
SELECT table_name FROM dict ORDER BY 1;
Find object type
-----------------
SELECT object_name , object_type FROM
all_objects WHERE object_name = upper('&object_name');

For analyzing tables
--------------------
ANALYZE TABLE &table_name COMPUTE
STATISTICS;

Find last_analyzed details
--------------------------
SELECT last_analyzed FROM user_tables
WHERE table_name = upper('&table_name');
SELECT last_analyzed FROM user_indexes
WHERE table_name = upper('&table_name');

Gather table stats
-------------------
exec
dbms_stats.delete_table_stats('&owner','&table_name');
exec
dbms_stats.gather_table_stats('&owner','&table_name',null,4,false,'for
all indexed columns size 50', 5,'default',true,null,null,null);
exec
dbms_stats.gather_table_stats(ownname=>user,
tabname=>‘table_name‘, estimate_percent=>5,
method_opt=>'for all indexed columns size 50', cascade=>true);

(5 is a good starter.If you have a really huge table (>10million rows), you may want to do just 1% as 5% will take a long time OR If you have a really small table (<10k rows), you may want to do 99%)

Example Table_Name is csban_1
exec
dbms_stats.gather_table_stats(ownname=>'bdm',tabname=>'csban_1',estimate_percent=>5,method_opt=>'for
all indexed columns size 50',cascade=>true);

Delete table stats
------------------
exec 
dbms_stats.delete_table_stats(user,'&table_name');
exec 
dbms_stats.delete_table_stats(user,'agent_list_id_temp');

Unlock table stats
-------------------
exec
dbms_stats.unlock_table_stats(ownname=>'cusp272',tabname=>'crtsb562v');


DB LINKS
*********

Creating private database link
-------------------------------
CREATE database link <link_name>
CONNECT TO <schema> 
USING <database>;

Droping private database link
------------------------------
DROP database link <link_name>;

Find the db_links
-------------------
DESC all_db_links

SET lines 132 pages 66
COL owner    FOR a15
COL db_link  FOR a15
COL username FOR a15
COL host     FOR a15

SELECT owner,Db_link,username,host
FROM all_db_links 
WHERE db_link like  upper('%&link_name%');

get passwords for the user database links
------------------------------------------
SET lines 132 pages 66
COL db_link  FOR a15
COL username FOR a15
COL host     FOR a15
SELECT  db_link,username,password,host
FROM user_db_links 
WHERE db_link like  upper('%&link_name%');
 
INDEX
******

Find index details
------------------
DESC all_indexes
DESC all_ind_columns

Get index details from the server
---------------------------------
COL tb_name FOR a20
COL tb_sp FOR a20
COL ind_name FOR a25
COL col_name FOR a20
COL col_pos FOR 99
break on tb_name skip 0 on tb_sp skip 0 on ind_name skip 2 on col_name skip 0
SET lines 132 pages 66 
SELECT a.table_name tb_name,
       a.tablespace_name tb_sp,
       a.index_name  ind_name, 
       index_type ind_typ,
       column_name col_name , 
       column_position col_pos
FROM all_indexes a, all_ind_columns b
WHERE a.table_name = b.table_name
  and a.index_name = b.index_name
  and a.table_name = upper('&table_name')
ORDER BY a.index_name,column_position;
Get index details from remote server
------------------------------------
col tb_name for a20
col tb_sp for a20
col ind_name for a25
col col_name for a20
col col_pos for 99
break on tb_name skip 0 on tb_sp skip 0 on ind_name skip 2 on col_name skip 0
set lines 132 pages 66 
SELECT a.table_name tb_name,
       a.tablespace_name tb_sp, 
       a.index_name  ind_name, 
         index_type  ind_typ,
       column_name   col_name , 
       column_position col_pos
  FROM all_indexes@ a, all_ind_columns@ b
 WHERE a.table_name = b.table_name
   and a.index_name = b.index_name
   and a.table_name = upper('&table_name')
ORDER BY a.index_name,column_position;
Build index
------------
exec index_builder.build('bdm','&table_name','pdm');

Nuke index
----------
exec index_builder.nuke('bdm','&table_name','pdm');


Change the tablespace for a given index for a partitioned table
----------------------------------------------------------------
Example:
table name : prod_rev_fact
index name : prdrev_prdcddim_idx
columns : product_code_dim_id

partitions : tablespace name
-----------------------------
p200401 : prdrevfct200401
p200412 : prdrevfct200401
p200512 : prdrevfct200401
p200606 : prod_rev_fact_ts

Step 1: Drop the index using the command.
------
DROP INDEX prdrev_prdcddim_idx;
Step 2:
-------
CREATE INDEX prdrev_prdcddim_idx ON prod_rev_fact
(product_code_dim_id)
  initrans   2
  maxtrans   255
  nologging
local (  
  partition p200401
    nologging
    tablespace prdrevfct200401
    pctfree    10
    initrans   2
    maxtrans   255
    storage    (
                initial          5m
                next             5m
                minextents       1
                maxextents       2147483645
                pctincrease      0
                freelists        1
                freelist groups  1
                buffer_pool      default
               ),  
  partition p200412
    nologging
    tablespace prdrevfct200401
    pctfree    10
    initrans   2
    maxtrans   255
    storage    (
                initial          5m
                next             5m
                minextents       1
                maxextents       2147483645
                pctincrease      0
                freelists        1
                freelist groups  1
                buffer_pool      default
               ),
  partition p200512
    nologging
    tablespace prdrevfct200401
    pctfree    10
    initrans   2
    maxtrans   255
    storage    (
                initial          5m
                next             5m
                minextents       1
                maxextents       2147483645
                pctincrease      0
                freelists        1
                freelist groups  1
                buffer_pool      default
               ),
  partition p200606
    nologging
    tablespace prod_rev_fact_ts
    pctfree    10
    initrans   2
    maxtrans   255
    storage    (
                initial          5m
                next             5m
                minextents       1
                maxextents       2147483645
                pctincrease      0
                freelists        1
                freelist groups  1
                buffer_pool      default
               )
)
parallel ( degree 3 instances 1 );
Move an index to another tablespace
-------------------------------------
ALTER index  rebuild tablespace ;
Coalesce indexes
--------------------
ALTER index  coalesce;

Checking indexes and their validity
-----------------------------------
analyze index  validate structure;
Monitor the usage of the index ( start/stop).
-------------------------------------------------
Start
-----
ALTER index  monitoring usage;

Stop
----
ALTER index  nomonitoring usage;


Rename the index
---------------------
ALTER index  rename to  ;


TABLESPACE
***********

Find table spaces
------------------
DESC all_tables

SET lines 132 pages 66 newp 0
COL owner FOR a20
COL tb_sp FOR a20

SELECT owner,table_name tb_name,tablespace_name tb_sp
FROM all_tables 
WHERE  table_name = upper('&table_name');

SELECT segment_name, segment_type, CREATEd, bytes 
FROM all_objects o, dba_segments s 
WHERE o.object_name=s.segment_name and o.object_type=s.segment_type 
AND tablespace_name=upper('&table_name')
ORDER BY CREATEd DESC,bytes;


Find Free Space:
---------------
SELECT tablespace_name, sum(bytes) 
FROM dba_free_space having sum(bytes) in 
(SELECT max(sum(bytes)) FROM dba_free_space group by tablespace_name)
group by tablespace_name
ORDER BY 2;

SELECT tablespace_name, sum(bytes)
FROM dba_free_space group by tablespace_name 
ORDER BY 2 asc;

Actual space occupied by the table
-----------------------------------
COL segment_name FOR a25
COL partition_name FOR a20
COL segment_type FOR a15
COL space_mb FOR 99999
COL blocks FOR 999999
break on segment_name skip 0 on segment_type skip 0
compute sum of mb on segment_name
compute sum of blocks on segment_name

SELECT segment_name,segment_type,partition_name,bytes/1024/1024  mb,blocks
FROM user_segments
WHERE segment_name = upper('&table_name');

Actual space occupied by the data.
--------------------------------
SELECT table_name,(num_rows*avg_row_len)/(1024*1024) mb FROM user_tables WHERE table_name=upper('&table_name');

Move a table to another tablespace
----------------------------------
ALTER table  move tablespace ;

Move partitions of a partitioned table to a different tablespace_name
----------------------------------------------------------------------
ALTER table  move partition  tablepsace  nologging;

PARTITIONS
***********

Find partitions of a given table along with partition_name
-----------------------------------------------------------
DESC all_tab_partitions

SET lines 132 pages 66
COL owner      FOR a8
COL tbl_name   FOR a20
COL part_name  FOR a20
COL part_pos   FOR 99
COL part_col   FOR a15
COL num_rows  FOR 999999999
break on owner skip 0 on tbl_name skip 0 on part_col skip 0 on part_name skip 0 on report skip 0
SELECT table_owner         owner , 
       table_name          tbl_name,
       column_name         part_col,
       partition_name      part_name,
       partition_position  part_pos,
       num_rows            num_rows
  FROM all_tab_partitions,
       all_part_key_columns
 WHERE table_name = name(+)
   AND table_name =  upper('&table_name')
ORDER BY 1,2,3,4,5,6;

DESC all_ind_partitions

SELECT partition_name 
FROM all_ind_partitions
WHERE table_name = upper('&table_name');

Find a partition_name for a given table
---------------------------------------
SET lines 132  pages 66
COL owner FOR a10
COL tbl_name  FOR a10

SELECT * 
FROM all_part_key_columns
WHERE name = upper('&table_name');

ADD/TRUNC/DEL partition in a given table
-----------------------------------------
ALTER table &table_name ADD PARTITION p200606 values less than (200607);

ALTER table &table_name TRUNCATE p200606 values less than (200607);

ALTER table &table_name DROP p200606 values less than (200607);

Exchange partition (get data from a non-partitioned table into partitioned table partition)
------------------------------------------------------------------------------------------
ALTER table  exchange partition p200609 with table  with validation;

Split the partition
-------------------

eg: splits p200701 into p200701 and 200612
ALTER table   split partition p200701 at ('200701') into ( partition p200612 , partition p200701)     ;
ALTER table   split partition p200612 at ('200612') into ( partition p200611 , partition p200612)     ;
   
Get count from a partitioned table
----------------------------------
SELECT /*+ parallel(a,8) */ count(1) FROM  partition(p200608) a;

SYNONYMS
*********


DESC all_synonyms
-----------------

FROM local server
------------------
COL owner    FOR a10
COL syn_name FOR a20
COL tbl_own  FOR a15
COL tbl_name FOR a20
COL db_link  FOR a15
break on owner skip 0 on syn_name skip 0 on tbl_own skip 0 on tbl_name skip 0 on db_link skip 0

SELECT owner, synonym_name syn_name, table_owner tbl_own, table_name tbl_name, db_link
FROM all_synonyms
WHERE synonym_name = upper('&synonym_name');

FROM remote server
------------------
COL owner    FOR a10
COL syn_name FOR a20
COL tbl_own  FOR a15
COL tbl_name FOR a20
COL db_link  FOR a15
break on owner skip 0 on syn_name skip 0 on tbl_own skip 0 on tbl_name skip 0 on db_link skip 0

SELECT owner, synonym_name syn_name, table_owner tbl_own, table_name tbl_name, db_link  
FROM all_synonyms@crdmprd
WHERE synonym_name = upper('&synonym_name');


VIEWS
*****

Get view details
----------------
SET long 3000
SET lines 132 pages 66

SELECT owner , view_name , text
FROM all_views
WHERE view_name =  upper('&vw_name');


CONSTRAINTS
************


Get information on constraints of a given table
------------------------------------------------
(including foreign (referred) table/column information, a query like this may be used)

SET lines 132 pages 66
COLUMN consname FORMAT a15;
COLUMN colname FORMAT a12;
COLUMN type FORMAT a14;
COLUMN cond FORMAT a25;
COLUMN ref_tabname FORMAT a14;
COLUMN ref_colname FORMAT a14;

SELECT
  uc.constraint_name consname,
  ucc.column_name colname,
  case
    when uc.constraint_type='c' then 'check'
    when uc.constraint_type='p' then 'primary key'
    when uc.constraint_type='r' then 'referential'
    when uc.constraint_type='u' then 'unique'
    else uc.constraint_type
  end as type,
  uc.search_condition cond,
  ucc_r.table_name ref_tabname,
  ucc_r.column_name ref_colname
FROM
  user_constraints uc
  JOIN
  user_cons_columns ucc on
    uc.constraint_name=ucc.constraint_name and
    uc.owner=ucc.owner
  LEFT JOIN
  user_constraints uc_r on
    uc.r_constraint_name=uc_r.constraint_name and
    uc.owner=uc_r.owner
  LEFT JOIN
  user_cons_columns ucc_r on
    uc_r.constraint_name=ucc_r.constraint_name and
    uc_r.owner=ucc_r.owner
WHERE
  uc.table_name = upper('&tablename')
ORDER BY consname,colname;


COL owner      FOR a10
COL tbl        FOR a12
COL name       FOR a23
COL typ        FOR a1
COL col_name   FOR a10
COL c_pos      FOR 99
COL src_cond   FOR a10
COL r_owner    FOR a10
COL r_cons     FOR a20
SET lines 132 pages 66

SELECT a.owner owner,
       a.table_name tbl, 
       a.constraint_name name, 
       a.constraint_type typ,
       b.column_name  col_name,
       b.position   c_pos,
       a.status     status,
       a.search_condition src_cond,
       a.r_owner r_owner,
       a.r_constraint_name r_cons
  FROM all_constraints a,
       all_cons_columns b
 WHERE a.constraint_name = b.constraint_name
   and a.constraint_name = upper('&constraint_name');



PRIVILEGES
***********
Get the privileges granted on objects (all_tab_privs)
------------------------------------------------------
SET lines 132 pages 66
COL grantor      FOR a15
COL grantee      FOR a15
COL table_schema FOR a8
COL table_name   FOR a15
COL privilege    FOR a8
COL grantable    FOR a3
COL hierarchy    FOR a3
break on grantor skip 0 on grantee skip 0 on table_schema skip 0 on table_name skip 0 on privilege skip 0 

SELECT grantor,grantee,table_schema,table_name,privilege,grantable,hierarchy
FROM all_tab_privs 
WHERE table_name = '&table_name'
ORDER BY grantor,grantee,table_schema,table_schema,table_name,privilege;

Find user_sys_privs
--------------------
SELECT distinct grantable  FROM all_tab_privs ;

Find privileges given on different tables
------------------------------------------
DESC all_tab_privs
SELECT distinct privilege FROM all_tab_privs ;

SELECT distinct grantable FROM all_tab_privs ;

Grant/Revoke privileges:
------------------------
GRANT select, insert, update, delete ON <object> TO <user>;

REVOKE privileges ON <object> FROM <user>;




2nd max salary

Description
This tool is used to to select the 2nd max salary from a table.
select  B.ecm_code,b.rec from(                 select A.ecm_code,rownum rec from (
                              select ECM_CODE,rownum from T_ECM
                              order by ecm_code desc
            )A
       where rownum<3 data-blogger-escaped-pre="pre" data-blogger-escaped-rec="2" data-blogger-escaped-where="where">
[ Read More ]
Read more...
Monday, October 22, 2012

Advance SQL

Posted by Raju Gupta at 11:33 AM – 0 comments
 

The query that uses partition OVER PARTITION BY analytic function

The below example shows the cumulative salary within a departement row by row, with each row including a summation of the prior rows salary.

SELECT ename "Ename", deptno "Deptno", sal "Sal",
  SUM(sal)
    OVER (ORDER BY deptno, ename) "Running Total",
  SUM(SAL)
    OVER (PARTITION BY deptno
          ORDER BY ename) "Dept Total",
  ROW_NUMBER()
    OVER (PARTITION BY deptno
          ORDER BY ENAME) "Seq"
FROM emp
ORDER BY deptno, ename


Result:
-------

Ename Deptno Sal Running Total Dept Total Seq
------ ------ ------ ------------- ---------- ----
CLARK 10 2450 2450 2450 1
KING 5000 7450 7450 2
MILLER 1300 8750 8750 3

ADAMS 20 1100 9850 1100 1
FORD 3000 12850 4100 2
JONES 2975 15825 7075 3
SCOTT 3000 18825 10075 4
SMITH 800 19625 10875 5

ALLEN 30 1600 21225 1600 1
BLAKE 2850 24075 4450 2
JAMES 950 25025 5400 3
MARTIN 1250 26275 6650 4
TURNER 1500 27775 8150 5
WARD 1250 29025 9400 6

Execution Plan
---------------------------------------------------
0 SELECT STATEMENT Optimizer=CHOOSE
1 0 WINDOW (SORT)
2 1 TABLE ACCESS (FULL) OF 'EMP'
Statistics
---------------------------------------------------
0 recursive calls
0 db block gets
3 consistent gets
0 physical reads
0 redo size
1658 bytes sent via SQL*Net to client
503 bytes received via SQL*Net from client
2 SQL*Net roundtrips to/from client
1 sorts (memory)
0 sorts (disk)
14 rows processed

The example shows how to calculate a "Running Total" for the entire query. This is done using the entire ordered result set, via SUM(sal) OVER (ORDER BY deptno, ename).

Further, we were able to compute a running total within each department, a total that would be reset at the beginning of the next department. The PARTITION BY deptno in that SUM(sal) caused this to happen, a partitioning clause was specified in the query in order to break the data up into groups.

The ROW_NUMBER() function is used to sequentially number the rows returned in each group, according to our ordering criteria (a "Seq" column was added to in order to display this position).

The execution plan shows, that the whole query is very well performed with only 3 consistent gets, this can never be accomplished with standard SQL or even PL/SQL.

[ Read More ]
Read more...

Query to search Special character in word

Posted by Raju Gupta at 12:00 AM – 0 comments
 

The query looks for any special characters in column field (specially useful for password field) and reports it.  

SELECT DISTINCT employee,PASSWORD 
FROM
(SELECT employee,LENGTH(TRIM(TRANSLATE(password, 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', ' '))) KEY,PASSWORD 
FROM table_name) 
WHERE KEY IS NOT NULL


[ Read More ]
Read more...
Sunday, October 21, 2012

Multi User session Kill in Oracle

Posted by Raju Gupta at 11:31 AM – 1 comments
 

To kill the inactive users login in Oracle from any schema in a database.If any unwanted transactions were kept withput roll back it will block the buffer memory, then it leads to database block.Using this query we can find out the User and the machine number, so that we can kill the bolcking transaction.   

SELECT   SYS.v_$lock.SID, machine, program, object_name, logon_time, osuser
    FROM SYS.v_$lock, SYS.v_$session, all_objects
   WHERE SYS.v_$lock.SID = SYS.v_$session.SID
     AND SYS.v_$lock.id1 = all_objects.object_id
     AND SYS.v_$lock.TYPE = 'TM'
ORDER BY SYS.v_$lock.SID, machine, program

[ Read More ]
Read more...
Monday, October 15, 2012

TABLE FINDER

Posted by Raju Gupta at 12:30 PM – 0 comments
 
Table_Finder is a procedure to find all the tables that are queried in a particular package or procedure. It takes Package name or procedure name as input parameter. Final output will be the list of table names that are queried by that package along with the table?s owner name. It finds the table names involved in all schemas. This developed procedure will be useful to all development and enhancement projects as it is gives output without consuming time.

CREATE OR REPLACE PROCEDURE table_finder(pkg_name IN VARCHAR) AS
CURSOR Test IS
 SELECT owner,referenced_name,object_type FROM user_dependencies ud,all_objects ao,user_synonyms us
  WHERE ud.name=pkg_name
  AND ud.referenced_type IN ( 'TABLE','SYNONYM')
  AND ud.referenced_owner NOT IN ('SYS','PUBLIC')
  AND ud.referenced_name=ao.object_name
  AND ud.referenced_name=us.synonym_name(+)
  AND ao.object_type LIKE'TABLE';
   
     BEGIN
           for rec in test
               loop
                      dbms_output.put_line(rec.owner);
                      dbms_output.put_line(rec.referenced_name);
                      dbms_output.put_line(rec.object_type);
               end loop;
      END;

[ Read More ]
Read more...

Oracle PL/SQL Query for Pagination

Posted by Raju Gupta at 12:33 AM – 1 comments
 
Oracle PL/SQL function makes the input query statement such a way that the query out put returns for a start row index to end row index.
CREATE OR REPLACE FUNCTION pagination_stmt_fn 
 (
  i_query_statement   IN   VARCHAR2,
  i_start_index       IN   NUMBER,
  i_end_index         IN   NUMBER
 )
 RETURN VARCHAR2
 IS
 o_query_statement   VARCHAR2 (32000);
 v_start_index       NUMBER           := 0;
 v_end_index         NUMBER           := 0;
BEGIN
 IF i_start_index = 0
 THEN
  v_start_index := 1;
 ELSE
  v_start_index := i_start_index;
 END IF;

 IF i_end_index = 0
 THEN
  v_end_index := 10000000;
 ELSE
  v_end_index := i_end_index;
 END IF;

 o_query_statement :=
  ' select  * from (  '
    || '  select result.*, rownum row_num  from ( '
    || i_query_statement
    || ' ) result ) '
  || ' where row_num between '
  || TO_CHAR (v_start_index)
  || ' and '
  || TO_CHAR (v_end_index);

RETURN o_query_statement;

EXCEPTION
 WHEN OTHERS
 THEN
 RETURN NULL;
END pagination_stmt_fn;
/

/************************************************************************************************

--In put parameters
-- i_query_statement:  "SELELCT * FROM EMP ORDER BY EMPLOYEE_ID"   
   (assumption:   Table EMP is exist and contains some rows)

-- i_start_index: 10
--i_end_index: 25


select pagination_stmt_fn( 'SELECT * FROM EMP ORDER BY EMPLOYEE_ID',10,25) "pagination statement" from dual;


--out put on SQL* Plus window

pagination statement
--------------------------------------------------------------------------------
 select  * from (    select result.*, rownum row_num  from ( SELECT * FROM EMP 
ORDER BY EMPLOYEE_ID ) result )  where row_num between 10 and 25


*************************************************************************************************/

[ Read More ]
Read more...
Sunday, October 14, 2012

Oracle and SQL Server Database Search String procedure

Posted by Raju Gupta at 12:26 AM – 1 comments
 
This Procedure/Query is used to search list of strings available in Oracle/SQL server database. The strings to be searched should be passed as a parameter to the Procedure/Query. The results will be entered in a temporary table with the Table name and field name where the strings are found in the database.


CREATE PROCEDURE  strCheck 
(@strck varchar(100))

 AS

create table tbl3( num int)
create table TEMP_rec(tblName varchar(50),colName varchar(50))
Declare @tblName as varchar(25)
Declare @colName as varchar(25)
declare @colType as varchar(25)
declare @sql as varchar(200)

declare @num as int 
Declare tblcur cursor for 
select table_name as Name from INFORMATION_SCHEMA.Tables 
open tblcur 
 fetch next from tblcur into @tblName
while @@fetch_status=0

begin
 Declare colcur cursor for 
 SELECT column_Name,Data_Type FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME =   @tblName
   
 open colcur 
  fetch next from colcur into @colName,@coltype
  while @@fetch_status=0
  begin
   if @coltype='char' or @coltype='varchar'
   begin
    set @sql=''
    set @sql='select 1 from '
    select @sql = @sql + @tblName + ' where ' + @colname + ' like ' + '''%' + @strck + '%'''
    insert into tbl3 
     exec (@sql)
    if exists (select * from tbl3)
    begin
     delete from tbl3
     insert into TEMP_rec
      select @tblName,@colName
    end
   end
   fetch next from colcur into @colName,@coltype
  end
 close colcur
 deallocate colcur
    fetch next from tblcur into @tblName

end

close tblcur
deallocate tblcur
select * from TEMP_rec
drop table tbl3
drop table TEMP_rec
GO
[ Read More ]
Read more...

Deletion Records of Duplicate

Posted by Raju Gupta at 12:23 AM – 0 comments
 
Describes how to use SQL query of remove duplicate records from tables
DELETE FROM T_CONTACTS A 
WHERE A.ROWID > (SELECT MIN (ROWID) FROM T_CONTACTS B WHERE A.PHONE_NO = B.PHONE_NO);
[ Read More ]
Read more...

Oracle Sql Queries to view dependencies and partitioning.

Posted by Raju Gupta at 12:16 AM – 0 comments
 
This is the list of queries to find out the dependencies between databse objects and to find out the partitioning details of a table.


1:
select * from dict


Description: It will give you the list of all the system tables that are available with the comments on how a particular table can help you.

2 :
SELECT *  FROM All_Dependencies WHERE owner = 'GLOS_DB' AND NAME LIKE '%XYZ%'


Description :  It describes dependencies between procedures, packages, functions, package bodies, and triggers accessible to the current user, including dependencies on views created without any database links.This view does not display the SCHEMAID column.

3:
SELECT * from all_source
where TYPE IN('PROCEDURE','PACKAGE','FUNCTION',)
AND TEXT LIKE '%XYZ%'

Description : It will give you the list of all those database objects which you have mentioned in the TYPE IN clause and where your table is being referred . There are total  7 types which are as follows :
1 FUNCTION
2 JAVA SOURCE
3 PACKAGE
4 PACKAGE BODY
5 PROCEDURE
6 TRIGGER
7 TYPE

4:
select * from all_mviews where Mview_name = 'schema name.MV_NAME'


Description: This will give you all the information related to your mentioned Materialized view like its last refresh_date, compile state etc.

5:
SELECT * FROM DBA_VIEWS WHERE TEXT LIKE '%XYZ%'


Description : It will give you the details of the views that are accessible to a DBA. Details such as its owner name, its type etc.



6:
select * from All_Views where Text like '%XYZ%'  AND TYPE LIKE 'VIEW'


Description : It will give you the details of the views that are accessible to users. Details such as its owner name, its type etc.

7:
select* from  DBA_DEPENDENCIES

Description : DBA_DEPENDENCIES describes all dependencies in the database between procedures, packages, functions, package bodies, and triggers, including dependencies on views created without any database links.
For example :

SELECT type, name FROM SYS.DBA_DEPENDENCIES WHERE referenced_type   = 'TABLE' AND referenced_owner = 'GLOS_DB' AND referenced_name = 'GETS_GS_FINANCIAL_OASIS'AND type !=   'UNDEFINED'

8:

Select * from all_objects where Object_name like'%XYZ%'


Description : This will give you the information of all the objects that are accessible to the users.

9:
Select * from all_errors


Description : It describes current errors on all stored objects (views, procedures, functions, packages, and package bodies) accessible to the current user. It gives you the information like name of the object, type of the object, line in which error has came, position in the line where error occurred and text of the error.

10:
select TABLE_NAME from user_tab_cols where COLUMN_NAME like ' %XYZ%'


Description: This will give you the list of all the tables where the mentioned column is used.


Partitioning Related Queries :

1:
select * from all_part_tables


Description : It will list out all the tables that have been partitioned. It will give the information such as table name, partition type, sub partition type etc.

2:
select * from ALL_TAB_PARTITIONS where table_name like '˜XYZ'


Description : It will list out all the partitions and details of the partitions like partition name, sub partition count etc existing for  a table

3:
select * from All_Tab_Subpartitions where table_name like 'XYZ'


Description : It describes, for each table subpartition accessible to the current user, the subpartition name, name of the table and partition to which it belongs, and its storage attributes.

4:
select * from all_subpartition_templates


Description : It describes the subpartition templates accessible to the current user.
[ Read More ]
Read more...
Newer Posts
Subscribe to: Posts (Atom)
  • Popular
  • Recent
  • Archives

Popular Posts

  • Comparing data (rows)in two tables in PL/SQL
    Pl/sql code have Cursors that will fetch table and columns that you want to compare and it will Iterate through all tables in the local d...
  • Oracle Sql Queries to view dependencies and partitioning.
    This is the list of queries to find out the dependencies between databse objects and to find out the partitioning details of a table. 1...
  • Oracle PL/SQL Query for Pagination
    Oracle PL/SQL function makes the input query statement such a way that the query out put returns for a start row index to end row index. ...
  • Serial Number Related Query
    This query will let us know the corresponding Sales Order number associated with a given serial number installed in Installed Base. -...
  • Oracle and SQL Server Database Search String procedure
    This Procedure/Query is used to search list of strings available in Oracle/SQL server database. The strings to be searched should be passed...
  • Multi User session Kill in Oracle
    To kill the inactive users login in Oracle from any schema in a database.If any unwanted transactions were kept withput roll back it will...
  • SQL tips
    Re-usable SQL Queries useful in day-to-day scenario. COMMON QUERIES *************** SELECT instance_name FROM v$instance; ...
  • Query to search Special character in word
    The query looks for any special characters in column field (specially useful for password field) and reports it.   SELECT DISTINCT emp...
  • Advance SQL
    The query that uses partition OVER PARTITION BY analytic function The below example shows the cumulative salary within a departement ...
  • TABLE FINDER
    Table_Finder is a procedure to find all the tables that are queried in a particular package or procedure. It takes Package name or procedur...
Powered by Blogger.

Archives

  • ▼  2012 (11)
    • ▼  October (11)
      • Comparing data (rows)in two tables in PL/SQL
      • Serial Number Related Query
      • SQL tips
      • Advance SQL
      • Query to search Special character in word
      • Multi User session Kill in Oracle
      • TABLE FINDER
      • Oracle PL/SQL Query for Pagination
      • Oracle and SQL Server Database Search String proce...
      • Deletion Records of Duplicate
      • Oracle Sql Queries to view dependencies and partit...
 

Labels

  • Delete Query (1)
  • Oracle SQL Query (4)
  • PL/SQL Example (2)
  • Stored Procedure Example (3)
  • String Search Query (1)
  • System Query (1)

Followers

 
 
© 2011 SQL Tutorial with Examples | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger