2026-03-12 20:23:15

This commit is contained in:
root
2026-03-12 21:23:47 +01:00
parent eab4b36eca
commit 93039b8489
3332 changed files with 699614 additions and 0 deletions

73
idev/asm_alias.sql Normal file
View File

@@ -0,0 +1,73 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : asm_alias.sql |
-- | CLASS : Automatic Storage Management |
-- | PURPOSE : Provide a summary report of all alias definitions contained |
-- | within all ASM disk groups. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET TERMOUT OFF;
COLUMN current_instance NEW_VALUE current_instance NOPRINT;
SELECT rpad(sys_context('USERENV', 'INSTANCE_NAME'), 17) current_instance FROM dual;
SET TERMOUT ON;
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Report : ASM Aliases |
PROMPT | Instance : &current_instance |
PROMPT +------------------------------------------------------------------------+
SET ECHO OFF
SET FEEDBACK 6
SET HEADING ON
SET LINESIZE 180
SET PAGESIZE 50000
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
COLUMN disk_group_name FORMAT a25 HEAD 'Disk Group Name'
COLUMN alias_name FORMAT a50 HEAD 'Alias Name'
COLUMN file_number HEAD 'File|Number'
COLUMN file_incarnation HEAD 'File|Incarnation'
COLUMN alias_index HEAD 'Alias|Index'
COLUMN alias_incarnation HEAD 'Alias|Incarnation'
COLUMN parent_index HEAD 'Parent|Index'
COLUMN reference_index HEAD 'Reference|Index'
COLUMN alias_directory FORMAT a10 HEAD 'Alias|Directory?'
COLUMN system_created FORMAT a8 HEAD 'System|Created?'
BREAK ON report ON disk_group_name SKIP 1
SELECT
g.name disk_group_name
, a.name alias_name
, a.file_number file_number
, a.file_incarnation file_incarnation
, a.alias_index alias_index
, a.alias_incarnation alias_incarnation
, a.parent_index parent_index
, a.reference_index reference_index
, a.alias_directory alias_directory
, a.system_created system_created
FROM
v$asm_alias a JOIN v$asm_diskgroup g USING (group_number)
ORDER BY
g.name
, a.file_number
/

58
idev/asm_clients.sql Normal file
View File

@@ -0,0 +1,58 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : asm_clients.sql |
-- | CLASS : Automatic Storage Management |
-- | PURPOSE : Provide a summary report of all clients making use of this ASM |
-- | instance. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET TERMOUT OFF;
COLUMN current_instance NEW_VALUE current_instance NOPRINT;
SELECT rpad(sys_context('USERENV', 'INSTANCE_NAME'), 17) current_instance FROM dual;
SET TERMOUT ON;
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Report : ASM Clients |
PROMPT | Instance : &current_instance |
PROMPT +------------------------------------------------------------------------+
SET ECHO OFF
SET FEEDBACK 6
SET HEADING ON
SET LINESIZE 180
SET PAGESIZE 50000
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
COLUMN disk_group_name FORMAT a25 HEAD 'Disk Group Name'
COLUMN instance_name FORMAT a20 HEAD 'Instance Name'
COLUMN db_name FORMAT a9 HEAD 'Database Name'
COLUMN status FORMAT a12 HEAD 'Status'
SELECT
a.name disk_group_name
, c.instance_name instance_name
, c.db_name db_name
, c.status status
FROM
v$asm_diskgroup a JOIN v$asm_client c USING (group_number)
ORDER BY
a.name
/

73
idev/asm_diskgroups.sql Normal file
View File

@@ -0,0 +1,73 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : asm_diskgroups.sql |
-- | CLASS : Automatic Storage Management |
-- | PURPOSE : Provide a summary report of all disk groups. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET TERMOUT OFF;
COLUMN current_instance NEW_VALUE current_instance NOPRINT;
SELECT rpad(sys_context('USERENV', 'INSTANCE_NAME'), 17) current_instance FROM dual;
SET TERMOUT ON;
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Report : ASM Disk Groups |
PROMPT | Instance : &current_instance |
PROMPT +------------------------------------------------------------------------+
SET ECHO OFF
SET FEEDBACK 6
SET HEADING ON
SET LINESIZE 180
SET PAGESIZE 50000
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
COLUMN group_name FORMAT a25 HEAD 'Disk Group|Name'
COLUMN sector_size FORMAT 99,999 HEAD 'Sector|Size'
COLUMN block_size FORMAT 99,999 HEAD 'Block|Size'
COLUMN allocation_unit_size FORMAT 999,999,999 HEAD 'Allocation|Unit Size'
COLUMN state FORMAT a11 HEAD 'State'
COLUMN type FORMAT a6 HEAD 'Type'
COLUMN total_mb FORMAT 999,999,999 HEAD 'Total Size (MB)'
COLUMN used_mb FORMAT 999,999,999 HEAD 'Used Size (MB)'
COLUMN pct_used FORMAT 999.99 HEAD 'Pct. Used'
BREAK ON report ON disk_group_name SKIP 1
COMPUTE sum LABEL "Grand Total: " OF total_mb used_mb ON report
SELECT
name group_name
, sector_size sector_size
, block_size block_size
, allocation_unit_size allocation_unit_size
, state state
, type type
, total_mb total_mb
, (total_mb - free_mb) used_mb
, ROUND((1- (free_mb / total_mb))*100, 2) pct_used
FROM
v$asm_diskgroup
WHERE
total_mb != 0
ORDER BY
name
/

70
idev/asm_disks.sql Normal file
View File

@@ -0,0 +1,70 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : asm_disks.sql |
-- | CLASS : Automatic Storage Management |
-- | PURPOSE : Provide a summary report of all disks contained within all disk |
-- | groups. This script is also responsible for queriing all |
-- | candidate disks - those that are not assigned to any disk |
-- | group. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET TERMOUT OFF;
COLUMN current_instance NEW_VALUE current_instance NOPRINT;
SELECT rpad(sys_context('USERENV', 'INSTANCE_NAME'), 17) current_instance FROM dual;
SET TERMOUT ON;
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Report : ASM Disks |
PROMPT | Instance : &current_instance |
PROMPT +------------------------------------------------------------------------+
SET ECHO OFF
SET FEEDBACK 6
SET HEADING ON
SET LINESIZE 180
SET PAGESIZE 50000
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
COLUMN disk_group_name FORMAT a25 HEAD 'Disk Group Name'
COLUMN disk_file_path FORMAT a20 HEAD 'Path'
COLUMN disk_file_name FORMAT a20 HEAD 'File Name'
COLUMN disk_file_fail_group FORMAT a20 HEAD 'Fail Group'
COLUMN total_mb FORMAT 999,999,999 HEAD 'File Size (MB)'
COLUMN used_mb FORMAT 999,999,999 HEAD 'Used Size (MB)'
COLUMN pct_used FORMAT 999.99 HEAD 'Pct. Used'
BREAK ON report ON disk_group_name SKIP 1
COMPUTE sum LABEL "" OF total_mb used_mb ON disk_group_name
COMPUTE sum LABEL "Grand Total: " OF total_mb used_mb ON report
SELECT
NVL(a.name, '[CANDIDATE]') disk_group_name
, b.path disk_file_path
, b.name disk_file_name
, b.failgroup disk_file_fail_group
, b.total_mb total_mb
, (b.total_mb - b.free_mb) used_mb
, ROUND((1- (b.free_mb / b.total_mb))*100, 2) pct_used
FROM
v$asm_diskgroup a RIGHT OUTER JOIN v$asm_disk b USING (group_number)
ORDER BY
a.name
/

75
idev/asm_disks_perf.sql Normal file
View File

@@ -0,0 +1,75 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : asm_disks_perf.sql |
-- | CLASS : Automatic Storage Management |
-- | PURPOSE : Provide a summary report of all disks contained within all ASM |
-- | disk groups along with their performance metrics. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET TERMOUT OFF;
COLUMN current_instance NEW_VALUE current_instance NOPRINT;
SELECT rpad(sys_context('USERENV', 'INSTANCE_NAME'), 17) current_instance FROM dual;
SET TERMOUT ON;
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Report : ASM Disk Performance |
PROMPT | Instance : &current_instance |
PROMPT +------------------------------------------------------------------------+
SET ECHO OFF
SET FEEDBACK 6
SET HEADING ON
SET LINESIZE 256
SET PAGESIZE 50000
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
COLUMN disk_group_name FORMAT a20 HEAD 'Disk Group Name'
COLUMN disk_path FORMAT a20 HEAD 'Disk Path'
COLUMN reads FORMAT 999,999,999,999 HEAD 'Reads'
COLUMN writes FORMAT 999,999,999,999 HEAD 'Writes'
COLUMN read_errs FORMAT 999,999,999 HEAD 'Read|Errors'
COLUMN write_errs FORMAT 999,999,999 HEAD 'Write|Errors'
COLUMN read_time FORMAT 999,999,999,999 HEAD 'Read|Time'
COLUMN write_time FORMAT 999,999,999,999 HEAD 'Write|Time'
COLUMN bytes_read FORMAT 999,999,999,999,999 HEAD 'Bytes|Read'
COLUMN bytes_written FORMAT 999,999,999,999,999 HEAD 'Bytes|Written'
BREAK ON report ON disk_group_name SKIP 2
COMPUTE sum LABEL "" OF reads writes read_errs write_errs read_time write_time bytes_read bytes_written ON disk_group_name
COMPUTE sum LABEL "Grand Total: " OF reads writes read_errs write_errs read_time write_time bytes_read bytes_written ON report
SELECT
a.name disk_group_name
, b.path disk_path
, b.reads reads
, b.writes writes
, b.read_errs read_errs
, b.write_errs write_errs
, b.read_time read_time
, b.write_time write_time
, b.bytes_read bytes_read
, b.bytes_written bytes_written
FROM
v$asm_diskgroup a JOIN v$asm_disk b USING (group_number)
ORDER BY
a.name
/

56
idev/asm_drop_files.sql Normal file
View File

@@ -0,0 +1,56 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : asm_drop_files.sql |
-- | CLASS : Automatic Storage Management |
-- | PURPOSE : Used to create a SQL script that removes all ASM files |
-- | contained within all diskgroups. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET ECHO OFF
SET FEEDBACK OFF
SET HEADING OFF
SET LINESIZE 256
SET PAGESIZE 50000
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
COLUMN full_alias_path FORMAT a255 HEAD 'File Name'
COLUMN disk_group_name NOPRINT
SELECT
'ALTER DISKGROUP ' ||
disk_group_name ||
' DROP FILE ''' || CONCAT('+' || disk_group_name, SYS_CONNECT_BY_PATH(alias_name, '/')) || ''';' full_alias_path
FROM
( SELECT
g.name disk_group_name
, a.parent_index pindex
, a.name alias_name
, a.reference_index rindex
, f.type type
FROM
v$asm_file f RIGHT OUTER JOIN v$asm_alias a USING (group_number, file_number)
JOIN v$asm_diskgroup g USING (group_number)
)
WHERE type IS NOT NULL
START WITH (MOD(pindex, POWER(2, 24))) = 0
CONNECT BY PRIOR rindex = pindex
/
SET FEEDBACK 6
SET HEAD ON

108
idev/asm_files.sql Normal file
View File

@@ -0,0 +1,108 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : asm_files.sql |
-- | CLASS : Automatic Storage Management |
-- | PURPOSE : Provide a summary report of all files, file metadata, and |
-- | volume information for all ASM disk groups customized for |
-- | Oracle 11g and higher. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET TERMOUT OFF;
COLUMN current_instance NEW_VALUE current_instance NOPRINT;
SELECT rpad(sys_context('USERENV', 'INSTANCE_NAME'), 17) current_instance FROM dual;
SET TERMOUT ON;
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Report : ASM Files |
PROMPT | Instance : &current_instance |
PROMPT +------------------------------------------------------------------------+
SET ECHO OFF
SET FEEDBACK 6
SET HEADING ON
SET LINESIZE 180
SET PAGESIZE 50000
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
COLUMN full_path FORMAT a75 HEAD 'ASM File Name / Volume Name / Device Name'
COLUMN system_created FORMAT a8 HEAD 'System|Created?'
COLUMN bytes FORMAT 9,999,999,999,999 HEAD 'Bytes'
COLUMN space FORMAT 9,999,999,999,999 HEAD 'Space'
COLUMN type FORMAT a18 HEAD 'File Type'
COLUMN redundancy FORMAT a12 HEAD 'Redundancy'
COLUMN striped FORMAT a8 HEAD 'Striped'
COLUMN creation_date FORMAT a20 HEAD 'Creation Date'
COLUMN disk_group_name noprint
BREAK ON report ON disk_group_name SKIP 1
COMPUTE sum LABEL "" OF bytes space ON disk_group_name
COMPUTE sum LABEL "Grand Total: " OF bytes space ON report
SELECT
CONCAT('+' || db_files.disk_group_name, SYS_CONNECT_BY_PATH(db_files.alias_name, '/')) full_path
, db_files.bytes
, db_files.space
, NVL(LPAD(db_files.type, 18), '<DIRECTORY>') type
, db_files.creation_date
, db_files.disk_group_name
, LPAD(db_files.system_created, 4) system_created
FROM
( SELECT
g.name disk_group_name
, a.parent_index pindex
, a.name alias_name
, a.reference_index rindex
, a.system_created system_created
, f.bytes bytes
, f.space space
, f.type type
, TO_CHAR(f.creation_date, 'DD-MON-YYYY HH24:MI:SS') creation_date
FROM
v$asm_file f RIGHT OUTER JOIN v$asm_alias a USING (group_number, file_number)
JOIN v$asm_diskgroup g USING (group_number)
) db_files
WHERE db_files.type IS NOT NULL
START WITH (MOD(db_files.pindex, POWER(2, 24))) = 0
CONNECT BY PRIOR db_files.rindex = db_files.pindex
UNION
SELECT
'+' || volume_files.disk_group_name || ' [' || volume_files.volume_name || '] ' || volume_files.volume_device full_path
, volume_files.bytes
, volume_files.space
, NVL(LPAD(volume_files.type, 18), '<DIRECTORY>') type
, volume_files.creation_date
, volume_files.disk_group_name
, null
FROM
( SELECT
g.name disk_group_name
, v.volume_name volume_name
, v.volume_device volume_device
, f.bytes bytes
, f.space space
, f.type type
, TO_CHAR(f.creation_date, 'DD-MON-YYYY HH24:MI:SS') creation_date
FROM
v$asm_file f RIGHT OUTER JOIN v$asm_volume v USING (group_number, file_number)
JOIN v$asm_diskgroup g USING (group_number)
) volume_files
WHERE volume_files.type IS NOT NULL
/

73
idev/asm_files2.sql Normal file
View File

@@ -0,0 +1,73 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : asm_files2.sql |
-- | CLASS : Automatic Storage Management |
-- | PURPOSE : Provide a summary report of all files (and file metadata) |
-- | information for all ASM disk groups. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET TERMOUT OFF;
COLUMN current_instance NEW_VALUE current_instance NOPRINT;
SELECT rpad(sys_context('USERENV', 'INSTANCE_NAME'), 17) current_instance FROM dual;
SET TERMOUT ON;
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Report : ASM Files |
PROMPT | Instance : &current_instance |
PROMPT +------------------------------------------------------------------------+
SET ECHO OFF
SET FEEDBACK 6
SET HEADING ON
SET LINESIZE 180
SET PAGESIZE 50000
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
COLUMN disk_group_name FORMAT a25 HEAD 'Disk Group Name'
COLUMN file_name FORMAT a50 HEAD 'File Name'
COLUMN bytes FORMAT 9,999,999,999,999 HEAD 'Bytes'
COLUMN space FORMAT 9,999,999,999,999 HEAD 'Space'
COLUMN type FORMAT a18 HEAD 'File Type'
COLUMN redundancy FORMAT a12 HEAD 'Redundancy'
COLUMN striped FORMAT a8 HEAD 'Striped'
COLUMN creation_date FORMAT a20 HEAD 'Creation Date'
BREAK ON report ON disk_group_name SKIP 1
COMPUTE sum LABEL "" OF bytes space ON disk_group_name
COMPUTE sum LABEL "Grand Total: " OF bytes space ON report
SELECT
g.name disk_group_name
, a.name file_name
, f.bytes bytes
, f.space space
, f.type type
, TO_CHAR(f.creation_date, 'DD-MON-YYYY HH24:MI:SS') creation_date
FROM
v$asm_file f JOIN v$asm_alias a USING (group_number, file_number)
JOIN v$asm_diskgroup g USING (group_number)
WHERE
system_created = 'Y'
ORDER BY
g.name
, file_number
/

84
idev/asm_files_10g.sql Normal file
View File

@@ -0,0 +1,84 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : asm_files_10g.sql |
-- | CLASS : Automatic Storage Management |
-- | PURPOSE : Provide a summary report of all files (and file metadata) |
-- | information for all ASM disk groups customized for Oracle 10g. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET TERMOUT OFF;
COLUMN current_instance NEW_VALUE current_instance NOPRINT;
SELECT rpad(sys_context('USERENV', 'INSTANCE_NAME'), 17) current_instance FROM dual;
SET TERMOUT ON;
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Report : ASM Files |
PROMPT | Instance : &current_instance |
PROMPT +------------------------------------------------------------------------+
SET ECHO OFF
SET FEEDBACK 6
SET HEADING ON
SET LINESIZE 180
SET PAGESIZE 50000
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
COLUMN full_alias_path FORMAT a75 HEAD 'File Name'
COLUMN system_created FORMAT a8 HEAD 'System|Created?'
COLUMN bytes FORMAT 9,999,999,999,999 HEAD 'Bytes'
COLUMN space FORMAT 9,999,999,999,999 HEAD 'Space'
COLUMN type FORMAT a18 HEAD 'File Type'
COLUMN redundancy FORMAT a12 HEAD 'Redundancy'
COLUMN striped FORMAT a8 HEAD 'Striped'
COLUMN creation_date FORMAT a20 HEAD 'Creation Date'
COLUMN disk_group_name NOPRINT
BREAK ON report ON disk_group_name SKIP 1
COMPUTE sum LABEL "" OF bytes space ON disk_group_name
COMPUTE sum LABEL "Grand Total: " OF bytes space ON report
SELECT
CONCAT('+' || disk_group_name, SYS_CONNECT_BY_PATH(alias_name, '/')) full_alias_path
, bytes
, space
, NVL(LPAD(type, 18), '<DIRECTORY>') type
, creation_date
, disk_group_name
, LPAD(system_created, 4) system_created
FROM
( SELECT
g.name disk_group_name
, a.parent_index pindex
, a.name alias_name
, a.reference_index rindex
, a.system_created system_created
, f.bytes bytes
, f.space space
, f.type type
, TO_CHAR(f.creation_date, 'DD-MON-YYYY HH24:MI:SS') creation_date
FROM
v$asm_file f RIGHT OUTER JOIN v$asm_alias a USING (group_number, file_number)
JOIN v$asm_diskgroup g USING (group_number)
)
WHERE type IS NOT NULL
START WITH (MOD(pindex, POWER(2, 24))) = 0
CONNECT BY PRIOR rindex = pindex
/

65
idev/asm_templates.sql Normal file
View File

@@ -0,0 +1,65 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : asm_templates.sql |
-- | CLASS : Automatic Storage Management |
-- | PURPOSE : Provide a summary report of all template information for all |
-- | ASM disk groups. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET TERMOUT OFF;
COLUMN current_instance NEW_VALUE current_instance NOPRINT;
SELECT rpad(sys_context('USERENV', 'INSTANCE_NAME'), 17) current_instance FROM dual;
SET TERMOUT ON;
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Report : ASM Templates |
PROMPT | Instance : &current_instance |
PROMPT +------------------------------------------------------------------------+
SET ECHO OFF
SET FEEDBACK 6
SET HEADING ON
SET LINESIZE 180
SET PAGESIZE 50000
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
COLUMN disk_group_name FORMAT a25 HEAD 'Disk Group Name'
COLUMN entry_number FORMAT 999999 HEAD 'Entry Number'
COLUMN redundancy FORMAT a12 HEAD 'Redundancy'
COLUMN stripe FORMAT a8 HEAD 'Stripe'
COLUMN system FORMAT a6 HEAD 'System'
COLUMN template_name FORMAT a30 HEAD 'Template Name'
BREAK ON report ON disk_group_name SKIP 1
SELECT
b.name disk_group_name
, a.entry_number entry_number
, a.redundancy redundancy
, a.stripe stripe
, a.system system
, a.name template_name
FROM
v$asm_template a JOIN v$asm_diskgroup b USING (group_number)
ORDER BY
b.name
, a.entry_number
/

70
idev/asmm_components.sql Normal file
View File

@@ -0,0 +1,70 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : asmm_components.sql |
-- | CLASS : Automatic Shared Memory Management |
-- | PURPOSE : Provide a summary report of all dynamic components as part of |
-- | Oracle's ASMM configuration. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET TERMOUT OFF;
COLUMN current_instance NEW_VALUE current_instance NOPRINT;
SELECT rpad(instance_name, 17) current_instance FROM v$instance;
SET TERMOUT ON;
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Report : ASMM Components |
PROMPT | Instance : &current_instance |
PROMPT +------------------------------------------------------------------------+
SET ECHO OFF
SET FEEDBACK 6
SET HEADING ON
SET LINESIZE 180
SET PAGESIZE 50000
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
COLUMN component FORMAT a25 HEAD 'Component Name'
COLUMN current_size FORMAT 9,999,999,999 HEAD 'Current Size'
COLUMN min_size FORMAT 9,999,999,999 HEAD 'Min Size'
COLUMN max_size FORMAT 9,999,999,999 HEAD 'Max Size'
COLUMN user_specified_size FORMAT 9,999,999,999 HEAD 'User Specified|Size'
COLUMN oper_count FORMAT 9,999 HEAD 'Oper.|Count'
COLUMN last_oper_type FORMAT a10 HEAD 'Last Oper.|Type'
COLUMN last_oper_mode FORMAT a10 HEAD 'Last Oper.|Mode'
COLUMN last_oper_time FORMAT a20 HEAD 'Last Oper.|Time'
COLUMN granule_size FORMAT 999,999,999 HEAD 'Granule Size'
SELECT
component
, current_size
, min_size
, max_size
, user_specified_size
, oper_count
, last_oper_type
, last_oper_mode
, TO_CHAR(last_oper_time, 'DD-MON-YYYY HH24:MI:SS') last_oper_time
, granule_size
FROM
v$sga_dynamic_components
ORDER BY
component DESC
/

View File

@@ -0,0 +1,94 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : awr_snapshots_dbtime.sql |
-- | CLASS : Automatic Workload Repository |
-- | PURPOSE : Provide a list of all AWR snapshots and the total database time |
-- | (DB Time) consumed within its interval. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET TERMOUT OFF;
COLUMN current_instance NEW_VALUE current_instance NOPRINT;
SELECT rpad(sys_context('USERENV', 'INSTANCE_NAME'), 17) current_instance FROM dual;
SET TERMOUT ON;
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Report : AWR Snapshots (DB Time Report) |
PROMPT | Instance : &current_instance |
PROMPT +------------------------------------------------------------------------+
SET ECHO OFF
SET FEEDBACK 6
SET HEADING ON
SET LINESIZE 256
SET PAGESIZE 50000
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
COLUMN instance_name_print FORMAT a13 HEADING 'Instance Name'
COLUMN snap_id FORMAT 9999999 HEADING 'Snap ID'
COLUMN startup_time FORMAT a21 HEADING 'Instance Startup Time'
COLUMN begin_interval_time FORMAT a20 HEADING 'Begin Interval Time'
COLUMN end_interval_time FORMAT a20 HEADING 'End Interval Time'
COLUMN elapsed_time FORMAT 999,999,999,999.99 HEADING 'Elapsed Time (min)'
COLUMN db_time FORMAT 999,999,999,999.99 HEADING 'DB Time (min)'
COLUMN pct_db_time FORMAT 999999999 HEADING '% DB Time'
COLUMN cpu_time FORMAT 999,999,999.99 HEADING 'CPU Time (min)'
BREAK ON instance_name_print ON startup_time
DEFINE spool_file=awr_snapshots_dbtime.lst
SPOOL &spool_file
SELECT
i.instance_name instance_name_print
, s.snap_id snap_id
, TO_CHAR(s.startup_time, 'mm/dd/yyyy HH24:MI:SS') startup_time
, TO_CHAR(s.begin_interval_time, 'mm/dd/yyyy HH24:MI:SS') begin_interval_time
, TO_CHAR(s.end_interval_time, 'mm/dd/yyyy HH24:MI:SS') end_interval_time
, ROUND(EXTRACT(DAY FROM s.end_interval_time - s.begin_interval_time) * 1440 +
EXTRACT(HOUR FROM s.end_interval_time - s.begin_interval_time) * 60 +
EXTRACT(MINUTE FROM s.end_interval_time - s.begin_interval_time) +
EXTRACT(SECOND FROM s.end_interval_time - s.begin_interval_time) / 60, 2) elapsed_time
, ROUND((e.value - b.value)/1000000/60, 2) db_time
, ROUND(((((e.value - b.value)/1000000/60) / (EXTRACT(DAY FROM s.end_interval_time - s.begin_interval_time) * 1440 +
EXTRACT(HOUR FROM s.end_interval_time - s.begin_interval_time) * 60 +
EXTRACT(MINUTE FROM s.end_interval_time - s.begin_interval_time) +
EXTRACT(SECOND FROM s.end_interval_time - s.begin_interval_time) / 60) ) * 100), 2) pct_db_time
FROM
dba_hist_snapshot s
, gv$instance i
, dba_hist_sys_time_model e
, dba_hist_sys_time_model b
WHERE
i.instance_number = s.instance_number
AND e.snap_id = s.snap_id
AND b.snap_id = s.snap_id - 1
AND e.stat_id = b.stat_id
AND e.instance_number = b.instance_number
AND e.instance_number = s.instance_number
AND e.stat_name = 'DB time'
ORDER BY
i.instance_name
, s.snap_id;
SPOOL OFF
PROMPT Report written to &spool_file
PROMPT

View File

@@ -0,0 +1,102 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : awr_snapshots_dbtime_xls.sql |
-- | CLASS : Automatic Workload Repository |
-- | PURPOSE : Provide a list of all AWR snapshots and the total database time |
-- | (DB Time) consumed within its interval. The output from this |
-- | script can be used when loading the data into MS Excel. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET TERMOUT OFF;
COLUMN current_instance NEW_VALUE current_instance NOPRINT;
SELECT rpad(sys_context('USERENV', 'INSTANCE_NAME'), 17) current_instance FROM dual;
SET TERMOUT ON;
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Report : AWR Snapshots (DB Time Report) for Microsoft Excel |
PROMPT | Instance : &current_instance |
PROMPT +------------------------------------------------------------------------+
SET ECHO OFF
SET FEEDBACK OFF
SET HEADING OFF
SET LINESIZE 32767
SET PAGESIZE 50000
SET TERMOUT OFF
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
DEFINE fileName=awr_snapshots_dbtime_xls
COLUMN dbname NEW_VALUE _dbname NOPRINT
SELECT name dbname FROM v$database;
COLUMN spool_time NEW_VALUE _spool_time NOPRINT
SELECT TO_CHAR(SYSDATE,'YYYYMMDD') spool_time FROM dual;
SPOOL &FileName._&_dbname._&_spool_time..txt
SELECT
'Instance Name' || chr(9)
|| 'Instance Startup Time' || chr(9)
|| 'Begin Interval Time' || chr(9)
|| 'End Interval Time' || chr(9)
|| 'Elapsed Time (min)' || chr(9)
|| 'DB Time (min)' || chr(9)
|| '% DB Time'
FROM dual;
SELECT
i.instance_name || chr(9)
|| TO_CHAR(s.startup_time, 'mm/dd/yyyy HH24:MI:SS') || chr(9)
|| TO_CHAR(s.begin_interval_time, 'mm/dd/yyyy HH24:MI:SS') || chr(9)
|| TO_CHAR(s.end_interval_time, 'mm/dd/yyyy HH24:MI:SS') || chr(9)
|| ROUND(EXTRACT(DAY FROM s.end_interval_time - s.begin_interval_time) * 1440 +
EXTRACT(HOUR FROM s.end_interval_time - s.begin_interval_time) * 60 +
EXTRACT(MINUTE FROM s.end_interval_time - s.begin_interval_time) +
EXTRACT(SECOND FROM s.end_interval_time - s.begin_interval_time) / 60, 2) || chr(9)
|| ROUND((e.value - b.value)/1000000/60, 2) || chr(9)
|| ROUND(((((e.value - b.value)/1000000/60) / (EXTRACT(DAY FROM s.end_interval_time - s.begin_interval_time) * 1440 +
EXTRACT(HOUR FROM s.end_interval_time - s.begin_interval_time) * 60 +
EXTRACT(MINUTE FROM s.end_interval_time - s.begin_interval_time) +
EXTRACT(SECOND FROM s.end_interval_time - s.begin_interval_time) / 60) ) * 100), 2) instance_db_time
FROM
dba_hist_snapshot s
, gv$instance i
, dba_hist_sys_time_model e
, dba_hist_sys_time_model b
WHERE
i.instance_number = s.instance_number
AND e.snap_id = s.snap_id
AND b.snap_id = s.snap_id - 1
AND e.stat_id = b.stat_id
AND e.instance_number = b.instance_number
AND e.instance_number = s.instance_number
AND e.stat_name = 'DB time'
ORDER BY
i.instance_name
, s.snap_id;
SPOOL OFF
SET FEEDBACK 6
SET HEADING ON
SET TERMOUT ON
PROMPT Wrote report to &FileName._&_dbname._&_spool_time..txt
PROMPT

View File

@@ -0,0 +1,75 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : dba_blocks_used_by_table.sql |
-- | CLASS : Database Administration |
-- | PURPOSE : This article describes how to find out how many blocks are |
-- | really being used within a table. (ie. Blocks that are not |
-- | empty) Scripts are included for both Oracle7 and Oracle8. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
--------------------------------------------
HOW MANY BLOCKS CONTAIN DATA (are not empty)
-----------------------------------------------------------------------
Each row in the table has pseudocolumn called ROWID.
This pseudo contains information about physical location
of the row in format:
block_number.row.file
If the table is stored in a tablespace which has one
datafile, all we have to do is to get DISTINCT
number of block_number from ROWID column of this table.
But if the table is stored in a tablespace with more than one
datafile then you can have the same block_number but in
different datafiles so we have to get DISTINCT number of
block_number+file from ROWID.
The SELECT statements which give us the number of "really used"
blocks is below. They are different for ORACLE 7 and ORACLE 8
because of different structure of ROWID column in these versions.
You could ask why the above information could not be determined
by using the ANALYZE TABLE command. The ANALYZE TABLE command only
identifies the number of 'ever' used blocks or the high water mark
for the table.
-----------------------------------------------------------------------
-------
ORACLE7
-----------------------------------------------------------------------
SELECT
COUNT(DISTINCT(SUBSTR(rowid,1,8)
||
SUBSTR(rowid,15,4)))
FROM &table_name
/
--------
ORACLE8+
-----------------------------------------------------------------------
SELECT COUNT ( DISTINCT
DBMS_ROWID.ROWID_BLOCK_NUMBER(rowid)
||
DBMS_ROWID.ROWID_RELATIVE_FNO(rowid)
) "Used"
FROM &table_name;
- or -
SELECT COUNT (DISTINCT SUBSTR(rowid,1,15)) "Used"
FROM &table_name;

View File

@@ -0,0 +1,69 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : dba_column_constraints.sql |
-- | CLASS : Database Administration |
-- | PURPOSE : Reports on all column constraints in the database. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET TERMOUT OFF;
COLUMN current_instance NEW_VALUE current_instance NOPRINT;
SELECT rpad(instance_name, 17) current_instance FROM v$instance;
SET TERMOUT ON;
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Report : Column Constraints for a Specified Table |
PROMPT | Instance : &current_instance |
PROMPT +------------------------------------------------------------------------+
PROMPT
ACCEPT schema CHAR PROMPT 'Enter schema : '
ACCEPT tab_name CHAR PROMPT 'Enter table name : '
SET ECHO OFF
SET FEEDBACK 6
SET HEADING ON
SET LINESIZE 180
SET PAGESIZE 50000
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
COLUMN constraint_name FORMAT a20 HEADING 'Constraint Name'
COLUMN table_name FORMAT a20 HEADING 'Table Name'
COLUMN column_name FORMAT a25 HEADING 'Column Name'
COLUMN position FORMAT 999,999,999 HEADING 'Index Position'
BREAK ON report ON owner ON table_name SKIP 1
SELECT
owner
, table_name
, constraint_name
, column_name
, position
FROM
dba_cons_columns
WHERE
owner = UPPER('&schema')
AND table_name = UPPER('&tab_name')
ORDER BY
owner
, table_name
, constraint_name
, position
/

1632
idev/dba_compare_schemas.sql Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,76 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : dba_controlfile_records.sql |
-- | CLASS : Database Administration |
-- | PURPOSE : Query information information about the control file record |
-- | sections. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET TERMOUT OFF;
COLUMN current_instance NEW_VALUE current_instance NOPRINT;
SELECT rpad(instance_name, 17) current_instance FROM v$instance;
SET TERMOUT ON;
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Report : Control File Records |
PROMPT | Instance : &current_instance |
PROMPT +------------------------------------------------------------------------+
SET ECHO OFF
SET FEEDBACK 6
SET HEADING ON
SET LINESIZE 180
SET PAGESIZE 50000
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
COLUMN type FORMAT a30 HEADING "Record Section Type"
COLUMN record_size FORMAT 999,999 HEADING "Record Size|(in bytes)"
COLUMN records_total FORMAT 999,999 HEADING "Records Allocated"
COLUMN bytes_alloc FORMAT 999,999,999 HEADING "Bytes Allocated"
COLUMN records_used FORMAT 999,999 HEADING "Records Used"
COLUMN bytes_used FORMAT 999,999,999 HEADING "Bytes Used"
COLUMN pct_used FORMAT B999 HEADING "% Used"
COLUMN first_index HEADING "First Index"
COLUMN last_index HEADING "Last Index"
COLUMN last_recid HEADING "Last RecID"
BREAK ON report
COMPUTE sum OF records_total ON report
COMPUTE sum OF bytes_alloc ON report
COMPUTE sum OF records_used ON report
COMPUTE sum OF bytes_used ON report
COMPUTE avg OF pct_used ON report
SELECT
type
, record_size
, records_total
, (records_total * record_size) bytes_alloc
, records_used
, (records_used * record_size) bytes_used
, NVL(records_used/records_total * 100, 0) pct_used
, first_index
, last_index
, last_recid
FROM v$controlfile_record_section
ORDER BY type
/

51
idev/dba_controlfiles.sql Normal file
View File

@@ -0,0 +1,51 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : dba_controlfiles.sql |
-- | CLASS : Database Administration |
-- | PURPOSE : Query all control files from the database. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET TERMOUT OFF;
COLUMN current_instance NEW_VALUE current_instance NOPRINT;
SELECT rpad(instance_name, 17) current_instance FROM v$instance;
SET TERMOUT ON;
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Report : Control Files |
PROMPT | Instance : &current_instance |
PROMPT +------------------------------------------------------------------------+
SET ECHO OFF
SET FEEDBACK 6
SET HEADING ON
SET LINESIZE 256
SET PAGESIZE 50000
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
COLUMN name FORMAT a85 HEADING "Controlfile Name"
COLUMN status HEADING "Status"
SELECT
name
, LPAD(status, 7) status
FROM v$controlfile
ORDER BY name
/

82
idev/dba_cr_init.sql Normal file
View File

@@ -0,0 +1,82 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : dba_cr_init.sql |
-- | CLASS : Database Administration |
-- | PURPOSE : This script reads the database instance parameters and creates |
-- | an example init.ora file. This is often used when cloning a |
-- | database and need a fresh text init.ora file for the new |
-- | database. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET ECHO OFF
SET FEEDBACK OFF
SET HEADING OFF
SET LINESIZE 32767
SET PAGESIZE 50000
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
COLUMN oracle_sid NEW_VALUE xoracle_sid NOPRINT FORMAT a1
SELECT value oracle_sid
FROM v$parameter
WHERE name = 'instance_name'
/
spool init&xoracle_sid..ora.sample
SELECT
'# +-------------------------------------------------------------------+' || chr(10) ||
'# | FILE : init' || i.value || '.ora' || LPAD('|', 43-length(i.value), ' ') || chr(10) ||
'# | CREATION DATE : ' ||
to_char(sysdate, 'DD-MON-YYYY') ||
' |' || chr(10) ||
'# | DATABASE NAME : ' || d.value || LPAD('|', 51-length(d.value), ' ') || chr(10) ||
'# | INSTANCE NAME : ' || i.value || LPAD('|', 51-length(i.value), ' ') || chr(10) ||
'# | SERVER NAME : ' || s.value || LPAD('|', 51-length(s.value), ' ') || chr(10) ||
'# | GLOBAL NAME : ' || g.global_name|| LPAD('|', 51-length(g.global_name), ' ') || chr(10) ||
'# +-------------------------------------------------------------------+'
FROM
v$parameter d
, v$parameter i
, v$parameter s
, global_name g
WHERE
d.name = 'db_name'
AND i.name = 'instance_name'
AND s.name = 'service_names';
select
'# +---------------------+' || chr(10) ||
'# | DATABASE PARAMETERS |' || chr(10) ||
'# +---------------------+'
from dual;
SELECT
DECODE(isdefault, 'TRUE', '# ') ||
DECODE(isdefault, 'TRUE', RPAD(name,43), RPAD(name,45)) ||
' = ' ||
value
FROM v$parameter
ORDER BY name;
spool off
SET FEEDBACK 6
SET HEADING ON

60
idev/dba_db_growth.sql Normal file
View File

@@ -0,0 +1,60 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : dba_db_growth.sql |
-- | CLASS : Database Administration |
-- | PURPOSE : Provides a report on physical database growth with respect to |
-- | the date that data files have been added. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET TERMOUT OFF;
COLUMN current_instance NEW_VALUE current_instance NOPRINT;
SELECT rpad(instance_name, 17) current_instance FROM v$instance;
SET TERMOUT ON;
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Report : Database Growth |
PROMPT | Instance : &current_instance |
PROMPT | Note : This script only tracks when a new data file was added to |
PROMPT | the database. Any data file that was manually increased or |
PROMPT | decreased in size or automatically increased using the |
PROMPT | AUTOEXTEND option is not tracked by this script. |
PROMPT +------------------------------------------------------------------------+
SET ECHO OFF
SET FEEDBACK 6
SET HEADING ON
SET LINESIZE 180
SET PAGESIZE 50000
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
COLUMN month FORMAT a7 HEADING 'Month'
COLUMN growth FORMAT 999,999,999,999,999 HEADING 'Growth (Bytes)'
BREAK ON report
COMPUTE sum OF growth ON report
SELECT
TO_CHAR(creation_time, 'RRRR-MM') month
, SUM(bytes) growth
FROM sys.v_$datafile
GROUP BY TO_CHAR(creation_time, 'RRRR-MM')
ORDER BY TO_CHAR(creation_time, 'RRRR-MM');

54
idev/dba_directories.sql Normal file
View File

@@ -0,0 +1,54 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : dba_directories.sql |
-- | CLASS : Database Administration |
-- | PURPOSE : Provides a summary report of all Oracle Directory objects. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET TERMOUT OFF;
COLUMN current_instance NEW_VALUE current_instance NOPRINT;
SELECT rpad(instance_name, 17) current_instance FROM v$instance;
SET TERMOUT ON;
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Report : Oracle Directories |
PROMPT | Instance : &current_instance |
PROMPT +------------------------------------------------------------------------+
SET ECHO OFF
SET FEEDBACK 6
SET HEADING ON
SET LINESIZE 180
SET PAGESIZE 50000
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
COLUMN owner FORMAT a10 HEADING 'Owner'
COLUMN directory_name FORMAT a30 HEADING 'Directory Name'
COLUMN directory_path FORMAT a85 HEADING 'Directory Path'
SELECT
owner
, directory_name
, directory_path
FROM
dba_directories
ORDER BY
owner
, directory_name;

63
idev/dba_errors.sql Normal file
View File

@@ -0,0 +1,63 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : dba_errors.sql |
-- | CLASS : Database Administration |
-- | PURPOSE : Report on all procedural (PL/SQL, Views, Triggers, etc.) errors.|
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET TERMOUT OFF;
COLUMN current_instance NEW_VALUE current_instance NOPRINT;
SELECT rpad(instance_name, 17) current_instance FROM v$instance;
SET TERMOUT ON;
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Report : All Procedural (PL/SQL, Views, Triggers, etc.) Errors |
PROMPT | Instance : &current_instance |
PROMPT +------------------------------------------------------------------------+
SET ECHO OFF
SET FEEDBACK 6
SET HEADING ON
SET LINESIZE 180
SET PAGESIZE 50000
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
COLUMN type FORMAT a15 HEAD 'Object Type'
COLUMN owner FORMAT a17 HEAD 'Schema'
COLUMN name FORMAT a30 HEAD 'Object Name'
COLUMN sequence FORMAT 999,999 HEAD 'Sequence'
COLUMN line FORMAT 999,999 HEAD 'Line'
COLUMN position FORMAT 999,999 HEAD 'Position'
COLUMN text HEAD 'Text'
SELECT
type
, owner
, name
, sequence
, line
, position
, text || chr(10) || chr(10) text
FROM
dba_errors
ORDER BY
1, 2, 3
/

View File

@@ -0,0 +1,88 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : dba_file_space_usage.sql |
-- | CLASS : Database Administration |
-- | PURPOSE : Reports on all data file usage. This script was designed to |
-- | work with Oracle8i or higher. It will include true TEMPORARY |
-- | tablespaces. (i.e. use of "tempfiles") |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET TERMOUT OFF;
COLUMN current_instance NEW_VALUE current_instance NOPRINT;
SELECT rpad(instance_name, 17) current_instance FROM v$instance;
SET TERMOUT ON;
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Report : File Usage |
PROMPT | Instance : &current_instance |
PROMPT +------------------------------------------------------------------------+
SET ECHO OFF
SET FEEDBACK 6
SET HEADING ON
SET LINESIZE 256
SET PAGESIZE 50000
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
COLUMN tablespace FORMAT a18 HEADING 'Tablespace Name'
COLUMN filename FORMAT a75 HEADING 'Filename'
COLUMN filesize FORMAT 9,999,999,999,999 HEADING 'File Size'
COLUMN used FORMAT 9,999,999,999,999 HEADING 'Used (in bytes)'
COLUMN pct_used FORMAT 999 HEADING 'Pct. Used'
BREAK ON report
COMPUTE sum OF filesize ON report
COMPUTE sum OF used ON report
COMPUTE avg OF pct_used ON report
SELECT /*+ ordered */
d.tablespace_name tablespace
, d.file_name filename
, d.file_id file_id
, d.bytes filesize
, NVL((d.bytes - s.bytes), d.bytes) used
, TRUNC(((NVL((d.bytes - s.bytes) , d.bytes)) / d.bytes) * 100) pct_used
FROM
sys.dba_data_files d
, v$datafile v
, ( select file_id, SUM(bytes) bytes
from sys.dba_free_space
GROUP BY file_id) s
WHERE
(s.file_id (+)= d.file_id)
AND (d.file_name = v.name)
UNION
SELECT
d.tablespace_name tablespace
, d.file_name filename
, d.file_id file_id
, d.bytes filesize
, NVL(t.bytes_cached, 0) used
, TRUNC((t.bytes_cached / d.bytes) * 100) pct_used
FROM
sys.dba_temp_files d
, v$temp_extent_pool t
, v$tempfile v
WHERE
(t.file_id (+)= d.file_id)
AND (d.file_id = v.file#)
/

View File

@@ -0,0 +1,95 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : dba_file_space_usage_7.sql |
-- | CLASS : Database Administration |
-- | PURPOSE : Reports on all data file usage. This script was designed to |
-- | work with Oracle7 and Oracle8. This script can be run against |
-- | higher database versions (i.e. Oracle8i) but will not return |
-- | information about true TEMPORARY tablespaces. (i.e. use of |
-- | "tempfiles") |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET TERMOUT OFF;
COLUMN current_instance NEW_VALUE current_instance NOPRINT;
SELECT rpad(instance_name, 17) current_instance FROM v$instance;
SET TERMOUT ON;
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Report : File Usage |
PROMPT | Instance : &current_instance |
PROMPT +------------------------------------------------------------------------+
SET ECHO OFF
SET FEEDBACK 6
SET HEADING ON
SET LINESIZE 180
SET PAGESIZE 50000
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
COLUMN bs NEW_VALUE xbs NOPRINT FORMAT a1
COLUMN tablespace FORMAT a30 HEADING 'Tablespace Name'
COLUMN filename FORMAT a55 HEADING 'Filename'
COLUMN filesize FORMAT 9,999,999,999,999 HEADING 'File Size'
COLUMN used FORMAT 9,999,999,999,999 HEADING 'Used (in bytes)'
COLUMN free FORMAT 9,999,999,999,999 HEADING 'Free (in bytes)'
COLUMN pct_used FORMAT 999 HEADING 'Pct. Used'
SET TERMOUT OFF
SELECT value bs FROM v$parameter WHERE name = 'db_block_size';
SET TERMOUT ON
BREAK ON report
COMPUTE avg OF pct_used ON report
COMPUTE sum OF filesize ON report
COMPUTE sum OF used ON report
COMPUTE sum OF free ON report
SELECT
DECODE(x.online$,
1,x.name,
65537, substr(rpad(x.name,9),1,9)||' (TEMP)',
substr(rpad(x.name,9),1,9)||' (OFF)') tablespace
, a.file_name filename
, ROUND(f.blocks*&xbs) filesize
, NVL(ROUND(SUM(s.length*&xbs),1),0) used
, ROUND(((f.blocks*&xbs)) - nvl(sum(s.length*&xbs),0), 1) free
, NVL(TRUNC(ROUND(SUM(s.length*&xbs) / (f.blocks*&xbs) * 100, 1)),0) pct_used
FROM
sys.dba_data_files A
, sys.uet$ s
, sys.file$ f
, sys.ts$ x
WHERE
x.ts# = f.ts#
AND x.online$ IN (1,2,65537)
AND f.status$ = 2
AND f.ts# = s.ts# (+)
AND f.file# = s.file# (+)
AND f.file# = a.file_id
GROUP BY
x.name
, x.online$
, f.blocks
, A.file_name
, a.file_id
/

181
idev/dba_file_use.sql Normal file
View File

@@ -0,0 +1,181 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : dba_file_use.sql |
-- | CLASS : Database Administration |
-- | PURPOSE : Reports on all datafiles/controlfiles/redo log files. This |
-- | script was designed to work with Oracle8i or higher. It will |
-- | include true TEMPORARY tablespaces. (i.e. use of "tempfiles") |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET TERMOUT OFF;
COLUMN current_instance NEW_VALUE current_instance NOPRINT;
SELECT rpad(instance_name, 17) current_instance FROM v$instance;
SET TERMOUT ON;
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Report : File Usage |
PROMPT | Instance : &current_instance |
PROMPT +------------------------------------------------------------------------+
SET ECHO OFF
SET FEEDBACK 6
SET HEADING ON
SET LINESIZE 180
SET PAGESIZE 50000
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
COLUMN db NEW_VALUE xdb NOPRINT FORMAT a1
COLUMN type FORMAT a8 HEADING 'Type'
COLUMN tablespace FORMAT a30 HEADING 'Tablspace'
COLUMN filename FORMAT a75 HEADING 'Filename'
COLUMN filesize FORMAT 9,999,999,999,999 HEADING 'File Size'
COLUMN stat FORMAT a10 HEADING 'Status'
COLUMN seq FORMAT 9999999 HEADING 'Sequence'
COLUMN arc FORMAT a4 HEADING 'Archived'
SET TERMOUT OFF
SELECT name db
FROM v$database;
SET TERMOUT ON
SELECT
'Data' type
, tablespace_name tablespace
, REPLACE(file_name,'?','&xdb') filename
, bytes filesize
, DECODE(status,'AVAILABLE','Available','INVALID','Invalid','****') stat
, 0 seq
, '' arc
FROM dba_data_files
UNION
SELECT
'Redo'
, 'Grp ' || a.group#
, member
, bytes
, DECODE(b.status,'CURRENT','Current','INACTIVE','Inactive','UNUSED','Unused','****')
, sequence#
, archived
FROM
v$logfile a
, v$log b
WHERE
a.group# = b.group#
UNION
SELECT
'Parm'
, 'Ctrl 1'
, REPLACE(NVL(LTRIM(SUBSTR(value,1,instr(value||',',',',1,1)-1)),' (none)'),
'?','&xdb') file_name
, 0
, ''
, 0
, ''
FROM
v$parameter
WHERE
name = 'control_files'
UNION
SELECT
'Parm'
, 'Ctrl 2'
, REPLACE(nvl(ltrim(substr(value,instr(value||',',',',1,1)+1,
instr(value||',',',',1,2)-instr(value||',',',',1,1)-1)),' (none)'),
'?' ,'&xdb') file_name
, 0
, ''
, 0
, ''
FROM
v$parameter
WHERE
name = 'control_files'
UNION
SELECT
'Parm'
, 'Ctrl 3'
, REPLACE(nvl(ltrim(substr(value,instr(value||',',',',1,2)+1,
instr(value||',',',',1,3)-instr(value||',',',',1,2)-1)),' (none)'),
'?','&xdb') file_name
, 0
, ''
, 0
, ''
FROM
v$parameter
WHERE
name = 'control_files'
UNION
SELECT
'Parm'
, 'Ctrl 4'
, REPLACE(nvl(ltrim(substr(value,instr(value||',',',',1,3)+1,
instr(value||',',',',1,4)-instr(value||',',',',1,3)-1)),' (none)'),
'?','&xdb') file_name
, 0
, ''
, 0
, ''
FROM
v$parameter
WHERE
name = 'control_files'
UNION
SELECT
'Parm'
, 'Ifile'
, REPLACE(value,'?','&xdb') file_name
, 0
, ''
, 0
, ''
FROM
v$parameter
WHERE
name = 'ifile'
UNION
SELECT
'Parm'
, 'Archive'
, DECODE(d.log_mode, 'ARCHIVELOG',
REPLACE(p.value,'?','&xdb') || ' - ENABLED',
REPLACE(p.value,'?','&xdb') || ' - Disabled') file_name
, 0
, ''
, 0
, ''
FROM
v$parameter p
, v$database d
WHERE
p.name = 'log_archive_dest'
UNION
SELECT
'Tempfile' type
, tablespace_name
, REPLACE(file_name,'?','$input{Oracle_SID_Name}') tempfile_name
, bytes
, DECODE(status,'AVAILABLE','Available','INVALID','Invalid','****') stat
, 0
, ''
FROM dba_temp_files
ORDER BY 1,2,3
/

174
idev/dba_file_use_7.sql Normal file
View File

@@ -0,0 +1,174 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : dba_file_use_7.sql |
-- | CLASS : Database Administration |
-- | PURPOSE : Reports on all datafiles/controlfiles/redo log files. This |
-- | script was designed to work with Oracle7 and Oracle8. This |
-- | script can be run against higher database versions (i.e. |
-- | Oracle8i) but will not return information about true TEMPORARY |
-- | tablespaces. (i.e. use of "tempfiles") |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET TERMOUT OFF;
COLUMN current_instance NEW_VALUE current_instance NOPRINT;
SELECT rpad(instance_name, 17) current_instance FROM v$instance;
SET TERMOUT ON;
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Report : File Usage |
PROMPT | Instance : &current_instance |
PROMPT +------------------------------------------------------------------------+
SET ECHO OFF
SET FEEDBACK 6
SET HEADING ON
SET LINESIZE 180
SET PAGESIZE 50000
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
COLUMN db NEW_VALUE xdb NOPRINT FORMAT a1
COLUMN type FORMAT a8 HEADING 'Type'
COLUMN tablespace FORMAT a30 HEADING 'Tablspace'
COLUMN filename FORMAT a55 HEADING 'Filename'
COLUMN filesize FORMAT 9,999,999,999,999 HEADING 'File Size'
COLUMN stat FORMAT a10 HEADING 'Status'
COLUMN seq FORMAT 9999 HEADING 'Sequence'
COLUMN arc FORMAT a4 HEADING 'Archived'
SET TERMOUT OFF
SELECT name db
FROM v$database;
SET TERMOUT ON
SELECT
'Data' type
, tablespace_name tablespace
, REPLACE(file_name,'?','&xdb') filename
, bytes filesize
, DECODE(status,'AVAILABLE','Available','INVALID','Invalid','****') stat
, 0 seq
, '' arc
FROM dba_data_files
UNION
SELECT
'Redo'
, 'Grp ' || a.group#
, member
, bytes
, DECODE(b.status,'CURRENT','Current','INACTIVE','Inactive','UNUSED','Unused','****')
, sequence#
, archived
FROM
v$logfile a
, v$log b
WHERE
a.group# = b.group#
UNION
SELECT
'Parm'
, 'Ctrl 1'
, REPLACE(NVL(LTRIM(SUBSTR(value,1,instr(value||',',',',1,1)-1)),' (none)'),
'?','&xdb') file_name
, 0
, ''
, 0
, ''
FROM
v$parameter
WHERE
name = 'control_files'
UNION
SELECT
'Parm'
, 'Ctrl 2'
, REPLACE(nvl(ltrim(substr(value,instr(value||',',',',1,1)+1,
instr(value||',',',',1,2)-instr(value||',',',',1,1)-1)),' (none)'),
'?' ,'&xdb') file_name
, 0
, ''
, 0
, ''
FROM
v$parameter
WHERE
name = 'control_files'
UNION
SELECT
'Parm'
, 'Ctrl 3'
, REPLACE(nvl(ltrim(substr(value,instr(value||',',',',1,2)+1,
instr(value||',',',',1,3)-instr(value||',',',',1,2)-1)),' (none)'),
'?','&xdb') file_name
, 0
, ''
, 0
, ''
FROM
v$parameter
WHERE
name = 'control_files'
UNION
SELECT
'Parm'
, 'Ctrl 4'
, REPLACE(nvl(ltrim(substr(value,instr(value||',',',',1,3)+1,
instr(value||',',',',1,4)-instr(value||',',',',1,3)-1)),' (none)'),
'?','&xdb') file_name
, 0
, ''
, 0
, ''
FROM
v$parameter
WHERE
name = 'control_files'
UNION
SELECT
'Parm'
, 'Ifile'
, REPLACE(value,'?','&xdb') file_name
, 0
, ''
, 0
, ''
FROM
v$parameter
WHERE
name = 'ifile'
UNION
SELECT
'Parm'
, 'Archive'
, DECODE(d.log_mode, 'ARCHIVELOG',
REPLACE(p.value,'?','&xdb') || ' - ENABLED',
REPLACE(p.value,'?','&xdb') || ' - Disabled') file_name
, 0
, ''
, 0
, ''
FROM
v$parameter p
, v$database d
WHERE
p.name = 'log_archive_dest'
ORDER BY 1,2,3
/

84
idev/dba_files.sql Normal file
View File

@@ -0,0 +1,84 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : dba_files.sql |
-- | CLASS : Database Administration |
-- | PURPOSE : Reports on all data files within each tablespaces. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET TERMOUT OFF;
COLUMN current_instance NEW_VALUE current_instance NOPRINT;
SELECT rpad(instance_name, 17) current_instance FROM v$instance;
SET TERMOUT ON;
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Report : Data File Report |
PROMPT | Instance : &current_instance |
PROMPT +------------------------------------------------------------------------+
SET ECHO OFF
SET FEEDBACK 6
SET HEADING ON
SET LINESIZE 180
SET PAGESIZE 50000
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
COLUMN tablespace FORMAT a30 HEADING 'Tablespace Name'
COLUMN filename FORMAT a75 HEADING 'Filename'
COLUMN filesize FORMAT 9,999,999,999,999 HEADING 'File Size'
COLUMN autoextensible FORMAT a4 HEADING 'Auto'
COLUMN increment_by FORMAT 999,999,999,999 HEADING 'Next'
COLUMN maxbytes FORMAT 999,999,999,999 HEADING 'Max'
BREAK ON report
COMPUTE sum OF filesize ON report
SELECT /*+ ordered */
d.tablespace_name tablespace
, d.file_name filename
, d.bytes filesize
, d.autoextensible autoextensible
, d.increment_by * e.value increment_by
, d.maxbytes maxbytes
FROM
sys.dba_data_files d
, v$datafile v
, (SELECT value
FROM v$parameter
WHERE name = 'db_block_size') e
WHERE
(d.file_name = v.name)
UNION
SELECT
d.tablespace_name tablespace
, d.file_name filename
, d.bytes filesize
, d.autoextensible autoextensible
, d.increment_by * e.value increment_by
, d.maxbytes maxbytes
FROM
sys.dba_temp_files d
, (SELECT value
FROM v$parameter
WHERE name = 'db_block_size') e
ORDER BY
1
, 2
/

106
idev/dba_files_all.sql Normal file
View File

@@ -0,0 +1,106 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : dba_files_all.sql |
-- | CLASS : Database Administration |
-- | PURPOSE : Reports on all data files, online redo log files, and control |
-- | files within the database. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET TERMOUT OFF;
COLUMN current_instance NEW_VALUE current_instance NOPRINT;
SELECT rpad(instance_name, 17) current_instance FROM v$instance;
SET TERMOUT ON;
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Report : Data File Report (all physical files) |
PROMPT | Instance : &current_instance |
PROMPT +------------------------------------------------------------------------+
SET ECHO OFF
SET FEEDBACK 6
SET HEADING ON
SET LINESIZE 180
SET PAGESIZE 50000
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
COLUMN tablespace FORMAT a30 HEADING 'Tablespace Name / File Class'
COLUMN filename FORMAT a75 HEADING 'Filename'
COLUMN filesize FORMAT 9,999,999,999,999 HEADING 'File Size'
COLUMN autoextensible FORMAT a4 HEADING 'Auto'
COLUMN increment_by FORMAT 999,999,999,999 HEADING 'Next'
COLUMN maxbytes FORMAT 999,999,999,999 HEADING 'Max'
BREAK ON report
COMPUTE sum OF filesize ON report
SELECT /*+ ordered */
d.tablespace_name tablespace
, d.file_name filename
, d.bytes filesize
, d.autoextensible autoextensible
, d.increment_by * e.value increment_by
, d.maxbytes maxbytes
FROM
sys.dba_data_files d
, v$datafile v
, (SELECT value
FROM v$parameter
WHERE name = 'db_block_size') e
WHERE
(d.file_name = v.name)
UNION
SELECT
d.tablespace_name tablespace
, d.file_name filename
, d.bytes filesize
, d.autoextensible autoextensible
, d.increment_by * e.value increment_by
, d.maxbytes maxbytes
FROM
sys.dba_temp_files d
, (SELECT value
FROM v$parameter
WHERE name = 'db_block_size') e
UNION
SELECT
'[ ONLINE REDO LOG ]'
, a.member
, b.bytes
, null
, TO_NUMBER(null)
, TO_NUMBER(null)
FROM
v$logfile a
, v$log b
WHERE
a.group# = b.group#
UNION
SELECT
'[ CONTROL FILE ]'
, a.name
, TO_NUMBER(null)
, null
, TO_NUMBER(null)
, TO_NUMBER(null)
FROM
v$controlfile a
ORDER BY 1,2
/

View File

@@ -0,0 +1,108 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : dba_free_space_frag.sql |
-- | CLASS : Database Administration |
-- | PURPOSE : Report free space fragmentation. |
-- | !!! THIS SCRIPT MUST BE RUN AS THE SYS USER !!! |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
CONNECT / AS SYSDBA
SET TERMOUT OFF;
COLUMN current_instance NEW_VALUE current_instance NOPRINT;
SELECT rpad(instance_name, 17) current_instance FROM v$instance;
SET TERMOUT ON;
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Report : Free Space Fragmentation Report |
PROMPT | Instance : &current_instance |
PROMPT +------------------------------------------------------------------------+
CREATE OR REPLACE VIEW free_space (
tablespace
, pieces
, free_bytes
, free_blocks
, largest_bytes
, largest_blks
, fsfi
, data_file
, file_id
, total_blocks
)
AS
SELECT
a.tablespace_name
, COUNT(*)
, SUM(a.bytes)
, SUM(a.blocks)
, MAX(a.bytes)
, MAX(a.blocks)
, SQRT(MAX(a.blocks)/SUM(a.blocks))*(100/SQRT(SQRT(count(a.blocks))))
, UPPER(b.file_name)
, MAX(a.file_id)
, MAX(b.blocks)
FROM
sys.dba_free_space a
, sys.dba_data_files b
WHERE
a.file_id = b.file_id
GROUP BY
a.tablespace_name, b.file_name
/
CLEAR COLUMNS
SET ECHO OFF
SET FEEDBACK OFF
SET HEADING ON
SET LINESIZE 180
SET PAGESIZE 50000
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
BREAK ON tablespace SKIP 2 ON REPORT
COMPUTE SUM OF total_blocks ON tablespace
COMPUTE SUM OF free_blocks ON tablespace
COMPUTE SUM OF free_blocks ON report
COMPUTE SUM OF total_blocks ON report
COLUMN tablespace HEADING "Tablespace" FORMAT a30
COLUMN file_id HEADING File# FORMAT 99999
COLUMN pieces HEADING Frag FORMAT 9999
COLUMN free_bytes HEADING 'Free Byte'
COLUMN free_blocks HEADING 'Free Blk' FORMAT 999,999,999
COLUMN largest_bytes HEADING 'Biggest Bytes'
COLUMN largest_blks HEADING 'Biggest Blks' FORMAT 999,999,999
COLUMN data_file HEADING 'File Name' FORMAT a75
COLUMN total_blocks HEADING 'Total Blocks' FORMAT 999,999,999
SELECT
tablespace
, data_file
, pieces
, free_blocks
, largest_blks
, file_id
, total_blocks
FROM
free_space
/
DROP VIEW free_space
/

175
idev/dba_highwater_mark.sql Normal file
View File

@@ -0,0 +1,175 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : dba_highwater_mark.sql |
-- | CLASS : Database Administration |
-- | PURPOSE : Determine the highwater mark of a given table. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
analyze table &owner.&table_name compute statistics
/
SELECT
blocks
FROM
dba_segments
WHERE
owner = '&&owner'
AND segment_name = '&&table_name'
/
SELECT
empty_blocks
FROM
dba_tables
WHERE
owner = '&&owner'
AND table_name = '&&table_name'
/
HIGHWATER_MARK = dba_segments.blocks - dba_tables.empty_blocks - 1
----------------------------------------------------------------
What is the High Water Mark?
----------------------------
All Oracle segments have an upper boundary containing the data within
the segment. This upper boundary is called the "high water mark" or HWM.
The high water mark is an indicator that marks blocks that are allocated
to a segment, but are not used yet. This high water mark typically bumps
up at 5 data blocks at a time. It is reset to "zero" (position to the start
of the segment) when a TRUNCATE command is issued. So you can have empty
blocks below the high water mark, but that means that the block has been
used (and is probably empty caused by deletes). Oracle does not move the
HWM, nor does it *shrink* tables, as a result of deletes. This is also
true of Oracle8. Full table scans typically read up to the high water mark.
Data files do not have a high water mark; only segments do have them.
How to determine the high water mark
------------------------------------
To view the high water mark of a particular table::
ANALYZE TABLE <tablename> ESTIMATE/COMPUTE STATISTICS;
This will update the table statistics. After generating the statistics,
to determine the high water mark:
SELECT blocks, empty_blocks, num_rows
FROM user_tables
WHERE table_name = <tablename>;
BLOCKS represents the number of blocks 'ever' used by the segment.
EMPTY_BLOCKS represents only the number of blocks above the 'HIGH WATER MARK'
.
Deleting records doesn't lower the high water mark. Therefore, deleting
records doesn't raise the EMPTY_BLOCKS figure.
Let us take the following example based on table BIG_EMP1 which
has 28672 rows (Oracle 8.0.6):
SQL> connect system/manager
Connected.
SQL> SELECT segment_name,segment_type,blocks
2> FROM dba_segments
3> WHERE segment_name='BIG_EMP1';
SEGMENT_NAME SEGMENT_TYPE BLOCKS EXTENTS
----------------------------- ----------------- ---------- -------
BIG_EMP1 TABLE 1024 2
1 row selected.
SQL> connect scott/tiger
SQL> ANALYZE TABLE big_emp1 ESTIMATE STATISTICS;
Statement processed.
SQL> SELECT table_name,num_rows,blocks,empty_blocks
2> FROM user_tables
3> WHERE table_name='BIG_EMP1';
TABLE_NAME NUM_ROWS BLOCKS EMPTY_BLOCKS
------------------------------ ---------- ---------- ------------
BIG_EMP1 28672 700 323
1 row selected.
Note: BLOCKS + EMPTY_BLOCKS (700+323=1023) is one block less than
DBA_SEGMENTS.BLOCKS. This is because one block is reserved for the
segment header. DBA_SEGMENTS.BLOCKS holds the total number of blocks
allocated to the table. USER_TABLES.BLOCKS holds the total number of
blocks allocated for data.
SQL> SELECT COUNT (DISTINCT
2> DBMS_ROWID.ROWID_BLOCK_NUMBER(rowid)||
3> DBMS_ROWID.ROWID_RELATIVE_FNO(rowid)) "Used"
4> FROM big_emp1;
Used
----------
700
1 row selected.
SQL> DELETE from big_emp1;
28672 rows processed.
SQL> commit;
Statement processed.
SQL> ANALYZE TABLE big_emp1 ESTIMATE STATISTICS;
Statement processed.
SQL> SELECT table_name,num_rows,blocks,empty_blocks
2> FROM user_tables
3> WHERE table_name='BIG_EMP1';
TABLE_NAME NUM_ROWS BLOCKS EMPTY_BLOCKS
------------------------------ ---------- ---------- ------------
BIG_EMP1 0 700 323
1 row selected.
SQL> SELECT COUNT (DISTINCT
2> DBMS_ROWID.ROWID_BLOCK_NUMBER(rowid)||
3> DBMS_ROWID.ROWID_RELATIVE_FNO(rowid)) "Used"
4> FROM big_emp1;
Used
----------
0
1 row selected.
SQL> TRUNCATE TABLE big_emp1;
Statement processed.
SQL> ANALYZE TABLE big_emp1 ESTIMATE STATISTICS;
Statement processed.
SQL> SELECT table_name,num_rows,blocks,empty_blocks
2> FROM user_tables
3> WHERE table_name='BIG_EMP1';
TABLE_NAME NUM_ROWS BLOCKS EMPTY_BLOCKS
------------------------------ ---------- ---------- ------------
BIG_EMP1 0 0 511
1 row selected.
SQL> connect system/manager
Connected.
SQL> SELECT segment_name,segment_type,blocks
2> FROM dba_segments
3> WHERE segment_name='BIG_EMP1';
SEGMENT_NAME SEGMENT_TYPE BLOCKS EXTENTS
----------------------------- ----------------- ---------- -------
BIG_EMP1 TABLE 512 1
1 row selected.
NOTE:
----
TRUNCATE has also deallocated the space from the deleted rows.
To retain the space from the deleted rows allocated to the table use:
SQL> TRUNCATE TABLE big_emp1 REUSE STORAGE

View File

@@ -0,0 +1,62 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : dba_index_fragmentation.sql |
-- | CLASS : Database Administration |
-- | PURPOSE : To ascertain index fragmentation. As a rule of thumb if 10-15% |
-- | of the table data changes, then you should consider rebuilding |
-- | the index. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET ECHO OFF
SET FEEDBACK OFF
SET HEADING ON
SET LINESIZE 180
SET PAGESIZE 50000
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Calculate Index Fragmentation for a Specified Index |
PROMPT +------------------------------------------------------------------------+
PROMPT
ACCEPT index_name CHAR prompt 'Enter index name [SCHEMA].index_name : '
ANALYZE INDEX &index_name VALIDATE STRUCTURE;
COLUMN name HEADING 'Index Name' FORMAT a30
COLUMN del_lf_rows HEADING 'Deleted|Leaf Rows' FORMAT 999,999,999,999,999
COLUMN lf_rows_used HEADING 'Used|Leaf Rows' FORMAT 999,999,999,999,999
COLUMN ibadness HEADING '% Deleted|Leaf Rows' FORMAT 999.99999
SELECT
name
, del_lf_rows
, lf_rows - del_lf_rows lf_rows_used
, TO_CHAR( del_lf_rows /(DECODE(lf_rows,0,0.01,lf_rows))*100,'999.99999') ibadness
FROM index_stats
/
PROMPT
PROMPT Consider rebuilding any index if % of Deleted Leaf Rows is > 20%
PROMPT
UNDEFINE index_name
SET FEEDBACK 6

View File

@@ -0,0 +1,108 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : dba_index_schema_fragmentation_report.sql |
-- | CLASS : Database Administration |
-- | PURPOSE : Rebuilds an index to determine how fragmented it is. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Index Fragmentation Report for a Specified Schema |
PROMPT |------------------------------------------------------------------------|
PROMPT | Rebuild the index when: |
PROMPT | [*] deleted entries represent 20% or more of the current entries |
PROMPT | [*] the index depth is more then 4 levels |
PROMPT | |
PROMPT | Possible candidate for bitmap index: |
PROMPT | [*] when distinctiveness is more than 99% |
PROMPT +------------------------------------------------------------------------+
PROMPT
ACCEPT schema CHAR prompt 'Schema name (% allowed) : '
PROMPT
SPOOL index_schema_fragmentation_report_&schema..lst
SET SERVEROUTPUT ON
SET ECHO OFF
SET FEEDBACK 6
SET HEADING ON
SET LINESIZE 180
SET PAGESIZE 50000
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
DECLARE
c_name INTEGER;
ignore INTEGER;
height index_stats.height%TYPE := 0;
lf_rows index_stats.lf_rows%TYPE := 0;
del_lf_rows index_stats.del_lf_rows%TYPE := 0;
distinct_keys index_stats.distinct_keys%TYPE := 0;
CURSOR c_indx IS
SELECT owner, table_name, index_name
FROM dba_indexes
WHERE owner LIKE upper('&schema')
AND owner NOT IN ('SYS','SYSTEM');
BEGIN
dbms_output.enable (1000000);
dbms_output.put_line ('Owner Index Name % Deleted Entries Blevel Distinctiveness');
dbms_output.put_line ('--------------- --------------------------------------- ----------------- ------ ---------------');
c_name := DBMS_SQL.OPEN_CURSOR;
FOR r_indx in c_indx LOOP
DBMS_SQL.PARSE(c_name,'analyze index ' || r_indx.owner || '.' || r_indx.index_name || ' validate structure', DBMS_SQL.NATIVE);
ignore := DBMS_SQL.EXECUTE(c_name);
SELECT
height
, DECODE (lf_rows, 0, 1, lf_rows)
, del_lf_rows
, DECODE (distinct_keys, 0, 1, distinct_keys)
INTO
height
, lf_rows
, del_lf_rows
, distinct_keys
FROM index_stats;
--
-- Index is considered as candidate for rebuild when :
-- - when deleted entries represent 20% or more of the current entries
-- - when the index depth is more then 4 levels.(height starts counting from 1 so > 5)
-- Index is (possible) candidate for a bitmap index when :
-- - distinctiveness is more than 99%
--
IF ( height > 5 ) OR ( (del_lf_rows/lf_rows) > 0.2 ) THEN
dbms_output.put_line ( RPAD(r_indx.owner, 16, ' ')
|| RPAD(r_indx.index_name, 40, ' ')
|| LPAD(ROUND((del_lf_rows/lf_rows)*100,3),17,' ')
|| LPAD(height-1,7,' ')
|| LPAD(ROUND((lf_rows-distinct_keys)*100/lf_rows,3),16,' '));
END IF;
END LOOP;
DBMS_SQL.CLOSE_CURSOR(c_name);
END;
/
SPOOL OFF
PROMPT Report written to index_schema_fragmentation_report_&schema..lst
PROMPT

92
idev/dba_index_stats.sql Normal file
View File

@@ -0,0 +1,92 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : dba_index_stats.sql |
-- | CLASS : Database Administration |
-- | PURPOSE : Report index statistics. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET ECHO OFF
SET FEEDBACK OFF
SET HEADING OFF
SET LINESIZE 180
SET PAGESIZE 50000
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Calculate Index Statistics for a Specified Index |
PROMPT +------------------------------------------------------------------------+
PROMPT
ACCEPT index_name CHAR prompt 'Enter index name [SCHEMA].index_name : '
COLUMN name newline
COLUMN headsep newline
COLUMN height newline
COLUMN blocks newline
COLUMN lf_rows newline
COLUMN lf_blks newline
COLUMN lf_rows_len newline
COLUMN lf_blk_len newline
COLUMN br_rows newline
COLUMN br_blks newline
COLUMN br_rows_len newline
COLUMN br_blk_len newline
COLUMN del_lf_rows newline
COLUMN del_lf_rows_len newline
COLUMN distinct_keys newline
COLUMN most_repeated_key newline
COLUMN btree_space newline
COLUMN used_space newline
COLUMN pct_used newline
COLUMN rows_per_key newline
COLUMN blks_gets_per_access newline
ANALYZE INDEX &index_name VALIDATE STRUCTURE;
SELECT
name
, '----------------------------------------------------------------------------' headsep
, 'height ' ||to_char(height, '999,999,990') height
, 'blocks ' ||to_char(blocks, '999,999,990') blocks
, 'del_lf_rows ' ||to_char(del_lf_rows,'999,999,990') del_lf_rows
, 'del_lf_rows_len ' ||to_char(del_lf_rows_len,'999,999,990') del_lf_rows_len
, 'distinct_keys ' ||to_char(distinct_keys,'999,999,990') distinct_keys
, 'most_repeated_key ' ||to_char(most_repeated_key,'999,999,990') most_repeated_key
, 'btree_space ' ||to_char(btree_space,'999,999,990') btree_space
, 'used_space ' ||to_char(used_space,'999,999,990') used_space
, 'pct_used ' ||to_char(pct_used,'990') pct_used
, 'rows_per_key ' ||to_char(rows_per_key,'999,999,990') rows_per_key
, 'blks_gets_per_access ' ||to_char(blks_gets_per_access,'999,999,990') blks_gets_per_access
, 'lf_rows ' ||to_char(lf_rows, '999,999,990') || ' ' || +
'br_rows ' ||to_char(br_rows, '999,999,990') br_rows
, 'lf_blks ' ||to_char(lf_blks, '999,999,990') || ' ' || +
'br_blks ' ||to_char(br_blks, '999,999,990') br_blks
, 'lf_rows_len ' ||to_char(lf_rows_len,'999,999,990') || ' ' || +
'br_rows_len ' ||to_char(br_rows_len,'999,999,990') br_rows_len
, 'lf_blk_len ' ||to_char(lf_blk_len, '999,999,990') || ' ' || +
'br_blk_len ' ||to_char(br_blk_len, '999,999,990') br_blk_len
FROM
index_stats
/
UNDEFINE index_name
SET FEEDBACK 6
SET HEADING ON

View File

@@ -0,0 +1,63 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : dba_invalid_objects.sql |
-- | CLASS : Database Administration |
-- | PURPOSE : Provide a detailed report of all invalid objects in the |
-- | database. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET TERMOUT OFF;
COLUMN current_instance NEW_VALUE current_instance NOPRINT;
SELECT rpad(instance_name, 17) current_instance FROM v$instance;
SET TERMOUT ON;
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Report : Invalid Objects |
PROMPT | Instance : &current_instance |
PROMPT +------------------------------------------------------------------------+
SET ECHO OFF
SET FEEDBACK 6
SET HEADING ON
SET LINESIZE 180
SET PAGESIZE 50000
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
COLUMN owner FORMAT a25 HEADING 'Owner'
COLUMN object_name FORMAT a30 HEADING 'Object Name'
COLUMN object_type FORMAT a20 HEADING 'Object Type'
COLUMN status FORMAT a10 HEADING 'Status'
BREAK ON owner SKIP 2 ON report
COMPUTE count LABEL "" OF object_name ON owner
COMPUTE count LABEL "Grand Total: " OF object_name ON report
SELECT
owner
, object_name
, object_type
, status
FROM dba_objects
WHERE status <> 'VALID'
ORDER BY owner, object_name
/

View File

@@ -0,0 +1,62 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : dba_invalid_objects_summary.sql |
-- | CLASS : Database Administration |
-- | PURPOSE : Provides a summary report of all invalid objects in the |
-- | database. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET TERMOUT OFF;
COLUMN current_instance NEW_VALUE current_instance NOPRINT;
SELECT rpad(instance_name, 17) current_instance FROM v$instance;
SET TERMOUT ON;
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Report : Invalid Objects Summary |
PROMPT | Instance : &current_instance |
PROMPT +------------------------------------------------------------------------+
SET ECHO OFF
SET FEEDBACK 6
SET HEADING ON
SET LINESIZE 180
SET PAGESIZE 50000
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
COLUMN owner FORMAT a25 HEADING 'Owner'
COLUMN object_name FORMAT a30 HEADING 'Object Name'
COLUMN object_type FORMAT a20 HEADING 'Object Type'
COLUMN count FORMAT 999,999,999 HEADING 'Count'
BREAK ON owner SKIP 2 ON REPORT
COMPUTE sum LABEL "Count: " OF count ON owner
COMPUTE sum LABEL "Grand Total: " OF count ON report
SELECT
owner
, object_type
, count(*) Count
FROM dba_objects
WHERE status <> 'VALID'
GROUP BY owner, object_type
/

61
idev/dba_jobs.sql Normal file
View File

@@ -0,0 +1,61 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : dba_jobs.sql |
-- | CLASS : Database Administration |
-- | PURPOSE : Provides summary report on all registered and scheduled jobs. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET TERMOUT OFF;
COLUMN current_instance NEW_VALUE current_instance NOPRINT;
SELECT rpad(instance_name, 17) current_instance FROM v$instance;
SET TERMOUT ON;
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Report : Oracle Jobs |
PROMPT | Instance : &current_instance |
PROMPT +------------------------------------------------------------------------+
SET ECHO OFF
SET FEEDBACK 6
SET HEADING ON
SET LINESIZE 180
SET PAGESIZE 50000
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
COLUMN job FORMAT 9999999 HEADING 'Job ID'
COLUMN username FORMAT a20 HEADING 'User'
COLUMN what FORMAT a30 HEADING 'What'
COLUMN next_date HEADING 'Next Run Date'
COLUMN interval FORMAT a30 HEADING 'Interval'
COLUMN last_date HEADING 'Last Run Date'
COLUMN failures HEADING 'Failures'
COLUMN broken FORMAT a7 HEADING 'Broken?'
SELECT
job
, log_user username
, what
, TO_CHAR(next_date, 'DD-MON-YYYY HH24:MI:SS') next_date
, interval
, TO_CHAR(last_date, 'DD-MON-YYYY HH24:MI:SS') last_date
, failures
, broken
FROM
dba_jobs;

201
idev/dba_object_cache.sql Normal file
View File

@@ -0,0 +1,201 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : dba_object_cache.sql |
-- | CLASS : Database Administration |
-- | PURPOSE : Summary of objects in the shared pool cache. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET TERMOUT OFF;
COLUMN current_instance NEW_VALUE current_instance NOPRINT;
SELECT rpad(instance_name, 17) current_instance FROM v$instance;
SET TERMOUT ON;
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Report : Summary of Objects in the Shared Pool Cache |
PROMPT | Instance : &current_instance |
PROMPT +------------------------------------------------------------------------+
SET ECHO OFF
SET FEEDBACK 6
SET HEADING ON
SET LINESIZE 180
SET PAGESIZE 50000
SET TERMOUT OFF
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
COLUMN inst_id HEAD "Inst.|ID"
COLUMN owner FORMAT a10 HEAD "Owner"
COLUMN name FORMAT a30 HEAD "Name"
COLUMN db_link FORMAT a7 HEAD "DB Link"
COLUMN namespace FORMAT a25 HEAD "Namespace"
COLUMN type FORMAT a18 HEAD "Type"
COLUMN sharable_mem FORMAT 99,999,999,999 HEAD "Sharable|Memory"
COLUMN loads HEAD "Loads"
COLUMN executions FORMAT 99,999,999 HEAD "Executions"
COLUMN locks HEAD "Locks"
COLUMN pins HEAD "Pins"
COLUMN kept FORMAT a5 HEAD "Kept?"
COLUMN child_latch HEAD "Child Latch"
COLUMN hash_value HEAD "Hash Value"
COLUMN address HEAD "Address"
COLUMN paddress HEAD "Paddress"
COLUMN crsr_plan_hash_value HEAD "Cursor Plan|Hash Value"
COLUMN kglobt02 HEAD "kglobt02"
BREAK ON report
COMPUTE sum OF sharable_mem ON report
DEFINE spool_file=shared_pool_object_cache.lst
SPOOL &spool_file
SELECT
inst_id inst_id
, kglnaown owner
, kglnaobj name
-- , kglnadlk db_link
, DECODE( kglhdnsp
, 0 , 'CURSOR'
, 1 , 'TABLE/PROCEDURE'
, 2 , 'BODY'
, 3 , 'TRIGGER'
, 4 , 'INDEX'
, 5 , 'CLUSTER'
, 6 , 'OBJECT'
, 13, 'JAVA SOURCE'
, 14, 'JAVA RESOURCE'
, 15, 'REPLICATED TABLE OBJECT'
, 16, 'REPLICATION INTERNAL PACKAGE'
, 17, 'CONTEXT POLICY'
, 18, 'PUB_SUB'
, 19, 'SUMMARY'
, 20, 'DIMENSION'
, 21, 'APP CONTEXT'
, 22, 'STORED OUTLINE'
, 23, 'RULESET'
, 24, 'RSRC PLAN'
, 25, 'RSRC CONSUMER GROUP'
, 26, 'PENDING RSRC PLAN'
, 27, 'PENDING RSRC CONSUMER GROUP'
, 28, 'SUBSCRIPTION'
, 29, 'LOCATION'
, 30, 'REMOTE OBJECT'
, 31, 'SNAPSHOT METADATA'
, 32, 'JAVA SHARED DATA'
, 33, 'SECURITY PROFILE'
, 'INVALID NAMESPACE'
) namespace
, DECODE ( BITAND(kglobflg, 3)
, 0, 'NOT LOADED'
, 2, 'NON-EXISTENT'
, 3, 'INVALID STATUS'
, DECODE ( kglobtyp
, 0 , 'CURSOR'
, 1 , 'INDEX'
, 2 , 'TABLE'
, 3 , 'CLUSTER'
, 4 , 'VIEW'
, 5 , 'SYNONYM'
, 6 , 'SEQUENCE'
, 7 , 'PROCEDURE'
, 8 , 'FUNCTION'
, 9 , 'PACKAGE'
, 10, 'NON-EXISTENT'
, 11, 'PACKAGE BODY'
, 12, 'TRIGGER'
, 13, 'TYPE'
, 14, 'TYPE BODY'
, 15, 'OBJECT'
, 16, 'USER'
, 17, 'DBLINK'
, 18, 'PIPE'
, 19, 'TABLE PARTITION'
, 20, 'INDEX PARTITION'
, 21, 'LOB'
, 22, 'LIBRARY'
, 23, 'DIRECTORY'
, 24, 'QUEUE'
, 25, 'INDEX-ORGANIZED TABLE'
, 26, 'REPLICATION OBJECT GROUP'
, 27, 'REPLICATION PROPAGATOR'
, 28, 'JAVA SOURCE'
, 29, 'JAVA CLASS'
, 30, 'JAVA RESOURCE'
, 31, 'JAVA JAR'
, 32, 'INDEX TYPE'
, 33, 'OPERATOR'
, 34, 'TABLE SUBPARTITION'
, 35, 'INDEX SUBPARTITION'
, 36, 'REPLICATED TABLE OBJECT'
, 37, 'REPLICATION INTERNAL PACKAGE'
, 38, 'CONTEXT POLICY'
, 39, 'PUB_SUB'
, 40, 'LOB PARTITION'
, 41, 'LOB SUBPARTITION'
, 42, 'SUMMARY'
, 43, 'DIMENSION'
, 44, 'APP CONTEXT'
, 45, 'STORED OUTLINE'
, 46, 'RULESET'
, 47, 'RSRC PLAN'
, 48, 'RSRC CONSUMER GROUP'
, 49, 'PENDING RSRC PLAN'
, 50, 'PENDING RSRC CONSUMER GROUP'
, 51, 'SUBSCRIPTION'
, 52, 'LOCATION'
, 53, 'REMOTE OBJECT'
, 54, 'SNAPSHOT METADATA'
, 55, 'IFS'
, 56, 'JAVA SHARED DATA'
, 57, 'SECURITY PROFILE'
, 'INVALID TYPE'
)
) type
, kglobhs0 +
kglobhs1 +
kglobhs2 +
kglobhs3 +
kglobhs4 +
kglobhs5 +
kglobhs6 sharable_mem
, kglhdldc loads
, kglhdexc executions
, kglhdlkc locks
, kglobpc0 pins
, DECODE( kglhdkmk
, 0 ,'NO'
, 'YES'
) kept
-- , kglhdclt child_latch
-- , kglnahsh hash_value
-- , kglhdadr address
-- , kglhdpar paddress
-- , kglobt30 crsr_plan_hash_value
-- , kglobt02 kglobt02
FROM x$kglob
/
SPOOL OFF
SET TERMOUT ON
PROMPT
PROMPT Report written to &spool_file
PROMPT

View File

@@ -0,0 +1,62 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : dba_object_search.sql |
-- | CLASS : Database Administration |
-- | PURPOSE : Prompt the user for a query string and look for any object that |
-- | contains that string. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET TERMOUT OFF;
COLUMN current_instance NEW_VALUE current_instance NOPRINT;
SELECT rpad(instance_name, 17) current_instance FROM v$instance;
SET TERMOUT ON;
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Report : Object Search Interface |
PROMPT | Instance : &current_instance |
PROMPT +------------------------------------------------------------------------+
PROMPT
ACCEPT schema CHAR PROMPT 'Enter search string (i.e. GE_LINES) : '
SET ECHO OFF
SET FEEDBACK 6
SET HEADING ON
SET LINESIZE 180
SET PAGESIZE 50000
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
COLUMN owner FORMAT A20 HEADING "Owner"
COLUMN object_name FORMAT A45 HEADING "Object Name"
COLUMN object_type FORMAT A18 HEADING "Object Type"
COLUMN created HEADING "Created"
COLUMN status HEADING "Status"
SELECT
owner
, object_name
, object_type
, TO_CHAR(created, 'DD-MON-YYYY HH24:MI:SS') created
, LPAD(status, 7) status
FROM all_objects
WHERE object_name like UPPER('%&schema%')
ORDER BY owner, object_name, object_type
/

View File

@@ -0,0 +1,63 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : dba_object_summary.sql |
-- | CLASS : Database Administration |
-- | PURPOSE : Provide a summary report of all objects in the database. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET TERMOUT OFF;
COLUMN current_instance NEW_VALUE current_instance NOPRINT;
SELECT rpad(instance_name, 17) current_instance FROM v$instance;
SET TERMOUT ON;
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Report : Object Summary |
PROMPT | Instance : &current_instance |
PROMPT +------------------------------------------------------------------------+
SET ECHO OFF
SET FEEDBACK 6
SET HEADING ON
SET LINESIZE 180
SET PAGESIZE 50000
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
COLUMN owner FORMAT A20 HEADING "Owner"
COLUMN object_type FORMAT A25 HEADING "Object Type"
COLUMN obj_count FORMAT 999,999,999,999 HEADING "Object Count"
BREAK ON report ON owner SKIP 2
COMPUTE sum LABEL "" OF obj_count ON owner
COMPUTE sum LABEL "Grand Total: " OF obj_count ON report
SELECT
owner
, object_type
, count(*) obj_count
FROM
dba_objects
GROUP BY
owner
, object_type
ORDER BY
owner
, object_type
/

51
idev/dba_options.sql Normal file
View File

@@ -0,0 +1,51 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : dba_options.sql |
-- | CLASS : Database Administration |
-- | PURPOSE : Report on all Oracle installed options. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET TERMOUT OFF;
COLUMN current_instance NEW_VALUE current_instance NOPRINT;
SELECT rpad(instance_name, 17) current_instance FROM v$instance;
SET TERMOUT ON;
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Report : Database Options |
PROMPT | Instance : &current_instance |
PROMPT +------------------------------------------------------------------------+
SET ECHO OFF
SET FEEDBACK 6
SET HEADING ON
SET LINESIZE 180
SET PAGESIZE 50000
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
COLUMN parameter FORMAT a45 HEADING 'Option Name'
COLUMN value FORMAT a10 HEADING 'Installed?'
SELECT
parameter
, value
FROM
v$option
ORDER BY
parameter;

View File

@@ -0,0 +1,71 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : dba_owner_to_tablespace.sql |
-- | CLASS : Database Administration |
-- | PURPOSE : Provide a summary report of owner to tablespace for all |
-- | segments in the database. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET TERMOUT OFF;
COLUMN current_instance NEW_VALUE current_instance NOPRINT;
SELECT rpad(instance_name, 17) current_instance FROM v$instance;
SET TERMOUT ON;
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Report : Owner to Tablespace Report |
PROMPT | Instance : &current_instance |
PROMPT +------------------------------------------------------------------------+
SET ECHO OFF
SET FEEDBACK 6
SET HEADING ON
SET LINESIZE 180
SET PAGESIZE 50000
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
COLUMN owner FORMAT a20 HEADING "Owner"
COLUMN tablespace_name FORMAT a30 HEADING "Tablespace Name"
COLUMN segment_type FORMAT a18 HEADING "Segment Type"
COLUMN bytes FORMAT 9,999,999,999,999 HEADING "Size (in Bytes)"
COLUMN seg_count FORMAT 9,999,999,999 HEADING "Segment Count"
BREAK ON report ON owner SKIP 2
COMPUTE sum LABEL "" OF seg_count bytes ON owner
COMPUTE sum LABEL "Grand Total: " OF seg_count bytes ON report
SELECT
owner
, tablespace_name
, segment_type
, sum(bytes) bytes
, count(*) seg_count
FROM
dba_segments
GROUP BY
owner
, tablespace_name
, segment_type
ORDER BY
owner
, tablespace_name
, segment_type
/

View File

@@ -0,0 +1,58 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : dba_plsql_package_size.sql |
-- | CLASS : Database Administration |
-- | PURPOSE : Internal size of PL/SQL Packages. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET TERMOUT OFF;
COLUMN current_instance NEW_VALUE current_instance NOPRINT;
SELECT rpad(instance_name, 17) current_instance FROM v$instance;
SET TERMOUT ON;
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Report : PL/SQL Package Body Size Report |
PROMPT | Instance : &current_instance |
PROMPT +------------------------------------------------------------------------+
SET ECHO OFF
SET FEEDBACK 6
SET HEADING ON
SET LINESIZE 180
SET PAGESIZE 50000
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
COLUMN owner FORMAT a20 HEAD "Owner"
COLUMN name FORMAT a35 HEAD "Name"
COLUMN type FORMAT a18 HEAD "Type"
COLUMN total_bytes FORMAT 999,999,999,999 HEAD "Total bytes"
SELECT
owner
, name
, type
, source_size+code_size+parsed_size+error_size total_bytes
FROM
dba_object_size
WHERE
type = 'PACKAGE BODY'
AND owner NOT IN ('SYS')
ORDER BY
4 DESC;

View File

@@ -0,0 +1,59 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : dba_query_hidden_parameters.sql |
-- | CLASS : Database Administration |
-- | PURPOSE : Reports on all hidden "undocumented" database parameters. You |
-- | must be connected as the SYS user to run this script. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET TERMOUT OFF;
COLUMN current_instance NEW_VALUE current_instance NOPRINT;
SELECT rpad(instance_name, 17) current_instance FROM v$instance;
SET TERMOUT ON;
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Report : Invalid Objects |
PROMPT | Instance : &current_instance |
PROMPT +------------------------------------------------------------------------+
SET ECHO OFF
SET FEEDBACK 6
SET HEADING ON
SET LINESIZE 256
SET PAGESIZE 50000
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
COLUMN ksppinm FORMAT a55 HEAD 'Parameter Name'
COLUMN ksppstvl FORMAT a40 HEAD 'Value'
COLUMN ksppdesc FORMAT a60 HEAD 'Description' TRUNC
SELECT
ksppinm
, ksppstvl
, ksppdesc
FROM
x$ksppi x
, x$ksppcv y
WHERE
x.indx = y.indx
AND TRANSLATE(ksppinm,'_','#') like '#%'
ORDER BY
ksppinm
/

View File

@@ -0,0 +1,20 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : dba_random_number.sql |
-- | CLASS : Database Administration |
-- | PURPOSE : A quick way to produce random numbers using SQL. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SELECT
TRUNC(
(TO_NUMBER(SUBSTR(TO_CHAR(TO_NUMBER(TO_CHAR(SYSDATE,'sssss'))/86399),-7,7))/10000000)*32767
) random
FROM dual;

View File

@@ -0,0 +1,96 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : dba_rebuild_indexes.sql |
-- | CLASS : Database Administration |
-- | PURPOSE : This script generates another script that will include all of |
-- | the ALTER INDEX REBUILD .... commands needed to rebuild a |
-- | tablespaces indexes. This script will prompt the user for the |
-- | tablespace name. This script must be run be a user with the DBA |
-- | role under Oracle7. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET TERMOUT OFF;
COLUMN current_instance NEW_VALUE current_instance NOPRINT;
SELECT rpad(instance_name, 17) current_instance FROM v$instance;
SET TERMOUT ON;
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Report : Rebuild Index Build Script |
PROMPT | Instance : &current_instance |
PROMPT +------------------------------------------------------------------------+
PROMPT
ACCEPT TS_NAME CHAR PROMPT 'Enter the index tablespace name : '
PROMPT
PROMPT Thanks... Creating rebuild index script for tablespace: &TS_NAME
SET ECHO OFF
SET FEEDBACK OFF
SET HEADING OFF
SET LINESIZE 180
SET PAGESIZE 0
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
SET TERMOUT OFF
spool rebuild_&TS_NAME._indexes.sql
SELECT 'REM FILE : rebuild_&TS_NAME._indexes.sql' FROM dual;
SELECT ' ' FROM dual;
SELECT 'REM' FROM dual;
SELECT 'REM ***** ALTER INDEX REBUILD commands for tablespace: &TS_NAME' FROM dual;
SELECT 'REM' FROM dual;
SELECT ' ' FROM dual;
SELECT
'REM +------------------------------------------------------------------------+' || chr(10) ||
'REM | INDEX NAME : ' || owner || '.' || segment_name
|| lpad('|', 58 - (length(owner) + length(segment_name)) )
|| chr(10) ||
'REM | BYTES : ' || bytes
|| lpad ('|', 59-(length(bytes)) ) || chr(10) ||
'REM | EXTENTS : ' || extents
|| lpad ('|', 59-(length(extents)) ) || chr(10) ||
'REM +------------------------------------------------------------------------+' || chr(10) ||
'ALTER INDEX ' || owner || '.' || segment_name || chr(10) ||
' REBUILD ONLINE' || chr(10) ||
' TABLESPACE ' || tablespace_name || chr(10) ||
' STORAGE ( ' || chr(10) ||
' INITIAL ' || initial_extent || chr(10) ||
' NEXT ' || next_extent || chr(10) ||
' MINEXTENTS ' || min_extents || chr(10) ||
' MAXEXTENTS ' || max_extents || chr(10) ||
' PCTINCREASE ' || pct_increase || chr(10) ||
');' || chr(10) || chr(10)
FROM dba_segments
WHERE segment_type = 'INDEX'
AND owner NOT IN ('SYS')
AND tablespace_name = UPPER('&TS_NAME')
ORDER BY owner, bytes DESC
/
SPOOL OFF
SET TERMOUT ON
PROMPT
PROMPT Done... Built the script rebuild_&TS_NAME._indexes.sql
PROMPT

View File

@@ -0,0 +1,60 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : dba_recompile_invalid_objects.sql |
-- | CLASS : Database Administration |
-- | PURPOSE : Dynamically create a SQL script to recompile all INVALID |
-- | objects. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET ECHO OFF
SET FEEDBACK OFF
SET HEADING OFF
SET LINESIZE 180
SET PAGESIZE 0
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
spool compile.sql
SELECT 'alter ' ||
decode(object_type, 'PACKAGE BODY', 'package', object_type) ||
' ' ||
object_name||
' compile' ||
decode(object_type, 'PACKAGE BODY', ' body;', ';')
FROM dba_objects
WHERE status = 'INVALID'
/
spool off
SET ECHO off
SET FEEDBACK off
SET HEADING off
SET LINESIZE 180
SET PAGESIZE 0
SET TERMOUT on
SET TIMING off
SET TRIMOUT on
SET TRIMSPOOL on
SET VERIFY off
@compile
SET FEEDBACK 6
SET HEADING ON

62
idev/dba_registry.sql Normal file
View File

@@ -0,0 +1,62 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : dba_registry.sql |
-- | CLASS : Database Administration |
-- | PURPOSE : Provides summary report on all registered components. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET TERMOUT OFF;
COLUMN current_instance NEW_VALUE current_instance NOPRINT;
SELECT rpad(instance_name, 17) current_instance FROM v$instance;
SET TERMOUT ON;
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Report : Database Registry Components |
PROMPT | Instance : &current_instance |
PROMPT +------------------------------------------------------------------------+
SET ECHO OFF
SET FEEDBACK 6
SET HEADING ON
SET LINESIZE 180
SET PAGESIZE 50000
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
COLUMN comp_id FORMAT a9 HEADING 'Component|ID'
COLUMN comp_name FORMAT a35 HEADING 'Component|Name'
COLUMN version FORMAT a13 HEADING 'Version'
COLUMN status FORMAT a11 HEADING 'Status'
COLUMN modified HEADING 'Modified'
COLUMN Schema FORMAT a15 HEADING 'Schema'
COLUMN procedure FORMAT a45 HEADING 'Procedure'
SELECT
comp_id
, comp_name
, version
, status
, modified
, schema
, procedure
FROM
dba_registry
ORDER BY
comp_id;

View File

@@ -0,0 +1,57 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : dba_related_child_tables.sql |
-- | CLASS : Database Administration |
-- | PURPOSE : Query all child tables related to a given parent table name. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET ECHO OFF
SET FEEDBACK 6
SET HEADING ON
SET LINESIZE 180
SET PAGESIZE 50000
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | All child tables related to a parent table name |
PROMPT +------------------------------------------------------------------------+
PROMPT
ACCEPT table_owner prompt 'Enter parent table owner : '
ACCEPT table_name prompt 'Enter parent table name : '
SELECT
p.table_name PARENT_TABLE_NAME
, c.table_name CHILD_TABLE
FROM
dba_constraints p
, dba_constraints c
WHERE
(p.constraint_type = 'P' OR p.constraint_type = 'U')
AND
(c.constraint_type = 'R')
AND
(p.constraint_name = c.r_constraint_name)
AND
(p.owner = UPPER('&table_owner'))
AND
(p.table_name = UPPER('&table_name'))
ORDER BY 2
/

66
idev/dba_row_size.sql Normal file
View File

@@ -0,0 +1,66 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : dba_row_size.sql |
-- | CLASS : Database Administration |
-- | PURPOSE : Determines the row sizes for all tables in a given schema. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET TERMOUT OFF;
COLUMN current_instance NEW_VALUE current_instance NOPRINT;
SELECT rpad(instance_name, 17) current_instance FROM v$instance;
SET TERMOUT ON;
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Report : Calculate Row Size for Tables in a Specified Schema |
PROMPT | Instance : &current_instance |
PROMPT +------------------------------------------------------------------------+
PROMPT
ACCEPT schema CHAR PROMPT 'Enter schema name : '
SET ECHO OFF
SET FEEDBACK 6
SET HEADING ON
SET LINESIZE 180
SET PAGESIZE 50000
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
COLUMN Tot_Size FORMAT 99,999
COLUMN data_type FORMAT a15
BREAK ON table_name SKIP 2
COMPUTE sum OF Tot_Size ON table_name
COMPUTE sum OF data_length ON table_name
SELECT
table_name
, column_name
, DECODE( DATA_TYPE
, 'NUMBER' , DATA_PRECISION+DATA_SCALE
, 'VARCHAR2' , TO_NUMBER(DATA_LENGTH)
, 'CHAR' , TO_NUMBER(DATA_LENGTH)
, 'DATE' , TO_NUMBER(DATA_LENGTH)) Tot_Size
, DATA_TYPE
FROM dba_tab_columns
WHERE owner = UPPER('&schema')
ORDER BY table_name
, column_id
/

View File

@@ -0,0 +1,66 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : dba_segment_summary.sql |
-- | CLASS : Database Administration |
-- | PURPOSE : Provide a summary report of all segments in the database. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET TERMOUT OFF;
COLUMN current_instance NEW_VALUE current_instance NOPRINT;
SELECT rpad(instance_name, 17) current_instance FROM v$instance;
SET TERMOUT ON;
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Report : Segment Summary Report |
PROMPT | Instance : &current_instance |
PROMPT +------------------------------------------------------------------------+
SET ECHO OFF
SET FEEDBACK 6
SET HEADING ON
SET LINESIZE 180
SET PAGESIZE 50000
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
COLUMN owner FORMAT a20 HEADING "Owner"
COLUMN segment_type FORMAT a18 HEADING "Segment Type"
COLUMN bytes FORMAT 9,999,999,999,999 HEADING "Size (in Bytes)"
COLUMN seg_count FORMAT 9,999,999,999 HEADING "Segment Count"
BREAK ON report ON owner SKIP 2
COMPUTE sum LABEL "" OF seg_count bytes ON owner
COMPUTE sum LABEL "Grand Total: " OF seg_count bytes ON report
SELECT
owner
, segment_type
, sum(bytes) bytes
, count(*) seg_count
FROM
dba_segments
GROUP BY
owner
, segment_type
ORDER BY
owner
, segment_type
/

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

356
idev/dba_table_info.sql Normal file
View File

@@ -0,0 +1,356 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : dba_table_info.sql |
-- | CLASS : Database Administration |
-- | PURPOSE : Prompt the user for a schema and and table name then query all |
-- | metadata about the table. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET TERMOUT OFF;
COLUMN current_instance NEW_VALUE current_instance NOPRINT;
SELECT rpad(instance_name, 17) current_instance FROM v$instance;
SET TERMOUT ON;
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Report : Table Information |
PROMPT | Instance : &current_instance |
PROMPT +------------------------------------------------------------------------+
PROMPT
ACCEPT schema CHAR PROMPT 'Enter table owner : '
ACCEPT table_name CHAR PROMPT 'Enter table name : '
SET ECHO OFF
SET FEEDBACK 6
SET HEADING ON
SET LINESIZE 180
SET LONG 9000
SET PAGESIZE 50000
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | TABLE INFORMATION |
PROMPT +------------------------------------------------------------------------+
COLUMN owner FORMAT a20 HEADING "Owner"
COLUMN table_name FORMAT a30 HEADING "Table Name"
COLUMN tablespace_name FORMAT a30 HEADING "Tablespace"
COLUMN last_analyzed FORMAT a23 HEADING "Last Analyzed"
COLUMN num_rows FORMAT 9,999,999,999,999 HEADING "# of Rows"
SELECT
owner
, table_name
, tablespace_name
, TO_CHAR(last_analyzed, 'DD-MON-YYYY HH24:MI:SS') last_analyzed
, num_rows
FROM
dba_tables
WHERE
owner = UPPER('&schema')
AND table_name = UPPER('&table_name')
/
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | OBJECT INFORMATION |
PROMPT +------------------------------------------------------------------------+
COLUMN object_id HEADING "Object ID"
COLUMN data_object_id HEADING "Data Object ID"
COLUMN created FORMAT A23 HEADING "Created"
COLUMN last_ddl_time FORMAT A23 HEADING "Last DDL"
COLUMN status HEADING "Status"
SELECT
object_id
, data_object_id
, TO_CHAR(created, 'DD-MON-YYYY HH24:MI:SS') created
, TO_CHAR(last_ddl_time, 'DD-MON-YYYY HH24:MI:SS') last_ddl_time
, status
FROM
dba_objects
WHERE
owner = UPPER('&schema')
AND object_name = UPPER('&table_name')
AND object_type = 'TABLE'
/
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | SEGMENT INFORMATION |
PROMPT +------------------------------------------------------------------------+
COLUMN segment_name FORMAT a30 HEADING "Segment Name"
COLUMN partition_name FORMAT a30 HEADING "Partition Name"
COLUMN segment_type FORMAT a16 HEADING "Segment Type"
COLUMN tablespace_name FORMAT a30 HEADING "Tablespace"
COLUMN num_rows FORMAT 9,999,999,999,999 HEADING "Num Rows"
COLUMN bytes FORMAT 9,999,999,999,999 HEADING "Bytes"
COLUMN last_analyzed FORMAT a23 HEADING "Last Analyzed"
SELECT
seg.segment_name segment_name
, null partition_name
, seg.segment_type segment_type
, seg.tablespace_name tablespace_name
, tab.num_rows num_rows
, seg.bytes bytes
, TO_CHAR(tab.last_analyzed, 'DD-MON-YYYY HH24:MI:SS') last_analyzed
from
dba_segments seg
, dba_tables tab
WHERE
seg.owner = UPPER('&schema')
AND seg.segment_name = UPPER('&table_name')
AND seg.segment_name = tab.table_name
AND seg.owner = tab.owner
AND seg.segment_type = 'TABLE'
UNION ALL
SELECT
seg.segment_name segment_name
, seg.partition_name partition_name
, seg.segment_type segment_type
, seg.tablespace_name tablespace_name
, part.num_rows num_rows
, seg.bytes bytes
, TO_CHAR(part.last_analyzed, 'DD-MON-YYYY HH24:MI:SS') last_analyzed
FROM
dba_segments seg
, dba_tab_partitions part
WHERE
part.table_owner = UPPER('&schema')
AND part.table_name = UPPER('&table_name')
AND part.partition_name = seg.partition_name
AND seg.segment_type = 'TABLE PARTITION'
ORDER BY
segment_name
, partition_name
/
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | COLUMNS |
PROMPT +------------------------------------------------------------------------+
COLUMN column_name FORMAT a30 HEADING "Column Name"
COLUMN data_type FORMAT a25 HEADING "Data Type"
COLUMN nullable FORMAT a13 HEADing "Null?"
SELECT
column_name
, DECODE(nullable, 'Y', ' ', 'NOT NULL') nullable
, DECODE(data_type
, 'RAW', data_type || '(' || data_length || ')'
, 'CHAR', data_type || '(' || data_length || ')'
, 'VARCHAR', data_type || '(' || data_length || ')'
, 'VARCHAR2', data_type || '(' || data_length || ')'
, 'NUMBER', NVL2( data_precision
, DECODE( data_scale
, 0
, data_type || '(' || data_precision || ')'
, data_type || '(' || data_precision || ',' || data_scale || ')'
)
, data_type)
, data_type
) data_type
FROM
dba_tab_columns
WHERE
owner = UPPER('&schema')
AND table_name = UPPER('&table_name')
ORDER BY
column_id
/
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | INDEXES |
PROMPT +------------------------------------------------------------------------+
COLUMN index_name FORMAT a40 HEADING "Index Name"
COLUMN column_name FORMAT a30 HEADING "Column Name"
COLUMN column_length HEADING "Column Length"
BREAK ON index_name SKIP 1
SELECT
index_owner || '.' || index_name index_name
, column_name
, column_length
FROM
dba_ind_columns
WHERE
table_owner = UPPER('&schema')
AND table_name = UPPER('&table_name')
ORDER BY
index_name
, column_position
/
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | CONSTRAINTS |
PROMPT +------------------------------------------------------------------------+
COLUMN constraint_name FORMAT a30 HEADING "Constraint Name"
COLUMN constraint_type FORMAT a13 HEADING "Constraint|Type"
COLUMN search_condition FORMAT a30 HEADING "Search Condition"
COLUMN r_constraint_name FORMAT a30 HEADING "R / Constraint Name"
COLUMN delete_rule FORMAT a12 HEADING "Delete Rule"
COLUMN status HEADING "Status"
BREAK ON constraint_name ON constraint_type
SELECT
a.constraint_name
, DECODE(a.constraint_type
, 'P', 'Primary Key'
, 'C', 'Check'
, 'R', 'Referential'
, 'V', 'View Check'
, 'U', 'Unique'
, a.constraint_type
) constraint_type
, b.column_name
, a.search_condition
, NVL2(a.r_owner, a.r_owner || '.' || a.r_constraint_name, null) r_constraint_name
, a.delete_rule
, a.status
FROM
dba_constraints a
, dba_cons_columns b
WHERE
a.owner = UPPER('&schema')
AND a.table_name = UPPER('&table_name')
AND a.constraint_name = b.constraint_name
AND b.owner = UPPER('&schema')
AND b.table_name = UPPER('&table_name')
ORDER BY
a.constraint_name
, b.position
/
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | PARTITIONS (TABLE) |
PROMPT +------------------------------------------------------------------------+
COLUMN partition_name HEADING "Partition Name"
COLUMN column_name FORMAT a30 HEADING "Column Name"
COLUMN tablespace_name FORMAT a30 HEADING "Tablespace"
COLUMN composite FORMAT a9 HEADING "Composite"
COLUMN subpartition_count HEADING "Sub. Part.|Count"
COLUMN logging FORMAT a7 HEADING "Logging"
COLUMN high_value FORMAT a13 HEADING "High Value" TRUNC
BREAK ON partition_name
SELECT
a.partition_name
, b.column_name
, a.tablespace_name
, a.composite
, a.subpartition_count
, a.logging
FROM
dba_tab_partitions a
, dba_part_key_columns b
WHERE
a.table_owner = UPPER('&schema')
AND a.table_name = UPPER('&table_name')
AND RTRIM(b.object_type) = 'TABLE'
AND b.owner = a.table_owner
AND b.name = a.table_name
ORDER BY
a.partition_position
, b.column_position
/
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | PARTITIONS (INDEX) |
PROMPT +------------------------------------------------------------------------+
COLUMN index_name FORMAT a30 HEADING "Index Name"
COLUMN partitioning_type FORMAT a9 HEADING "Type"
COLUMN partition_count FORMAT 99999 HEADING "Part.|Count"
COLUMN partitioning_key_count FORMAT 99999 HEADING "Part.|Key Count"
COLUMN locality FORMAT a8 HEADING "Locality"
COLUMN alignment FORMAT a12 HEADING "Alignment"
SELECT
a.owner || '.' || a.index_name index_name
, b.column_name
, a.partitioning_type
, a.partition_count
, a.partitioning_key_count
, a.locality
, a.alignment
FROM
dba_part_indexes a
, dba_part_key_columns b
WHERE
a.owner = UPPER('&schema')
AND a.table_name = UPPER('&table_name')
AND RTRIM(b.object_type) = 'INDEX'
AND b.owner = a.owner
AND b.name = a.index_name
ORDER BY
a.index_name
, b.column_position
/
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | TRIGGERS |
PROMPT +------------------------------------------------------------------------+
COLUMN trigger_name FORMAT a30 HEADING "Trigger Name"
COLUMN trigger_type FORMAT a18 HEADING "Type"
COLUMN triggering_event FORMAT a9 HEADING "Trig.|Event"
COLUMN referencing_names FORMAT a65 HEADING "Referencing Names" newline
COLUMN when_clause FORMAT a65 HEADING "When Clause" newline
COLUMN trigger_body FORMAT a65 HEADING "Trigger Body" newline
SELECT
owner || '.' || trigger_name trigger_name
, trigger_type
, triggering_event
, status
, referencing_names
, when_clause
, trigger_body
FROM
dba_triggers
WHERE
table_owner = UPPER('&schema')
AND table_name = UPPER('&table_name')
ORDER BY
trigger_name
/

73
idev/dba_tables_all.sql Normal file
View File

@@ -0,0 +1,73 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : dba_tables_all.sql |
-- | CLASS : Database Administration |
-- | PURPOSE : Query all tables (and owners) within the database. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET TERMOUT OFF;
COLUMN current_instance NEW_VALUE current_instance NOPRINT;
SELECT rpad(instance_name, 17) current_instance FROM v$instance;
SET TERMOUT ON;
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Report : All Database Tables |
PROMPT | Instance : &current_instance |
PROMPT +------------------------------------------------------------------------+
SET ECHO OFF
SET FEEDBACK 6
SET HEADING ON
SET LINESIZE 180
SET PAGESIZE 50000
SET TERMOUT OFF
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
COLUMN owner FORMAT a20 HEADING "Owner"
COLUMN table_name FORMAT a30 HEADING "Table Name"
COLUMN tablespace_name FORMAT a30 HEADING "Tablespace"
COLUMN last_analyzed FORMAT a20 HEADING "Last Analyzed"
COLUMN num_rows FORMAT 999,999,999,999 HEADING "# of Rows"
DEFINE spool_file=database_tables.lst
SPOOL &spool_file
SELECT
owner
, table_name
, tablespace_name
, TO_CHAR(last_analyzed, 'DD-MON-YYYY HH24:MI:SS') last_analyzed
, num_rows
FROM
dba_tables
WHERE
owner NOT IN ('SYS', 'SYSTEM')
ORDER BY
owner
, table_name
/
SPOOL OFF
SET TERMOUT ON
PROMPT
PROMPT Report written to &spool_file
PROMPT

View File

@@ -0,0 +1,57 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : dba_tables_current_user.sql |
-- | CLASS : Database Administration |
-- | PURPOSE : Query all tables owned by the currently connected user. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET TERMOUT OFF;
COLUMN current_instance NEW_VALUE current_instance NOPRINT;
COLUMN current_user NEW_VALUE current_user NOPRINT;
SELECT rpad(instance_name, 17) current_instance, rpad(user, 13) current_user FROM v$instance;
SET TERMOUT ON;
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Report : Tables owned by &current_user |
PROMPT | Instance : &current_instance |
PROMPT +------------------------------------------------------------------------+
SET ECHO OFF
SET FEEDBACK 6
SET HEADING ON
SET LINESIZE 180
SET PAGESIZE 50000
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
COLUMN table_name FORMAT a30 HEADING "Table Name"
COLUMN tablespace_name FORMAT a30 HEADING "Tablespace"
COLUMN last_analyzed FORMAT a20 HEADING "Last Analyzed"
COLUMN num_rows FORMAT 999,999,999,990 HEADING "# of Rows"
SELECT
table_name
, tablespace_name
, TO_CHAR(last_analyzed, 'DD-MON-YYYY HH24:MI:SS') last_analyzed
, num_rows
FROM
user_tables
ORDER BY
table_name
/

View File

@@ -0,0 +1,64 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : dba_tables_query_user.sql |
-- | CLASS : Database Administration |
-- | PURPOSE : Prompt the user for a schema and then query all tables within |
-- | that schema. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET TERMOUT OFF;
COLUMN current_instance NEW_VALUE current_instance NOPRINT;
SELECT rpad(instance_name, 17) current_instance FROM v$instance;
SET TERMOUT ON;
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Report : Query Tables for Specified Schema |
PROMPT | Instance : &current_instance |
PROMPT +------------------------------------------------------------------------+
PROMPT
ACCEPT schema CHAR PROMPT 'Enter schema : '
SET ECHO OFF
SET FEEDBACK 6
SET HEADING ON
SET LINESIZE 180
SET PAGESIZE 50000
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
COLUMN owner FORMAT a20 HEADING "Owner"
COLUMN table_name FORMAT a30 HEADING "Table Name"
COLUMN tablespace_name FORMAT a30 HEADING "Tablespace"
COLUMN last_analyzed FORMAT a20 HEADING "Last Analyzed"
COLUMN num_rows FORMAT 999,999,999,999 HEADING "# of Rows"
SELECT
owner
, table_name
, tablespace_name
, TO_CHAR(last_analyzed, 'DD-MON-YYYY HH24:MI:SS') last_analyzed
, num_rows
FROM dba_tables
WHERE owner = UPPER('&schema')
ORDER BY
owner
, table_name
/

View File

@@ -0,0 +1,97 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : dba_tablespace_mapper.sql |
-- | CLASS : Database Administration |
-- | PURPOSE : Report on all USED and FREE SPACE within a tablespace. This is |
-- | a good script to report on tablespace fragmentation. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET TERMOUT OFF;
COLUMN current_instance NEW_VALUE current_instance NOPRINT;
COLUMN current_instance_nt NEW_VALUE current_instance_nt NOPRINT;
SELECT rpad(instance_name, 17) current_instance, instance_name current_instance_nt FROM v$instance;
SET TERMOUT ON;
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Report : Tablespace Mapper |
PROMPT | Instance : &current_instance |
PROMPT +------------------------------------------------------------------------+
PROMPT
ACCEPT tbs_in CHAR PROMPT 'Enter tablespace name : '
SET TERMOUT OFF;
COLUMN tbs NEW_VALUE tbs NOPRINT;
SELECT rpad(upper('&tbs_in'), 30) tbs
FROM dual;
SET TERMOUT ON;
SET ECHO OFF
SET FEEDBACK 6
SET HEADING ON
SET LINESIZE 180
SET PAGESIZE 50000
SET TERMOUT OFF
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
DEFINE fileName=tablespace_mapper
SPOOL &FileName._&current_instance_nt._&tbs_in..txt
COLUMN owner FORMAT a20 HEADING "Owner"
COLUMN object FORMAT a30 HEADING "Object"
COLUMN file_id HEADING "File ID"
COLUMN block_id HEADING "Block ID"
COLUMN bytes FORMAT 999,999,999,999 HEADING "Bytes"
SELECT
'FREE SPACE' owner
, ' ' object
, file_id
, block_id
, bytes
FROM
dba_free_space
WHERE
tablespace_name = UPPER('&tbs_in')
UNION
SELECT
SUBSTR(owner, 1, 20)
, SUBSTR(segment_name, 1, 32)
, file_id
, block_id
, bytes
FROM
dba_extents
WHERE
tablespace_name = UPPER('&tbs_in')
ORDER BY
3
, 4
/
SPOOL off
SET FEEDBACK 6
SET HEADING ON
SET TERMOUT ON
PROMPT
PROMPT Report written to &FileName._&current_instance_nt._&tbs_in..txt
PROMPT

View File

@@ -0,0 +1,70 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : dba_tablespace_to_owner.sql |
-- | CLASS : Database Administration |
-- | PURPOSE : Provide a summary report of tablespace to owner for all |
-- | segments in the database. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET TERMOUT OFF;
COLUMN current_instance NEW_VALUE current_instance NOPRINT;
SELECT rpad(instance_name, 17) current_instance FROM v$instance;
SET TERMOUT ON;
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Report : Tablespace to Owner |
PROMPT | Instance : &current_instance |
PROMPT +------------------------------------------------------------------------+
SET ECHO OFF
SET FEEDBACK 6
SET HEADING ON
SET LINESIZE 180
SET PAGESIZE 50000
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
COLUMN tablespace_name FORMAT a30 HEADING "Tablespace Name"
COLUMN owner FORMAT a20 HEADING "Owner"
COLUMN segment_type FORMAT a20 HEADING "Segment Type"
COLUMN bytes FORMAT 9,999,999,999,999 HEADING "Size (in Bytes)"
COLUMN seg_count FORMAT 9,999,999,999 HEADING "Segment Count"
BREAK ON report ON tablespace_name SKIP 2
COMPUTE sum LABEL "" OF seg_count bytes ON tablespace_name
COMPUTE sum LABEL "Grand Total: " OF seg_count bytes ON report
SELECT
tablespace_name
, owner
, segment_type
, sum(bytes) bytes
, count(*) seg_count
FROM
dba_segments
GROUP BY
tablespace_name
, owner
, segment_type
ORDER BY
tablespace_name
, owner
, segment_type
/

119
idev/dba_tablespaces.sql Normal file
View File

@@ -0,0 +1,119 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : dba_tablespaces.sql |
-- | CLASS : Database Administration |
-- | PURPOSE : Reports on all tablespaces including size and usage. This |
-- | script was designed to work with Oracle9i or higher. It will |
-- | include all tablespaces using any type of extent management as |
-- | well as true TEMPORARY tablespaces. (i.e. use of "tempfiles") |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET TERMOUT OFF;
COLUMN current_instance NEW_VALUE current_instance NOPRINT;
SELECT rpad(instance_name, 17) current_instance FROM v$instance;
SET TERMOUT ON;
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Report : Tablespaces |
PROMPT | Instance : &current_instance |
PROMPT +------------------------------------------------------------------------+
SET ECHO OFF
SET FEEDBACK 6
SET HEADING ON
SET LINESIZE 180
SET PAGESIZE 50000
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
COLUMN status FORMAT a9 HEADING 'Status'
COLUMN name FORMAT a30 HEADING 'Tablespace Name'
COLUMN type FORMAT a15 HEADING 'TS Type'
COLUMN extent_mgt FORMAT a10 HEADING 'Ext. Mgt.'
COLUMN segment_mgt FORMAT a10 HEADING 'Seg. Mgt.'
COLUMN ts_size FORMAT 9,999,999,999,999 HEADING 'Tablespace Size'
COLUMN used FORMAT 9,999,999,999,999 HEADING 'Used (in bytes)'
COLUMN free FORMAT 9,999,999,999,999 HEADING 'Free (in bytes)'
COLUMN pct_used FORMAT 999 HEADING 'Pct. Used'
BREAK ON report
COMPUTE sum OF ts_size ON report
COMPUTE sum OF used ON report
COMPUTE sum OF free ON report
COMPUTE avg OF pct_used ON report
SELECT
d.status status
, d.tablespace_name name
, d.contents type
, d.extent_management extent_mgt
, d.segment_space_management segment_mgt
, NVL(a.bytes, 0) ts_size
, NVL(a.bytes - NVL(f.bytes, 0), 0) used
-- , NVL(f.bytes, 0) free
, NVL((a.bytes - NVL(f.bytes, 0)) / a.bytes * 100, 0) pct_used
FROM
sys.dba_tablespaces d
, ( select tablespace_name, sum(bytes) bytes
from dba_data_files
group by tablespace_name
) a
, ( select tablespace_name, sum(bytes) bytes
from dba_free_space
group by tablespace_name
) f
WHERE
d.tablespace_name = a.tablespace_name(+)
AND d.tablespace_name = f.tablespace_name(+)
AND NOT (
d.extent_management like 'LOCAL'
AND
d.contents like 'TEMPORARY'
)
UNION ALL
SELECT
d.status status
, d.tablespace_name name
, d.contents type
, d.extent_management extent_mgt
, d.segment_space_management segment_mgt
, NVL(a.bytes, 0) ts_size
, NVL(t.bytes, 0) used
-- , NVL(a.bytes - NVL(t.bytes,0), 0) free
, NVL(t.bytes / a.bytes * 100, 0) pct_used
FROM
sys.dba_tablespaces d
, ( select tablespace_name, sum(bytes) bytes
from dba_temp_files
group by tablespace_name
) a
, ( select tablespace_name, sum(bytes_cached) bytes
from v$temp_extent_pool
group by tablespace_name
) t
WHERE
d.tablespace_name = a.tablespace_name(+)
AND d.tablespace_name = t.tablespace_name(+)
AND d.extent_management like 'LOCAL'
AND d.contents like 'TEMPORARY'
ORDER BY
2
/

View File

@@ -0,0 +1,80 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : dba_tablespaces_7.sql |
-- | CLASS : Database Administration |
-- | PURPOSE : Reports on all tablespaces including size and usage. This |
-- | script was designed to work with Oracle7 and Oracle8. This |
-- | script can be run against higher database versions (i.e. |
-- | Oracle8i) but will not return information about true TEMPORARY |
-- | tablespaces. (i.e. use of "tempfiles") |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET TERMOUT OFF;
COLUMN current_instance NEW_VALUE current_instance NOPRINT;
SELECT rpad(instance_name, 17) current_instance FROM v$instance;
SET TERMOUT ON;
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Report : Tablespaces |
PROMPT | Instance : &current_instance |
PROMPT +------------------------------------------------------------------------+
SET ECHO OFF
SET FEEDBACK 6
SET HEADING ON
SET LINESIZE 180
SET PAGESIZE 50000
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
COLUMN tablespace FORMAT a30 HEADING 'Tablespace Name'
COLUMN dummy NOPRINT
COLUMN bytes FORMAT 9,999,999,999,999 HEADING 'Tablespace Size'
COLUMN used FORMAT 9,999,999,999,999 HEADING 'Used (in bytes)'
COLUMN free FORMAT 9,999,999,999,999 HEADING 'Free (in bytes)'
COLUMN pct_used FORMAT 999 HEADING 'Pct. Used'
BREAK ON report
COMPUTE avg OF pct_used ON report
COMPUTE sum OF bytes ON report
COMPUTE sum OF used ON report
COMPUTE sum OF free ON report
SELECT
b.tablespace_name tablespace
, a.tablespace_name dummy
, SUM(b.bytes)/COUNT(DISTINCT a.file_id||'.'||a.block_id ) bytes
, NVL(SUM(b.bytes)/COUNT(DISTINCT a.file_id||'.'||a.block_id ) -
SUM(a.bytes)/COUNT(DISTINCT b.file_id ),
SUM(b.bytes)/COUNT(DISTINCT a.file_id||'.'||a.block_id )) used
, NVL(SUM(a.bytes)/COUNT(DISTINCT b.file_id ),0) free
, NVL(TRUNC(CEIL(100 * ( (SUM(b.bytes)/COUNT(DISTINCT a.file_id||'.'||a.block_id )) -
(SUM(a.bytes)/COUNT(DISTINCT b.file_id ) )) /
(SUM(b.bytes)/COUNT(DISTINCT a.file_id||'.'||a.block_id )))),100) pct_used
FROM
sys.dba_free_space a
, sys.dba_data_files b
WHERE
a.tablespace_name (+) = b.tablespace_name
GROUP BY
a.tablespace_name, b.tablespace_name
/

114
idev/dba_tablespaces_8i.sql Normal file
View File

@@ -0,0 +1,114 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : dba_tablespaces_8i.sql |
-- | CLASS : Database Administration |
-- | PURPOSE : Reports on all tablespaces including size and usage. This |
-- | script was designed to work with Oracle8i or higher. It will |
-- | include all tablespaces using any type of extent management as |
-- | well as true TEMPORARY tablespaces. (i.e. use of "tempfiles") |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET TERMOUT OFF;
COLUMN current_instance NEW_VALUE current_instance NOPRINT;
SELECT rpad(instance_name, 17) current_instance FROM v$instance;
SET TERMOUT ON;
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Report : Tablespaces |
PROMPT | Instance : &current_instance |
PROMPT +------------------------------------------------------------------------+
SET ECHO OFF
SET FEEDBACK 6
SET HEADING ON
SET LINESIZE 180
SET PAGESIZE 50000
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
COLUMN status FORMAT a9 HEADING 'Status'
COLUMN name FORMAT a30 HEADING 'Tablespace Name'
COLUMN type FORMAT a15 HEADING 'TS Type'
COLUMN extent_mgt FORMAT a11 HEADING 'Extent Mgt.'
COLUMN ts_size FORMAT 9,999,999,999,999 HEADING 'Tablespace Size'
COLUMN used FORMAT 9,999,999,999,999 HEADING 'Used (in bytes)'
COLUMN free FORMAT 9,999,999,999,999 HEADING 'Free (in bytes)'
COLUMN pct_used FORMAT 999 HEADING 'Pct. Used'
BREAK ON report
COMPUTE sum OF ts_size ON report
COMPUTE sum OF used ON report
COMPUTE sum OF free ON report
COMPUTE avg OF pct_used ON report
SELECT
d.status status
, d.tablespace_name name
, d.contents type
, d.extent_management extent_mgt
, NVL(a.bytes, 0) ts_size
, NVL(a.bytes - NVL(f.bytes, 0), 0) used
, NVL(f.bytes, 0) free
, NVL((a.bytes - NVL(f.bytes, 0)) / a.bytes * 100, 0) pct_used
FROM
sys.dba_tablespaces d
, ( select tablespace_name, sum(bytes) bytes
from dba_data_files
group by tablespace_name
) a
, ( select tablespace_name, sum(bytes) bytes
from dba_free_space
group by tablespace_name
) f
WHERE
d.tablespace_name = a.tablespace_name(+)
AND d.tablespace_name = f.tablespace_name(+)
AND NOT (
d.extent_management like 'LOCAL'
AND
d.contents like 'TEMPORARY'
)
UNION ALL
SELECT
d.status status
, d.tablespace_name name
, d.contents type
, d.extent_management extent_mg
, NVL(a.bytes, 0) ts_size
, NVL(t.bytes, 0) used
, NVL(a.bytes - NVL(t.bytes,0), 0) free
, NVL(t.bytes / a.bytes * 100, 0) pct_used
FROM
sys.dba_tablespaces d
, ( select tablespace_name, sum(bytes) bytes
from dba_temp_files
group by tablespace_name
) a
, ( select tablespace_name, sum(bytes_cached) bytes
from v$temp_extent_pool
group by tablespace_name
) t
WHERE
d.tablespace_name = a.tablespace_name(+)
AND d.tablespace_name = t.tablespace_name(+)
AND d.extent_management like 'LOCAL'
AND d.contents like 'TEMPORARY'
/

81
idev/dba_top_segments.sql Normal file
View File

@@ -0,0 +1,81 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : dba_top_segments.sql |
-- | CLASS : Database Administration |
-- | PURPOSE : Provides a report on the top segments (in bytes) grouped by |
-- | Segment Type. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET TERMOUT OFF;
COLUMN current_instance NEW_VALUE current_instance NOPRINT;
SELECT rpad(instance_name, 17) current_instance FROM v$instance;
SET TERMOUT ON;
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Report : Top Segments |
PROMPT | Instance : &current_instance |
PROMPT +------------------------------------------------------------------------+
SET ECHO OFF
SET FEEDBACK 6
SET HEADING ON
SET LINESIZE 180
SET PAGESIZE 50000
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
COLUMN segment_type FORMAT A20 HEADING 'Segment Type'
COLUMN owner FORMAT A15 HEADING 'Owner'
COLUMN segment_name FORMAT A30 HEADING 'Segment Name'
COLUMN partition_name FORMAT A30 HEADING 'Partition Name'
COLUMN tablespace_name FORMAT A20 HEADING 'Tablespace Name'
COLUMN bytes FORMAT 9,999,999,999,999 HEADING 'Size (in bytes)'
COLUMN extents FORMAT 999,999,999 HEADING 'Extents'
BREAK ON segment_type SKIP 1
COMPUTE sum OF bytes ON segment_type
SELECT
a.segment_type segment_type
, a.owner owner
, a.segment_name segment_name
, a.partition_name partition_name
, a.tablespace_name tablespace_name
, a.bytes bytes
, a.extents extents
FROM
(select
b.segment_type
, b.owner
, b.segment_name
, b.partition_name
, b.tablespace_name
, b.bytes
, b.extents
from
dba_segments b
order by
b.bytes desc
) a
WHERE
rownum < 101
ORDER BY
segment_type, bytes desc, owner, segment_name
/

View File

@@ -0,0 +1,76 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : erp_conc_manager_job_status.sql |
-- | CLASS : Oracle Applications |
-- | PURPOSE : Reports on concurrent manager job status. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET TERMOUT OFF;
COLUMN current_instance NEW_VALUE current_instance NOPRINT;
SELECT rpad(instance_name, 17) current_instance FROM v$instance;
SET TERMOUT ON;
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Report : Concurrent Manager Job Status |
PROMPT | Instance : &current_instance |
PROMPT +------------------------------------------------------------------------+
SET ECHO OFF
SET FEEDBACK 6
SET HEADING ON
SET LINESIZE 180
SET PAGESIZE 50000
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
COLUMN request_id FORMAT 9999999999 HEADING 'Request|ID';
COLUMN Req_Date FORMAT a20 HEADING 'Req|Date';
COLUMN oracle_process_id FORMAT 9999999 HEADING 'PID';
COLUMN session_id FORMAT 9999999 HEADING 'Session ID';
COLUMN oracle_id FORMAT 9999999 HEADING 'Oracle ID';
COLUMN os_process_id FORMAT a10 HEADING 'OS PID';
COLUMN requested_by FORMAT 9999999 HEADING 'Requested By';
COLUMN phase_code FORMAT a6 HEADING "Phase|Code"
COLUMN status_code FORMAT a6 HEADING "Status|Code"
COLUMN completion_text FORMAT a35 HEADING 'Text';
COLUMN user_id FORMAT 9999999 HEADING 'User ID';
COLUMN user_name FORMAT a18 HEADING 'User|Name';
COLUMN Req_Date FORMAT a20 HEADING 'Req|Date';
SELECT
a.request_id
, to_char(a.REQUEST_DATE,'DD-MON-YYYY HH24:MI:SS') Req_Date
, b.user_name
, a.phase_code
, a.status_code
, c.os_process_id
, a.oracle_id
, a.requested_by
, a.completion_text
FROM
applsys.fnd_concurrent_requests a
, applsys.fnd_user b
, applsys.fnd_concurrent_processes c
WHERE
a.requested_by = b.user_id
AND c.concurrent_process_id = a.controlling_manager
AND a.phase_code in ('R', 'T')
ORDER BY
a.request_id, c.os_process_id
/

View File

@@ -0,0 +1,86 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : erp_conc_manager_job_status.sql |
-- | CLASS : Oracle Applications |
-- | PURPOSE : Reports on concurrent manager job status. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET TERMOUT OFF;
COLUMN current_instance NEW_VALUE current_instance NOPRINT;
SELECT rpad(instance_name, 17) current_instance FROM v$instance;
SET TERMOUT ON;
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Report : Concurrent Manager Job Status |
PROMPT | Instance : &current_instance |
PROMPT +------------------------------------------------------------------------+
SET ECHO OFF
SET FEEDBACK 6
SET HEADING ON
SET LINESIZE 180
SET PAGESIZE 50000
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
COLUMN start_time FORMAT a20 HEADING "Start|Time"
COLUMN program_name FORMAT a50 HEADING "Program|Name"
COLUMN reqid FORMAT 9999999999 HEADING "Request|ID"
COLUMN tot_mins FORMAT 9999999 HEADING "Total|Run-Time|in Mins"
COLUMN hrs FORMAT 99999 HEADING "Running|Hrs"
COLUMN mins FORMAT 99999 HEADING "Running|Mins"
COLUMN secs FORMAT 99999 HEADING "Running|Secs"
COLUMN user_name FORMAT a18 HEADING "User|Name"
COLUMN oracle_sid FORMAT 99999 HEADING "Oracle|SID"
COLUMN serial# FORMAT 9999999 HEADING "Serial|#"
COLUMN phase FORMAT a5 HEADING "Phase|Code"
COLUMN status FORMAT a6 HEADING "Status|Code"
SELECT
r.request_id reqid
, TO_CHAR(r.actual_start_date, 'DD-MON-YYYY HH24:MI:SS') start_time
, u.user_name user_name
, r.phase_code phase
, r.status_code status
, FLOOR(((SYSDATE - r.actual_start_date)*24*60*60)/3600) hrs
, FLOOR((((SYSDATE - r.actual_start_date)*24*60*60) - FLOOR(((SYSDATE - r.actual_start_date)*24*60*60)/3600)*3600)/60) mins
, ROUND((((SYSDATE - r.actual_start_date)*24*60*60) - FLOOR(((SYSDATE - r.actual_start_date)*24*60*60)/3600)*3600 - (FLOOR((((SYSDATE - r.actual_start_date)*24*60*60) - FLOOR(((SYSDATE - r.actual_start_date)*24*60*60)/3600)*3600)/60)*60) )) secs
, (SYSDATE - r.actual_start_date)*24*60 tot_mins
, /* p.concurrent_program_id progid,*/
DECODE( p.user_concurrent_program_name
, 'Request Set Stage', 'RSS - '||r.description
, 'Report Set', 'RS - '||r.description
, p.user_concurrent_program_name ) program_name
, s.sid oracle_sid
, s.serial#
FROM
v$session s
, apps.fnd_user u
, apps.fnd_concurrent_processes pr
, apps.fnd_concurrent_programs_vl p
, apps.fnd_concurrent_requests r
WHERE
s.process = pr.os_process_id
AND pr.concurrent_process_id = r.controlling_manager
AND r.phase_code = 'R' -- and r.status_code = 'R'
AND r.requested_by = u.user_id
AND p.concurrent_program_id = r.concurrent_program_id
ORDER BY
1
/

View File

@@ -0,0 +1,73 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : erp_conc_manager_user_query.sql |
-- | CLASS : Oracle Applications |
-- | PURPOSE : Reports on concurrent manager processes. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET TERMOUT OFF;
COLUMN current_instance NEW_VALUE current_instance NOPRINT;
SELECT rpad(instance_name, 17) current_instance FROM v$instance;
SET TERMOUT ON;
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Report : Concurrent Manager Processes |
PROMPT | Instance : &current_instance |
PROMPT +------------------------------------------------------------------------+
SET ECHO OFF
SET FEEDBACK 6
SET HEADING ON
SET LINESIZE 180
SET PAGESIZE 50000
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
COLUMN oracle_process_id FORMAT 9999999 HEADING 'PID';
COLUMN session_id FORMAT 9999999 HEADING 'Session ID';
COLUMN oracle_id FORMAT 9999999 HEADING 'Oracle ID';
COLUMN os_process_id FORMAT a10 HEADING 'OS PID';
COLUMN request_id FORMAT 9999999999 HEADING 'Request ID';
COLUMN requested_by FORMAT 9999999 HEADING 'Requested By';
COLUMN status_code FORMAT a6 HEADING 'Status';
COLUMN completion_text FORMAT a15 HEADING 'Text';
COLUMN user_id FORMAT 9999999 HEADING 'User ID';
COLUMN user_name FORMAT a10 HEADING 'User Name';
SELECT
c.os_process_id
, a.oracle_id
, a.request_id
, a.requested_by
, b.user_name
, a.phase_code
, a.completion_text
FROM
applsys.fnd_concurrent_requests a
, applsys.fnd_user b
, applsys.fnd_concurrent_processes c
WHERE
a.requested_by = b.user_id
AND c.concurrent_process_id = a.controlling_manager
AND a.phase_code in ('R', 'T')
ORDER BY
c.os_process_id
/

View File

@@ -0,0 +1,60 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : example_create_clob.sql |
-- | CLASS : Examples |
-- | PURPOSE : Example SQL script that demonstrates how to create tables |
-- | containing a CLOB datatype in Oracle8i and higher. One of the |
-- | biggest differences between creating a CLOB in Oracle8 and |
-- | Oracle8i or higher is the use of the INDEX clause within the LOB|
-- | clause declaration. In Oracle8 it is possible to name the LOB |
-- | INDEX and declare a tablespace and storage clause for it. With |
-- | versions Oracle8i and higher, it is still possible to name the |
-- | INDEX LOB SEGMENT using the INDEX clause but these versions of |
-- | Oracle (8i and higher) will simply ignore anything else within |
-- | the INDEX clause (like tablespaces and storage clause.) From |
-- | what I have read Oracle is deprecating the tablespace and |
-- | storage clauses from being used within the INDEX clause. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
DROP TABLE xml_documents
/
CREATE TABLE xml_documents (
docname VARCHAR2(200)
, xmldoc CLOB
, log CLOB
, timestamp DATE
)
LOB (xmldoc)
STORE AS xml_documents_lob (
TABLESPACE lob_data
STORAGE (
INITIAL 1m NEXT 1m PCTINCREASE 0 MAXEXTENTS unlimited
)
INDEX xml_documents_lob_idx
)
LOB (log)
STORE AS xml_log_lob (
TABLESPACE lob_data
STORAGE (
INITIAL 1m NEXT 1m PCTINCREASE 0 MAXEXTENTS unlimited
)
INDEX xml_log_lob_idx
)
TABLESPACE users
STORAGE (
INITIAL 256k
NEXT 256k
MINEXTENTS 1
MAXEXTENTS 121
PCTINCREASE 0
)
/

View File

@@ -0,0 +1,74 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : example_create_clob_8.sql |
-- | CLASS : Examples |
-- | PURPOSE : Example SQL script that demonstrates how to create tables |
-- | containing a CLOB datatype in Oracle8. One of biggest |
-- | differences between creating a CLOB in Oracle8 and Oracle8i or |
-- | higher is the use of the INDEX clause within the LOB clause |
-- | declaration. In Oracle8 it is possible to name the LOB INDEX |
-- | and declare a tablespace and storage clause for it. With |
-- | versions Oracle8i and higher, it is still possible to name the |
-- | INDEX LOB SEGMENT using the INDEX clause but these versions of |
-- | Oracle (8i and higher) will simply ignore anything else within |
-- | the INDEX clause (like tablespaces and storage clause.) From |
-- | what I have read Oracle is deprecating the tablespace and |
-- | storage clauses from being used within the INDEX clause. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
DROP TABLE test_clob CASCADE CONSTRAINTS
/
CREATE TABLE test_clob (
testrunid NUMBER(15)
, startdate DATE
, parameters VARCHAR2(1000)
, testtopology CLOB
, comments VARCHAR2(4000)
, testlog CLOB
, prefix VARCHAR2(100)
)
LOB (testtopology)
STORE AS testtopology_lob (
TABLESPACE lob_data
STORAGE (
INITIAL 1m NEXT 1m PCTINCREASE 0 MAXEXTENTS unlimited
)
INDEX testtopology_lob_idx (
TABLESPACE lob_indexes
STORAGE (
INITIAL 256k NEXT 256k PCTINCREASE 0 MAXEXTENTS unlimited
)
)
)
LOB (testlog)
STORE AS testlog_lob (
TABLESPACE lob_data
STORAGE (
INITIAL 1m NEXT 1m PCTINCREASE 0 MAXEXTENTS unlimited
)
INDEX testlog_lob_idx (
TABLESPACE lob_indexes
STORAGE (
INITIAL 256k NEXT 256k PCTINCREASE 0 MAXEXTENTS unlimited
)
)
)
TABLESPACE users
STORAGE (
INITIAL 256k
NEXT 256k
MINEXTENTS 1
MAXEXTENTS 505
PCTINCREASE 0
)
/

View File

@@ -0,0 +1,34 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : example_create_dimension.sql |
-- | CLASS : Examples |
-- | PURPOSE : Example SQL script to create a dimension object. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
CREATE DIMENSION dim_clothes
LEVEL upc IS retail_tab.upc
LEVEL style IS retail_tab.style
LEVEL class IS retail_tab.class
LEVEL department IS retail_tab.department
LEVEL store IS retail_tab.store
LEVEL region IS retail_tab.region
LEVEL company IS retail_tab.company
HIERARCHY sales_rollup (
upc CHILD OF
style CHILD OF
class CHILD OF
department CHILD OF
store CHILD OF
region CHILD OF
company)
ATTRIBUTE style DETERMINES (color)
ATTRIBUTE upc DETERMINES (item_size);

View File

@@ -0,0 +1,296 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : example_create_emp_dept_custom.sql |
-- | CLASS : Examples |
-- | PURPOSE : Creates several DEMO tables along with creating a PL/SQL |
-- | procedure (fill_emp) for seeding the tables with demo data. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
prompt Connect as the test user. Default SCOTT...
CONNECT scott
/*
* -------------------------------------------------------------
* --- CREATE TABLE DEPT ---
* -------------------------------------------------------------
*/
DROP TABLE dept CASCADE CONSTRAINTS
/
CREATE TABLE dept (
dept_id NUMBER
, name VARCHAR2(100)
, location VARCHAR2(100)
)
/
ALTER TABLE dept
ADD CONSTRAINT dept_pk PRIMARY KEY(dept_id)
/
ALTER TABLE dept
MODIFY ( name CONSTRAINT dept_nn1 NOT NULL
, location CONSTRAINT dept_nn2 NOT NULL
)
/
/*
* -------------------------------------------------------------
* --- CREATE TABLE EMP ---
* -------------------------------------------------------------
*/
DROP TABLE emp CASCADE CONSTRAINTS
/
CREATE TABLE emp (
emp_id NUMBER
, dept_id NUMBER
, name VARCHAR2(30)
, date_of_birth DATE
, date_of_hire DATE
, monthly_salary NUMBER(15,2)
, position VARCHAR2(100)
, extension NUMBER
, office_location VARCHAR2(100)
)
/
ALTER TABLE emp
ADD CONSTRAINT emp_pk PRIMARY KEY(emp_id)
/
ALTER TABLE emp
MODIFY ( name CONSTRAINT emp_nn1 NOT NULL
, date_of_birth CONSTRAINT emp_nn2 NOT NULL
, date_of_hire CONSTRAINT emp_nn3 NOT NULL
, monthly_salary CONSTRAINT emp_nn4 NOT NULL
, position CONSTRAINT emp_nn5 NOT NULL
)
/
ALTER TABLE emp
ADD CONSTRAINT emp_fk1 FOREIGN KEY (dept_id)
REFERENCES dept(dept_id)
/
/*
* -------------------------------------------------------------
* --- INSERT INTO DEPT ---
* -------------------------------------------------------------
*/
INSERT INTO DEPT VALUES (100 , 'ACCOUNTING' , 'BUTLER, PA');
INSERT INTO DEPT VALUES (101 , 'RESEARCH' , 'DALLAS, TX');
INSERT INTO DEPT VALUES (102 , 'SALES' , 'CHICAGO, IL');
INSERT INTO DEPT VALUES (103 , 'OPERATIONS' , 'BOSTON, MA');
INSERT INTO DEPT VALUES (104 , 'IT' , 'PITTSBURGH, PA');
INSERT INTO DEPT VALUES (105 , 'ENGINEERING' , 'WEXFORD, PA');
INSERT INTO DEPT VALUES (106 , 'QA' , 'WEXFORD, PA');
INSERT INTO DEPT VALUES (107 , 'PROCESSING' , 'NEW YORK, NY');
INSERT INTO DEPT VALUES (108 , 'CUSTOMER SUPPORT' , 'TRANSFER, PA');
INSERT INTO DEPT VALUES (109 , 'HQ' , 'WEXFORD, PA');
INSERT INTO DEPT VALUES (110 , 'PRODUCTION SUPPORT' , 'MONTEREY, CA');
INSERT INTO DEPT VALUES (111 , 'DOCUMENTATION' , 'WEXFORD, PA');
INSERT INTO DEPT VALUES (112 , 'HELP DESK' , 'GREENVILLE, PA');
INSERT INTO DEPT VALUES (113 , 'AFTER HOURS SUPPORT' , 'SAN JOSE, CA');
INSERT INTO DEPT VALUES (114 , 'APPLICATION SUPPORT' , 'WEXFORD, PA');
INSERT INTO DEPT VALUES (115 , 'MARKETING' , 'SEASIDE, CA');
INSERT INTO DEPT VALUES (116 , 'NETWORKING' , 'WEXFORD, PA');
INSERT INTO DEPT VALUES (117 , 'DIRECTORS OFFICE' , 'WEXFORD, PA');
INSERT INTO DEPT VALUES (118 , 'ASSISTANTS' , 'WEXFORD, PA');
INSERT INTO DEPT VALUES (119 , 'COMMUNICATIONS' , 'SEATTLE, WA');
INSERT INTO DEPT VALUES (120 , 'REGIONAL SUPPORT' , 'PORTLAND, OR');
COMMIT;
/*
* -------------------------------------------------------------
* --- CREATE PACKAGE (random) ---
* -------------------------------------------------------------
*/
CREATE OR REPLACE PACKAGE random IS
-- Returns random integer between [0, r-1]
FUNCTION rndint(r IN NUMBER) RETURN NUMBER;
-- Returns random real between [0, 1]
FUNCTION rndflt RETURN NUMBER;
END;
/
CREATE OR REPLACE PACKAGE BODY random IS
m CONSTANT NUMBER:=100000000; /* initial conditions */
m1 CONSTANT NUMBER:=10000; /* (for best results) */
b CONSTANT NUMBER:=31415821; /* */
a NUMBER; /* seed */
the_date DATE; /* */
days NUMBER; /* for generating initial seed */
secs NUMBER; /* */
-- ------------------------
-- Private utility FUNCTION
-- ------------------------
FUNCTION mult(p IN NUMBER, q IN NUMBER) RETURN NUMBER IS
p1 NUMBER;
p0 NUMBER;
q1 NUMBER;
q0 NUMBER;
BEGIN
p1:=TRUNC(p/m1);
p0:=MOD(p,m1);
q1:=TRUNC(q/m1);
q0:=MOD(q,m1);
RETURN(MOD((MOD(p0*q1+p1*q0,m1)*m1+p0*q0),m));
END;
-- ---------------------------------------
-- Returns random integer between [0, r-1]
-- ---------------------------------------
FUNCTION rndint (r IN NUMBER) RETURN NUMBER IS
BEGIN
-- Generate a random NUMBER, and set it to be the new seed
a:=MOD(mult(a,b)+1,m);
-- Convert it to integer between [0, r-1] and return it
RETURN(TRUNC((TRUNC(a/m1)*r)/m1));
END;
-- ----------------------------------
-- Returns random real between [0, 1]
-- ----------------------------------
FUNCTION rndflt RETURN NUMBER IS
BEGIN
-- Generate a random NUMBER, and set it to be the new seed
a:=MOD(mult(a,b)+1,m);
RETURN(a/m);
END;
BEGIN
-- Generate initial seed "a" based on system date
the_date:=SYSDATE;
days:=TO_NUMBER(TO_CHAR(the_date, 'J'));
secs:=TO_NUMBER(TO_CHAR(the_date, 'SSSSS'));
a:=days*24*3600+secs;
END;
/
/*
* -------------------------------------------------------------
* --- CREATE PROCEDURE (fill_emp) ---
* -------------------------------------------------------------
*/
CREATE OR REPLACE PROCEDURE fill_emp (
num_records IN number)
IS
rand NUMBER;
randf NUMBER;
randfe NUMBER;
rand_dept_id NUMBER;
rand_dob NUMBER;
rand_date NUMBER;
rand_salary NUMBER;
record_count_success NUMBER;
record_count_fail_ic NUMBER;
record_count_fail_other NUMBER;
max_emp_id NUMBER;
CURSOR max_emp_csr IS
SELECT MAX(emp_id)
FROM emp;
BEGIN
DBMS_OUTPUT.ENABLE;
OPEN max_emp_csr;
FETCH max_emp_csr INTO max_emp_id;
CLOSE max_emp_csr;
max_emp_id := NVL(max_emp_id,0) + 1;
record_count_success := 0;
record_count_fail_ic := 0;
record_count_fail_other := 0;
FOR loop_index IN max_emp_id .. (max_emp_id + (num_records-1))
LOOP
rand := random.rndint(20);
randf := random.rndflt;
randfe := TRUNC( (random.rndflt*10000));
IF (randfe < 1000) THEN
randfe := randfe * 10;
END IF;
rand_dept_id := (rand + 100);
rand_date := rand * 10;
rand_salary := randf * 10000;
IF (rand_salary < 1000) THEN
rand_salary := rand_salary * 10;
END IF;
DECLARE
integrity_constraint_e EXCEPTION;
pragma EXCEPTION_INIT (integrity_constraint_e, -02291);
BEGIN
INSERT INTO emp
VALUES ( loop_index
, rand_dept_id
, 'Name at : ' || (rand_dept_id * 17)
, sysdate - (rand_date * 90)
, sysdate + rand_date
, rand_salary
, 'Position at : ' || (rand_dept_id * 13)
, randfe
, 'Office Location at : ' || (rand_dept_id * 15)
);
IF (MOD(loop_index, 1000) = 0) THEN
COMMIT;
-- DBMS_OUTPUT.PUT_LINE('Commit point reached at: ' || loop_index || '.');
END IF;
record_count_success := record_count_success + 1;
EXCEPTION
WHEN integrity_constraint_e THEN
-- DBMS_OUTPUT.PUT_LINE('Integrity constraint for dept_id: ' || rand_dept_id);
record_count_fail_ic := record_count_fail_ic + 1;
WHEN others THEN
-- DBMS_OUTPUT.PUT_LINE('Other failure');
record_count_fail_other := record_count_fail_other + 1;
END;
END LOOP;
COMMIT;
DBMS_OUTPUT.NEW_LINE;
DBMS_OUTPUT.PUT_LINE('Procedure complete inserting records into emp.');
DBMS_OUTPUT.PUT_LINE('----------------------------------------------');
DBMS_OUTPUT.PUT_LINE('Requested records : ' || num_records);
DBMS_OUTPUT.PUT_LINE('Successfully inserted records : ' || record_count_success);
DBMS_OUTPUT.PUT_LINE('Failed records (integrity_constraint) : ' || record_count_fail_ic);
DBMS_OUTPUT.PUT_LINE('Failed records (other) : ' || record_count_fail_other);
END;
/

View File

@@ -0,0 +1,91 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : example_create_emp_dept_original.sql |
-- | CLASS : Examples |
-- | PURPOSE : Creates several DEMO tables along with creating a PL/SQL |
-- | procedure (fill_emp) for seeding the tables with demo data. |
-- | This is the original SQL script that is included with the |
-- | Oracle RDBMS. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
CONNECT / AS SYSDBA
DROP PUBLIC SYNONYM PARTS;
prompt Connect as the test user. Default JHUNTER...
CONNECT JHUNTER
CREATE TABLE DEPT
(DEPTNO NUMBER(2) CONSTRAINT PK_DEPT PRIMARY KEY,
DNAME VARCHAR2(14) ,
LOC VARCHAR2(13) ) ;
CREATE TABLE EMP
(EMPNO NUMBER(4) CONSTRAINT PK_EMP PRIMARY KEY,
ENAME VARCHAR2(10),
JOB VARCHAR2(9),
MGR NUMBER(4),
HIREDATE DATE,
SAL NUMBER(7,2),
COMM NUMBER(7,2),
DEPTNO NUMBER(2) CONSTRAINT FK_DEPTNO REFERENCES DEPT);
INSERT INTO DEPT VALUES
(10,'ACCOUNTING','NEW YORK');
INSERT INTO DEPT VALUES (20,'RESEARCH','DALLAS');
INSERT INTO DEPT VALUES
(30,'SALES','CHICAGO');
INSERT INTO DEPT VALUES
(40,'OPERATIONS','BOSTON');
INSERT INTO EMP VALUES
(7369,'SMITH','CLERK',7902,to_date('17-12-1980','dd-mm-yyyy'),800,NULL,20);
INSERT INTO EMP VALUES
(7499,'ALLEN','SALESMAN',7698,to_date('20-2-1981','dd-mm-yyyy'),1600,300,30);
INSERT INTO EMP VALUES
(7521,'WARD','SALESMAN',7698,to_date('22-2-1981','dd-mm-yyyy'),1250,500,30);
INSERT INTO EMP VALUES
(7566,'JONES','MANAGER',7839,to_date('2-4-1981','dd-mm-yyyy'),2975,NULL,20);
INSERT INTO EMP VALUES
(7654,'MARTIN','SALESMAN',7698,to_date('28-9-1981','dd-mm-yyyy'),1250,1400,30);
INSERT INTO EMP VALUES
(7698,'BLAKE','MANAGER',7839,to_date('1-5-1981','dd-mm-yyyy'),2850,NULL,30);
INSERT INTO EMP VALUES
(7782,'CLARK','MANAGER',7839,to_date('9-6-1981','dd-mm-yyyy'),2450,NULL,10);
INSERT INTO EMP VALUES
(7788,'JHUNTER','ANALYST',7566,to_date('13-JUL-87','dd-mm-rr')-85,3000,NULL,20);
INSERT INTO EMP VALUES
(7839,'KING','PRESIDENT',NULL,to_date('17-11-1981','dd-mm-yyyy'),5000,NULL,10);
INSERT INTO EMP VALUES
(7844,'TURNER','SALESMAN',7698,to_date('8-9-1981','dd-mm-yyyy'),1500,0,30);
INSERT INTO EMP VALUES
(7876,'ADAMS','CLERK',7788,to_date('13-JUL-87', 'dd-mm-rr')-51,1100,NULL,20);
INSERT INTO EMP VALUES
(7900,'JAMES','CLERK',7698,to_date('3-12-1981','dd-mm-yyyy'),950,NULL,30);
INSERT INTO EMP VALUES
(7902,'FORD','ANALYST',7566,to_date('3-12-1981','dd-mm-yyyy'),3000,NULL,20);
INSERT INTO EMP VALUES
(7934,'MILLER','CLERK',7782,to_date('23-1-1982','dd-mm-yyyy'),1300,NULL,10);
CREATE TABLE BONUS
(
ENAME VARCHAR2(10) ,
JOB VARCHAR2(9) ,
SAL NUMBER,
COMM NUMBER
) ;
CREATE TABLE SALGRADE
( GRADE NUMBER,
LOSAL NUMBER,
HISAL NUMBER );
INSERT INTO SALGRADE VALUES (1,700,1200);
INSERT INTO SALGRADE VALUES (2,1201,1400);
INSERT INTO SALGRADE VALUES (3,1401,2000);
INSERT INTO SALGRADE VALUES (4,2001,3000);
INSERT INTO SALGRADE VALUES (5,3001,9999);
COMMIT;
rem EXIT

View File

@@ -0,0 +1,74 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : example_create_index.sql |
-- | CLASS : Examples |
-- | PURPOSE : Example SQL script to demonstrate how to create indexes with |
-- | proper naming conventions. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
/*
* -------------------------------
* UNIQUE INDEX
* -------------------------------
*/
CREATE UNIQUE INDEX emp_u1
ON emp(emp_id)
TABLESPACE indexes
STORAGE (
INITIAL 256K
NEXT 256K
MINEXTENTS 1
MAXEXTENTS 121
PCTINCREASE 0
FREELISTS 3
)
/
/*
* -------------------------------
* NON-UNIQUE (default) INDEX
* -------------------------------
*/
CREATE INDEX emp_n1
ON emp(name)
TABLESPACE indexes
STORAGE (
INITIAL 64K
NEXT 64K
MINEXTENTS 1
MAXEXTENTS 121
PCTINCREASE 0
FREELISTS 3
)
/
/*
* -------------------------------
* PRIMARY KEY INDEX
* -------------------------------
*/
ALTER TABLE emp
ADD CONSTRAINT emp_pk PRIMARY KEY(emp_id)
USING INDEX
TABLESPACE indexes
STORAGE (
INITIAL 64K
NEXT 64K
MINEXTENTS 1
MAXEXTENTS 121
PCTINCREASE 0
)
/

View File

@@ -0,0 +1,63 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : example_create_index_organized_table.sql |
-- | CLASS : Examples |
-- | PURPOSE : Example SQL script that demonstrates how to create an Index |
-- | Organized Table (IOT) object. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
/*
* ------------------------
* NORMAL IOT
* ------------------------
*/
DROP TABLE my_iot
/
CREATE TABLE my_iot (
id NUMBER
, name VARCHAR2(100)
, hiredate DATE
, CONSTRAINT my_iot_pk PRIMARY KEY (id)
)
ORGANIZATION INDEX
OVERFLOW TABLESPACE users
/
/*
* --------------------------------------------
* CREATE IOT FROM SELECTING FROM ANOTHER TABLE
* --------------------------------------------
*/
DROP TABLE my_iot_from_table
/
CREATE TABLE my_iot_from_table (
emp_id
, dept_id
, name
, date_of_birth
, date_of_hire
, monthly_salary
, position
, extension
, office_location
, CONSTRAINT my_iot_from_table_pk PRIMARY KEY (emp_id)
)
ORGANIZATION INDEX
OVERFLOW TABLESPACE users
AS
SELECT * FROM emp
/

View File

@@ -0,0 +1,40 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : example_create_materialized_view.sql |
-- | CLASS : Examples |
-- | PURPOSE : Example SQL script that demonstrates how to create several |
-- | materialized views. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
CREATE MATERIALIZED VIEW flight_fact_mv
BUILD IMMEDIATE
REFRESH COMPLETE ON COMMIT
ENABLE QUERY REWRITE
AS
SELECT
plane_id PLANE_ID
, sum(sale_amount) SUM_SALE_AMOUNT
FROM scott.flight_fact
GROUP BY plane_id
/
CREATE MATERIALIZED VIEW monthly_salary_mv
BUILD IMMEDIATE
REFRESH COMPLETE ON COMMIT
ENABLE QUERY REWRITE
AS
SELECT
b.name DEPT_NAME
, a.monthly_salary AVG_MONTHLY_SALARY
FROM emp a, dept b
/

View File

@@ -0,0 +1,25 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : example_create_not_null_constraints.sql |
-- | CLASS : Examples |
-- | PURPOSE : It is important when designing tables to name your NOT NULL |
-- | constraints. The following example provides the syntax necessary|
-- | to name your NOT NULL constraints. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
ALTER TABLE user_names
MODIFY ( name CONSTRAINT user_names_nn1 NOT NULL
, age CONSTRAINT user_names_nn2 NOT NULL
, update_log_date CONSTRAINT user_names_nn3 NOT NULL
)
/

View File

@@ -0,0 +1,61 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : example_create_primary_foreign_key.sql |
-- | CLASS : Examples |
-- | PURPOSE : Example SQL script that creates a Primary / Foreign key |
-- | relationship between the EMP and DEPT tables. It is advisable to|
-- | create a non-unique index on all foreign keys. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
-- +-----------------------------------------------------------------+
-- | ADD PRIMARY KEY |
-- +-----------------------------------------------------------------+
ALTER TABLE dept
ADD CONSTRAINT dept_pk PRIMARY KEY(dept_id)
USING INDEX
TABLESPACE indexes
STORAGE (
INITIAL 64K
NEXT 64K
MINEXTENTS 1
MAXEXTENTS 121
PCTINCREASE 0
)
/
-- +-----------------------------------------------------------------+
-- | ADD FOREIGN KEY |
-- +-----------------------------------------------------------------+
ALTER TABLE emp
ADD CONSTRAINT emp_fk1 FOREIGN KEY (dept_id)
REFERENCES dept(dept_id)
/
-- +-----------------------------------------------------------------+
-- | ADD NON-UNIQUE INDEX FOR THE FOREIGN KEY |
-- +-----------------------------------------------------------------+
CREATE INDEX emp_fk_n1
ON emp(dept_id)
TABLESPACE indexes
STORAGE (
INITIAL 64K
NEXT 64K
MINEXTENTS 1
MAXEXTENTS 121
PCTINCREASE 0
FREELISTS 3
)
/

View File

@@ -0,0 +1,235 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : example_create_profile_password_parameters.sql |
-- | CLASS : Examples |
-- | PURPOSE : The following CREATE FUNCTION and CREATE PROFILE script allow |
-- | the DBA to set better password controls for accounts in the |
-- | Oracle database. This script is based heavily on the default |
-- | script: utlpwdmg.sql |
-- | Note that this profile does not include parameters used to |
-- | limit resources. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
CONNECT / as sysdba
/*
* ------------------------------------------------------------------
* FIRST CREATE THE PL/SQL PASSWORD VERIFY FUNCTION
* ------------------------------------------------------------------
*/
CREATE OR REPLACE FUNCTION verify_function (
username VARCHAR2
, password VARCHAR2
, old_password VARCHAR2
) RETURN boolean IS
n BOOLEAN;
m INTEGER;
differ INTEGER;
isdigit BOOLEAN;
ischar BOOLEAN;
ispunct BOOLEAN;
digitarray VARCHAR2(20);
punctarray VARCHAR2(25);
chararray VARCHAR2(52);
BEGIN
digitarray:= '0123456789';
chararray:= 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
punctarray:='!"#$%&()``*+,-/:;<=>?_';
-- ---------------------------------------------
-- CHECK IF THE PASSWORD IS SAME AS THE USERNAME
-- ---------------------------------------------
IF NLS_LOWER(password) = NLS_LOWER(username)
THEN
raise_application_error(-20001, 'Password same as or similar to user');
END IF;
-- ---------------------------------------------
-- CHECK FOR THE MINIMUM LENGTH OF THE PASSWORD
-- ---------------------------------------------
IF length(password) < 4 THEN
raise_application_error(-20002, 'Password length less than 4');
END IF;
-- ---------------------------------------------
-- CHECK IF THE PASSWORD IS TOO SIMPLE. A
-- DICTIONARY OF WORDS MAY BE MAINTAINED AND A
-- CHECK MAY BE MADE SO AS NOT TO ALLOW THE
-- WORDS THAT ARE TOO SIMPLE FOR THE PASSWORD.
-- ---------------------------------------------
IF NLS_LOWER(password) IN ('welcome', 'database', 'account', 'user', 'password', 'oracle', 'computer', 'abcd') THEN
raise_application_error(-20002, 'Password too simple');
END IF;
-- ---------------------------------------------
-- CHECK IF THE PASSWORD CONTAINS AT LEAST ONE
-- LETTER, ONE DIGIT AND ONE PUNCTUATION MARK.
-- ---------------------------------------------
-- 1. Check for the digit
-- ---------------------------------------------
isdigit:=FALSE;
m := length(password);
FOR i IN 1..10 LOOP
FOR j IN 1..m LOOP
IF substr(password,j,1) = substr(digitarray,i,1) THEN
isdigit:=TRUE;
GOTO findchar;
END IF;
END LOOP;
END LOOP;
IF isdigit = FALSE THEN
raise_application_error(-20003, 'Password should contain at least one digit, one character and one punctuation');
END IF;
-- ---------------------------------------------
-- 2. Check for the character
-- ---------------------------------------------
<<findchar>>
ischar:=FALSE;
FOR i IN 1..length(chararray) LOOP
FOR j IN 1..m LOOP
IF substr(password,j,1) = substr(chararray,i,1) THEN
ischar:=TRUE;
GOTO findpunct;
END IF;
END LOOP;
END LOOP;
IF ischar = FALSE THEN
raise_application_error(-20003, 'Password should contain at least one digit, one character and one punctuation');
END IF;
-- ---------------------------------------------
-- 3. Check for the punctuation
-- ---------------------------------------------
<<findpunct>>
ispunct:=FALSE;
FOR i IN 1..length(punctarray) LOOP
FOR j IN 1..m LOOP
IF substr(password,j,1) = substr(punctarray,i,1) THEN
ispunct:=TRUE;
GOTO endsearch;
END IF;
END LOOP;
END LOOP;
IF ispunct = FALSE THEN
raise_application_error(-20003, 'Password should contain at least one digit, one character and one punctuation');
END IF;
<<endsearch>>
-- ---------------------------------------------
-- CHECK IF THE PASSWORD DIFFERS FROM THE
-- PREVIOUS PASSWORD BY AT LEAST 3 LETTERS
-- ---------------------------------------------
IF old_password = '' THEN
raise_application_error(-20004, 'Old password is null');
END IF;
differ := length(old_password) - length(password);
IF abs(differ) < 3 THEN
IF length(password) < length(old_password) THEN
m := length(password);
ELSE
m := length(old_password);
END IF;
differ := abs(differ);
FOR i IN 1..m LOOP
IF substr(password,i,1) != substr(old_password,i,1) THEN
differ := differ + 1;
END IF;
END LOOP;
IF differ < 3 THEN
raise_application_error(-20004, 'Password should differ by at least 3 characters');
END IF;
END IF;
-- ---------------------------------------------
-- Everything is fine; return TRUE
-- ---------------------------------------------
RETURN(TRUE);
END;
/
/*
** +-----------------------------------------------------------------------------------+
** | CREATE PASSWORD PROFILE: developer_profile |
** | --------------------------------------------------------------------------------- |
** | |
** | => FAILED_LOGIN_ATTEMPTS : Represents the number of failed login attempts that |
** | can be tried before Oracle locks out an account. |
** | Note that the user receives an error message: |
** | "ERROR: ORA-28000": The account is locked" upon |
** | the locking out of the account due to excessive |
** | failed connect attempts. |
** | |
** | => PASSWORD_GRACE_TIME : This setting is the amount of time a user has to |
** | change his or her password once the password |
** | expires (from "password_life_time"). This parameter |
** | is set by using by using either a number that |
** | represents days or a number that represents a |
** | fraction of a day. |
** | |
** | => PASSWORD_LIFE_TIME : This setting determines how long a user's password |
** | is good for. Once the time has passed, the password |
** | expires and the user cannot sign onto the system. |
** | To delay the password expiration, use the |
** | "PASSWORD_GRACE_TIME" parameter (above). |
** | |
** | => PASSWORD_LOCK_TIME : Determines how long an account will remain locked |
** | out if the number of failed attempts, as defined |
** | by "FAILED_LOGIN_ATTEMPTS", is exceeded. |
** | |
** | => PASSWORD_REUSE_MAX : This setting defines the number of times a password |
** | has to be changed before it can be reused. If this |
** | parameter is set, the parameter |
** | "PASSWORD_REUSE_TIME" parameter MUST be set to |
** | UNLIMITED. |
** | |
** | => PASSWORD_REUSE_TIME : This setting defines the number of days before a |
** | password can be reused. |
** | |
** | => PASSWORD_VERIFY_FUNCTION : This setting defines the user-defined PL/SQL |
** | function that is called to control the complexity |
** | of the password. |
** | |
** | NOTES ON REPRESENTING TIME : |
** | To express a fraction of a day for setting, use the notation y/z. In this |
** | format, z is the total of the fractional part of the day you are representing. |
** | Therefore, if you use hours, z is 24 (24 hours in a day). If you use minutes, |
** | z is 1440. If you use seconds, z is 86400. |
** | |
** | The y part of the fraction is the fractional part of the z quantity you wish to |
** | represent. For example, if you didn't want to immediately shut a user off when |
** | his or her password expired - but wanted to give the user six hours to change |
** | the password - you would use the setting of 1/4 (which is really 6/24, because |
** | 1/4 of a day is six hours). In another example, if you wanted to use 90 |
** | minutes, the proper setting would be 1/16 (90/1440 mathematically reduced). |
** | |
** +-----------------------------------------------------------------------------------+
*/
CREATE PROFILE DEVELOPER_PROFILE LIMIT
PASSWORD_LIFE_TIME 60
PASSWORD_GRACE_TIME 10
PASSWORD_REUSE_TIME 1800
PASSWORD_REUSE_MAX UNLIMITED
FAILED_LOGIN_ATTEMPTS 3
PASSWORD_LOCK_TIME 1/1440
PASSWORD_VERIFY_FUNCTION verify_function;

View File

@@ -0,0 +1,224 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : example_create_profile_resource_parameters.sql |
-- | CLASS : Examples |
-- | PURPOSE : The following script provides syntax on how to create an Oracle |
-- | profile to be used in limiting resources. The profile in this |
-- | example does not provide parameters related to password |
-- | security. |
-- | |
-- | Oracle Database enforces resource limits in the following ways: |
-- | |
-- | (*) If a user exceeds the CONNECT_TIME or IDLE_TIME session |
-- | resource limit, then the database rolls back the current |
-- | transaction and ends the session. When the user process |
-- | next issues a call, the database returns an error. |
-- | |
-- | (*) If a user attempts to perform an operation that exceeds |
-- | the limit for other session resources, then the database |
-- | aborts the operation, rolls back the current statement, |
-- | and immediately returns an error. The user can then |
-- | commit or roll back the current transaction, and must |
-- | then end the session. |
-- | |
-- | (*) If a user attempts to perform an operation that exceeds |
-- | the limit for a single call, then the database aborts the |
-- | operation, rolls back the current statement, and returns |
-- | an error, leaving the current transaction intact. |
-- | |
-- | NOTES: |
-- | |
-- | (*) You can use fractions of days for all parameters that |
-- | limit time, with days as units. For example, 1 hour is |
-- | 1/24 and 1 minute is 1/1440. None of the resource |
-- | parameters are specified in days! |
-- | |
-- | (*) You can specify resource limits for users regardless of |
-- | whether the resource limits are enabled. However, Oracle |
-- | Database does not enforce the limits until you enable |
-- | them. |
-- | |
-- | (*) After you set up the new profile, you must edit your |
-- | INIT.ORA file and set: |
-- | |
-- | RESOURCE_LIMIT = TRUE |
-- | |
-- | if you attempt to limit any of the profile resources |
-- | below: |
-- | |
-- | SESSIONS_PER_USER |
-- | CPU_PER_SESSION |
-- | CPU_PER_CALL |
-- | CONNECT_TIME |
-- | IDLE_TIME |
-- | LOGICAL_READS_PER_SESSION |
-- | COMPOSITE_LIMIT |
-- | PRIVATE_SGA |
-- | |
-- | You can also modify the "RESOURCE_LIMIT" parameter on the |
-- | SYSTEM level via: |
-- | |
-- | ALTER SYSTEM SET RESOURCE_LIMIT = TRUE; |
-- | |
-- | Note though; this will only apply for new users login |
-- | onto the database - not the existing users currently |
-- | logged on. |
-- | |
-- | It is possible to check the current information on this |
-- | parameter by performing the below SELECT: |
-- | |
-- | SELECT * FROM V$PARAMETER |
-- | WHERE NAME = 'resource_limit'; |
-- | |
-- | (*) When specified with a resource parameter (like those |
-- | parameters defined in this example script), UNLIMITED |
-- | indicates that a user assigned this profile can use an |
-- | unlimited amount of this resource. When specified with a |
-- | password parameter, UNLIMITED indicates that no limit has |
-- | been set for the parameter. |
-- | |
-- | (*) Specify DEFAULT if you want to omit a limit for this |
-- | resource in this profile. A user assigned this profile is |
-- | subject to the limit for this resource specified in the |
-- | DEFAULT profile. The DEFAULT profile initially defines |
-- | unlimited resources. You can change those limits with the |
-- | ALTER PROFILE statement. |
-- | |
-- | Any user who is not explicitly assigned a profile is |
-- | subject to the limits defined in the DEFAULT profile. |
-- | Also, if the profile that is explicitly assigned to a |
-- | user omits limits for some resources or specifies DEFAULT |
-- | for some limits, then the user is subject to the limits |
-- | on those resources defined by the DEFAULT profile. |
-- | |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
CONNECT / as sysdba
/*
** +-----------------------------------------------------------------------------------+
** | CREATE PASSWORD PROFILE: developer_profile |
** | --------------------------------------------------------------------------------- |
** | |
** | => SESSIONS_PER_USER : Specify the number of concurrent sessions to |
** | which you want to limit the user. When a user |
** | attempts to create a new session that exceeds |
** | the given threshold, they will not be allowed |
** | to login with that new session and presented |
** | with an ORA-02391 error. |
** | |
** | => CPU_PER_SESSION : Specify the CPU time limit for a session, |
** | expressed in hundredth of seconds. If the user |
** | exceeds this time limit, they are logged off |
** | with an ORA-02392 error. |
** | |
** | => CPU_PER_CALL : Specify the CPU time limit for a call (a parse, |
** | execute, or fetch), expressed in hundredths of |
** | seconds. If the user exceeds this time limit, |
** | they are logged off with an ORA-02393 error. |
** | |
** | => CONNECT_TIME : Specify the total elapsed time limit for a |
** | session, expressed in minutes. When a user |
** | session exceeds the given threshold, they are |
** | logged off and presented with an ORA-02399 |
** | error. |
** | |
** | => IDLE_TIME : Specify the permitted periods of continuous |
** | inactive time during a session, expressed in |
** | minutes. Long-running queries and other |
** | operations are not subject to this limit. When |
** | a user session exceeds the given threshold, |
** | they are logged off and presented with an |
** | ORA-02396 error. |
** | |
** | => LOGICAL_READS_PER_SESSION : Specify the permitted number of data blocks |
** | read in a session, including blocks read from |
** | memory and disk. When a user session exceeds |
** | the given threshold, they are logged off and |
** | presented with an ORA-02394 error. |
** | |
** | => LOGICAL_READS_PER_CALL : Specify the permitted number of data blocks |
** | read for a call to process a SQL statement |
** | (a parse, execute, or fetch). When a user |
** | session exceeds the given threshold, they are |
** | logged off and presented with an ORA-02395 |
** | error. |
** | |
** | => PRIVATE_SGA : Specify the amount of private space a session |
** | can allocate in the shared pool of the system |
** | global area (SGA) specified using the |
** | "size_clause". The size_clause lets you specify |
** | a number of bytes, kilobytes (K), megabytes (M),|
** | gigabytes (G), terabytes (T), petabytes (P), or |
** | exabytes (E) in any statement that lets you |
** | establish amounts of disk or memory space. Use |
** | the size_clause to specify a number or multiple |
** | of bytes. If you do not specify any of the |
** | multiple abbreviations, the integer is |
** | interpreted as bytes. |
** | |
** | NOTE: |
** | This limit applies only if you are using shared |
** | server architecture. The private space for a |
** | session in the SGA includes private SQL and |
** | PL/SQL areas, but not shared SQL and PL/SQL |
** | areas. |
** | |
** | => COMPOSITE_LIMIT : Specify the total resource cost for a session, |
** | expressed in service units. Oracle Database |
** | calculates the total service units as a |
** | weighted sum of CPU_PER_SESSION, CONNECT_TIME, |
** | LOGICAL_READS_PER_SESSION, and PRIVATE_SGA. |
** | |
** +-----------------------------------------------------------------------------------+
*/
/*
** +-----------------------------------------------------------------------------------+
** | If you assign the developer_profile profile to a user (as defined below), the |
** | user is subject to the following limits in subsequent sessions: |
** | |
** | => The user can have any number of concurrent sessions. |
** | => In a single session, the user cannot consume more than 120 seconds |
** | (2 minutes) of CPU time. |
** | => A single call made by the user cannot consume more than 30 seconds of CPU |
** | time. |
** | => A single session cannot last for more than 45 minutes. |
** | => A single session cannot be idle for more than 5 minutes. |
** | => In a single session, the number of data blocks read from memory and disk |
** | is subject to the limit specified in the DEFAULT profile. |
** | => A single call made by the user cannot read more than 1000 data blocks from |
** | memory and disk. |
** | => A single session cannot allocate more than 15 kilobytes of memory in the |
** | SGA. |
** | => In a single session, the total resource cost cannot exceed 5 million |
** | service units. The formula for calculating the total resource cost is |
** | specified by the ALTER RESOURCE COST statement. |
** | => Since the developer_profile profile omits a limit for password limits, the |
** | user is subject to the limits on these resources specified in the DEFAULT |
** | profile. |
** +-----------------------------------------------------------------------------------+
*/
CREATE PROFILE developer_profile LIMIT
SESSIONS_PER_USER UNLIMITED
CPU_PER_SESSION 12000
CPU_PER_CALL 3000
CONNECT_TIME 45
IDLE_TIME 5
LOGICAL_READS_PER_SESSION DEFAULT
LOGICAL_READS_PER_CALL 1000
PRIVATE_SGA 15K
COMPOSITE_LIMIT 5000000
/

View File

@@ -0,0 +1,141 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : example_create_resource_plan_multi_resource_plan_9i.sql |
-- | CLASS : Examples |
-- | PURPOSE : Example SQL script to create a Multilevel Schema / Resouce Plan |
-- | configuration in Oracle 9i. It will use default plan and |
-- | resource consumer group methods. |
-- | +---+
-- | [TOP PLAN] |
-- | | |
-- | ---------------------------- |
-- | / \ |
-- | 30% @ level 1 70% @ level 1 |
-- | | | |
-- | [SUB PLAN 1] [SUB PLAN 2] |
-- | | | |
-- | | | |
-- | ------------------------- ---------------------- |
-- | / | \ / | \ |
-- | 80% @ 20% @ 100% @ 100% @ 60% @ 40% @ |
-- | level 1 level 1 level 2 level 2 level 1 level 1 |
-- | | | | | | | |
-- | [ONLINE GROUP] [BATCH GROUP ] [OTHER GROUPS] [ONLINE GROUP] [BATCH GROUP] |
-- | [ SUB PLAN 1 ] [ SUB PLAN 1 ] [ SUB PLAN 2 ] [ SUB PLAN 2] |
-- | |
-- | +---+
-- | |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
BEGIN
-- +----------------------------------------------------------------------------+
-- | Create Pending Area |
-- +----------------------------------------------------------------------------+
DBMS_RESOURCE_MANAGER.CREATE_PENDING_AREA();
-- +----------------------------------------------------------------------------+
-- | Create three plans - One "Top Plan" and Two "Sub Plans" |
-- +----------------------------------------------------------------------------+
DBMS_RESOURCE_MANAGER.CREATE_PLAN(PLAN => 'TOP_PLAN', COMMENT => 'Top plan');
DBMS_RESOURCE_MANAGER.CREATE_PLAN(PLAN => 'SUB_PLAN1', COMMENT => 'Sub plan 1');
DBMS_RESOURCE_MANAGER.CREATE_PLAN(PLAN => 'SUB_PLAN2', COMMENT => 'Sub plan 2');
-- +----------------------------------------------------------------------------+
-- | Create all resource consumer groups that will be attached to the two |
-- | "Sub Plans". There will be two "user defined" resource consumer groups and |
-- | one "Oracle defined" resource consumer group (OTHER_GROUPS) defined for |
-- | each "Sub Plan". |
-- +----------------------------------------------------------------------------+
DBMS_RESOURCE_MANAGER.CREATE_CONSUMER_GROUP(CONSUMER_GROUP => 'ONLINE_GROUP_SUB_PLAN_1', COMMENT => 'Online Group - Sub Plan 1');
DBMS_RESOURCE_MANAGER.CREATE_CONSUMER_GROUP(CONSUMER_GROUP => 'BATCH_GROUP_SUB_PLAN_1', COMMENT => 'Batch Group - Sub Plan 1');
DBMS_RESOURCE_MANAGER.CREATE_CONSUMER_GROUP(CONSUMER_GROUP => 'ONLINE_GROUP_SUB_PLAN_2', COMMENT => 'Online Group - Sub Plan 2');
DBMS_RESOURCE_MANAGER.CREATE_CONSUMER_GROUP(CONSUMER_GROUP => 'BATCH_GROUP_SUB_PLAN_2', COMMENT => 'Batch Group - Sub Plan 2');
-- +----------------------------------------------------------------------------+
-- | We first define the directives that will control CPU resources between the |
-- | "Top Plan" and its two "Sub Plans". The first sub plan (SUB_PLAN1) will |
-- | receive 30% of the CPU at level 1 while the second sub plan (SUB_PLAN2) |
-- | will receive 70% of the CPU at level 1. |
-- +----------------------------------------------------------------------------+
DBMS_RESOURCE_MANAGER.CREATE_PLAN_DIRECTIVE( PLAN =>'TOP_PLAN'
, GROUP_OR_SUBPLAN =>'SUB_PLAN1'
, COMMENT=> 'All sub plan 1 user sessions at level 1'
, CPU_P1 => 30);
DBMS_RESOURCE_MANAGER.CREATE_PLAN_DIRECTIVE( PLAN =>'TOP_PLAN'
, GROUP_OR_SUBPLAN =>'SUB_PLAN2'
, COMMENT=> 'All sub plan 2 user sessions at level 1'
, CPU_P1 => 70);
-- +----------------------------------------------------------------------------+
-- | Finally, we define the key directives for each of the sub plans and |
-- | resources available for user sessions. |
-- +----------------------------------------------------------------------------+
DBMS_RESOURCE_MANAGER.CREATE_PLAN_DIRECTIVE( PLAN => 'SUB_PLAN1'
, GROUP_OR_SUBPLAN => 'ONLINE_GROUP_SUB_PLAN_1'
, COMMENT => 'Online sub plan 1 users sessions at level 1'
, CPU_P1 => 80
, CPU_P2=> 0);
DBMS_RESOURCE_MANAGER.CREATE_PLAN_DIRECTIVE( PLAN => 'SUB_PLAN1'
, GROUP_OR_SUBPLAN => 'BATCH_GROUP_SUB_PLAN_1'
, COMMENT => 'Batch sub plan 1 users sessions at level 1'
, CPU_P1 => 20
, CPU_P2 => 0);
DBMS_RESOURCE_MANAGER.CREATE_PLAN_DIRECTIVE( PLAN => 'SUB_PLAN1'
, GROUP_OR_SUBPLAN => 'OTHER_GROUPS'
, COMMENT => 'All other users sessions at level 2'
, CPU_P1 => 0
, CPU_P2 => 100);
DBMS_RESOURCE_MANAGER.CREATE_PLAN_DIRECTIVE( PLAN => 'SUB_PLAN2'
, GROUP_OR_SUBPLAN => 'ONLINE_GROUP_SUB_PLAN_2'
, COMMENT => 'Online sub plan 2 users sessions at level 1'
, CPU_P1 => 60
, CPU_P2 => 0);
DBMS_RESOURCE_MANAGER.CREATE_PLAN_DIRECTIVE( PLAN => 'SUB_PLAN2'
, GROUP_OR_SUBPLAN => 'BATCH_GROUP_SUB_PLAN_2'
, COMMENT => 'Batch sub plan 2 users sessions at level 1'
, CPU_P1 => 40
, CPU_P2 => 0);
DBMS_RESOURCE_MANAGER.CREATE_PLAN_DIRECTIVE( PLAN => 'SUB_PLAN2'
, GROUP_OR_SUBPLAN => 'OTHER_GROUPS'
, COMMENT => 'All other users sessions at level 2'
, CPU_P1 => 0
, CPU_P2 => 100);
-- +----------------------------------------------------------------------------+
-- | The preceding call to VALIDATE_PENDING_AREA is optional because the |
-- | validation is implicitly performed in SUBMIT_PENDING_AREA. |
-- +----------------------------------------------------------------------------+
DBMS_RESOURCE_MANAGER.VALIDATE_PENDING_AREA();
-- +----------------------------------------------------------------------------+
-- | Submit the pending area to Oracle! |
-- +----------------------------------------------------------------------------+
DBMS_RESOURCE_MANAGER.SUBMIT_PENDING_AREA();
END;
/
ALTER SYSTEM SET RESOURCE_MANAGER_PLAN = top_plan;

View File

@@ -0,0 +1,25 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : example_create_sequence.sql |
-- | CLASS : Examples |
-- | PURPOSE : Example SQL script that demonstrates how to create a sequence |
-- | number generator. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
DROP SEQUENCE user_id_seq
/
CREATE SEQUENCE user_id_seq
INCREMENT BY 1
START WITH 1000
NOMAXVALUE
NOCYCLE
/

View File

@@ -0,0 +1,120 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : example_create_table.sql |
-- | CLASS : Examples |
-- | PURPOSE : Simple create table script. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
/*
* --------------------------------------------------------
* ---------------- CREATE TABLE (DEPT) -------------------
* --------------------------------------------------------
*/
prompt Dropping Table (dept)...
DROP TABLE dept CASCADE CONSTRAINTS
/
prompt Creating Table (dept)...
CREATE TABLE dept (
deptno NUMBER(2)
, dname VARCHAR2(14)
, loc VARCHAR2(13)
)
TABLESPACE users
STORAGE (
INITIAL 128K
NEXT 128K
MINEXTENTS 1
MAXEXTENTS 121
PCTINCREASE 0
)
/
ALTER TABLE dept
ADD CONSTRAINT dept_pk PRIMARY KEY(deptno)
USING INDEX
TABLESPACE idx
STORAGE (
INITIAL 64K
NEXT 64K
MINEXTENTS 1
MAXEXTENTS 121
PCTINCREASE 0
)
/
ALTER TABLE dept
MODIFY ( dname CONSTRAINT dept_nn1 NOT NULL
)
/
/*
* -------------------------------------------------------
* ---------------- CREATE TABLE (EMP) -------------------
* -------------------------------------------------------
*/
prompt Dropping Table (emp)...
DROP TABLE emp CASCADE CONSTRAINTS
/
prompt Creating Table (emp)...
CREATE TABLE emp (
empno NUMBER(4)
, ename VARCHAR2(10)
, job VARCHAR2(9)
, mgr NUMBER(4)
, hiredate DATE
, sal NUMBER(7,2)
, comm NUMBER(7,2)
, deptno NUMBER(2)
)
TABLESPACE users
STORAGE (
INITIAL 128K
NEXT 128K
MINEXTENTS 1
MAXEXTENTS 121
PCTINCREASE 0
)
/
ALTER TABLE emp
ADD CONSTRAINT emp_pk PRIMARY KEY(empno)
USING INDEX
TABLESPACE idx
STORAGE (
INITIAL 64K
NEXT 64K
MINEXTENTS 1
MAXEXTENTS 121
PCTINCREASE 0
)
/
ALTER TABLE emp
MODIFY ( ename CONSTRAINT emp_nn1 NOT NULL
, job CONSTRAINT emp_nn2 NOT NULL
, hiredate CONSTRAINT emp_nn3 NOT NULL
)
/
ALTER TABLE emp
ADD CONSTRAINT emp_fk1 FOREIGN KEY (deptno)
REFERENCES dept(deptno)
/

View File

@@ -0,0 +1,155 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : example_create_table_buffer_pools.sql |
-- | CLASS : Examples |
-- | PURPOSE : Example SQL script that demonstrates how to create tables that |
-- | will exist in separate buffer pools. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
/*
** +---------------------------------------------------------------------------+
** | NOTES: |
** | |
** | DEFAULT Buffer Pool |
** | ------------------- |
** | (Still refered to as the database buffer cache) is always allocated in |
** | Oracle8 and higher. As with Oracle7, the normal LRU algorithm manages the |
** | data blocks in the default buffer pool. |
** | |
** | |
** | KEEP Buffer Pool |
** | ---------------- |
** | In Oracle7, the database allowed the DBA to define tables with the CACHE |
** | option. This allowed tables that where read in from a full table scan to |
** | be placed on the 'most recently used' (MTU) end of the 'least recently |
** | used' (LRU) list, as opposed to the LRU end. The idea was to keep database|
** | blocks that where read from a full table scan in the database buffer |
** | cache for a longer period of time before being aged out. These tables |
** | where | typically small tables, such as lookup tables. Oracle8 introduced |
** | the capability of reserving part of the default buffer pool for a "KEEP" |
** | buffer pool. This pool can be used as a cache for database blocks that |
** | should not be aged out. Keep in mind that as you allocate memory for the |
** | keep buffer pool, that you are taking away memory from the default buffer |
** | pool. If you undersize the KEEP buffer pool, objects will be aged out |
** | using the LRU algorithm, as with the default buffer pool. Also take care |
** | not to oversize this pool as this memory will go wasted and unused. |
** | |
** | RECYCLE Buffer Pool |
** | ------------------- |
** | The purpose of the RECYCLE buffer pool is to store memory blocks that are |
** | not likely to be reused again soon. This are usually very large objects, |
** | access to individual blocks may be very random and scattered. A prime |
** | candidate for the RECYCLE buffer pool. It is important to not create the |
** | size of this pool too small. Doing so may cause blocks to age out of the |
** | pool before an application of SQL statement uses them completely. If the |
** | block is aged out before the transaction is done with it, it needs to be |
** | re-read from disk, causing more I/O. |
** | |
** | |
** | Init.ora Settings |
** | ----------------- |
** | DB_BLOCK_BUFFERS = 2000 # Allocate 2000 blocks to the default buffer|
** | # cache. |
** | DB_BLOCK_LRU_LATCHES = 6 # Configure the number of LRU latches. The |
** | # default is CPU_COUNT/2 and the maximum |
** | # is CPU_COUNT. |
** | BUFFER_POOL_KEEP = (BUFFERS:100, LRU_LATCHES:2) |
** | # Configure the keep buffer pool. Assign 100|
** | # blocks to it from the default buffer |
** | # pool and 2 LRU latches. |
** | BUFFER_POOL_RECYCLE = (BUFFERS:100, LRU_LATCHES:1) |
** | # Configure the recycle buffer pool. Assign |
** | # 100 blocks to it from the database |
** | # buffer pool and 1 LRU latch. |
** | |
** | NOTE: Some documentation states to use 'nbuf,nlat' but this may not work |
** | correctly - use the full string ("buffers:nbuf","lru_latches:Nlat") |
** | |
** | Oracle9i NOTE !!! |
** | ----------------- |
** | The above database block cache parameters are deprecated in |
** | Oracle9i in favor of: --> <Parameter:DB_CACHE_SIZE> |
** | --> <Parameter:DB_KEEP_CACHE_SIZE> |
** | --> <Parameter:DB_RECYCLE_CACHE_SIZE> |
** | Oracle recommends that you use these new parameters instead. Also, |
** | BUFFER_POOL_KEEP cannot be combined with the new dynamic |
** | DB_KEEP_CACHE_SIZE parameter just as BUFFER_POOL_RECYCLE cannot be used |
** | with the dynamic parameter DB_RECYCLE_CACHE_SIZE. Combining these |
** | parameters in the same parameter file will produce an error. |
** | DB_BLOCK_BUFFERS, BUFFER_POOL_KEEP and BUFFER_POOL_RECYCLE are being |
** | retained for backward compatibility only. |
** +---------------------------------------------------------------------------+
*/
/*
** --------------------------------------------------------
** ----------- CREATE TABLE (EMP) ---------------
** ----------- BUFFER_POOL_KEEP ---------------
** --------------------------------------------------------
*/
prompt Dropping Table (emp)...
DROP TABLE emp CASCADE CONSTRAINTS
/
prompt Creating Table (emp)...
CREATE TABLE emp (
empno NUMBER(4)
, ename VARCHAR2(10)
, job VARCHAR2(9)
, mgr NUMBER(4)
, hiredate DATE
, sal NUMBER(7,2)
, comm NUMBER(7,2)
, deptno NUMBER(2)
)
TABLESPACE users
STORAGE (
INITIAL 128K
NEXT 128K
MINEXTENTS 1
MAXEXTENTS 121
PCTINCREASE 0
BUFFER_POOL KEEP
)
/
/*
** --------------------------------------------------------
** ----------- CREATE TABLE (DEPT) --------------
** ----------- BUFFER_POOL_RECYCLE --------------
** --------------------------------------------------------
*/
prompt Dropping Table (dept)...
DROP TABLE dept CASCADE CONSTRAINTS
/
prompt Creating Table (dept)...
CREATE TABLE dept (
deptno NUMBER(2)
, dname VARCHAR2(14)
, loc VARCHAR2(13)
)
TABLESPACE users
STORAGE (
INITIAL 128K
NEXT 128K
MINEXTENTS 1
MAXEXTENTS 121
PCTINCREASE 0
BUFFER_POOL RECYCLE
)
/

View File

@@ -0,0 +1,108 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : example_create_tablespace.sql |
-- | CLASS : Examples |
-- | PURPOSE : Example SQL script that demonstrates how to create several |
-- | types of tablespaces in Oracle7 - 11g. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
-- +-----------------------------------------------------------------+
-- | (Oracle9i and higher) |
-- | ORACLE MANAGED FILES (OMF) |
-- +-----------------------------------------------------------------+
CREATE TABLESPACE users
LOGGING DATAFILE SIZE 500M REUSE
AUTOEXTEND ON NEXT 1M MAXSIZE 500M
EXTENT MANAGEMENT LOCAL AUTOALLOCATE
SEGMENT SPACE MANAGEMENT AUTO
/
-- +-----------------------------------------------------------------+
-- | (Oracle9i and higher) |
-- | SEGMENT SPACE MANAGEMENT AUTO |
-- +-----------------------------------------------------------------+
CREATE TABLESPACE users
LOGGING DATAFILE '/u10/app/oradata/ORA920/users01.dbf' SIZE 500M REUSE
AUTOEXTEND ON NEXT 1M MAXSIZE 500M
EXTENT MANAGEMENT LOCAL AUTOALLOCATE
SEGMENT SPACE MANAGEMENT AUTO
/
-- +---------------------------------------------------------------------------+
-- | (Oracle8i and higher) - In version Oracle9i and higher, you |
-- | create the temporary tablespace as part |
-- | of the CREATE TABLESPACE statement: |
-- | |
-- | ... |
-- | DEFAULT TEMPORARY TABLESPACE temp |
-- | TEMPFILE '/u07/app/oradata/ORA920/temp01.dbf' |
-- | SIZE 500M REUSE |
-- | AUTOEXTEND ON NEXT 500M MAXSIZE 1500M |
-- | ... |
-- | TEMPORARY TABLESPACES |
-- +---------------------------------------------------------------------------+
CREATE TEMPORARY TABLESPACE temp
TEMPFILE '/u07/app/oradata/ORA920/temp01.dbf' SIZE 500M REUSE
AUTOEXTEND on NEXT 100M MAXSIZE unlimited
EXTENT MANAGEMENT LOCAL UNIFORM SIZE 1M
/
-- +-----------------------------------------------------------------+
-- | (Oracle8i and higher) |
-- | LOCALLY MANAGED TABLESPACES - with AUTOALLOCATE clause |
-- | |
-- | Use AUTOALLOACTE clause, if the tablespace is expected to |
-- | contain objects of varying sizes requiring different extent |
-- | sizes and having many extents. AUTOALLOCATE is default. |
-- +-----------------------------------------------------------------+
CREATE TABLESPACE users
LOGGING DATAFILE '/u10/app/oradata/ORA817/users01.dbf' SIZE 100M REUSE
AUTOEXTEND ON NEXT 100M MAXSIZE 500M
EXTENT MANAGEMENT LOCAL AUTOALLOCATE
/
-- +-----------------------------------------------------------------+
-- | (Oracle8i and higher) |
-- | LOCALLY MANAGED TABLESPACES - with UNIFORM SIZE clause |
-- | |
-- | Use UNIFORM SIZE clause if you want exact control over |
-- | unused space, and you can predict exactly the space to be |
-- | allocated for an object or objects and the number and size |
-- | of extents. Default extent size is 1M, if you do not specify |
-- | size parameter. |
-- +-----------------------------------------------------------------+
CREATE TABLESPACE users
LOGGING DATAFILE '/u10/app/oradata/ORA817/users01.dbf' SIZE 10M REUSE
AUTOEXTEND ON NEXT 1M MAXSIZE 500M
EXTENT MANAGEMENT LOCAL UNIFORM SIZE 512K
/
-- +-----------------------------------------------------------------+
-- | (All versions of Oracle) |
-- | DICTIONARY MANAGED TABLESPACE |
-- +-----------------------------------------------------------------+
CREATE TABLESPACE users
DATAFILE '/u10/app/oradata/ORA734/users01.dbf' SIZE 10M
DEFAULT STORAGE (initial 64k next 64k maxextents 121 pctincrease 0)
/

View File

@@ -0,0 +1,64 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : example_create_temporary_tables.sql |
-- | CLASS : Examples |
-- | PURPOSE : Example SQL script that demonstrates how to create temporary |
-- | tables. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
connect scott/tiger
set serveroutput on
Prompt ====================================================
Prompt CREATE TEMPORARY TABLE WITH DEFAULT SETTINGS...
Prompt (Oracle8i will use on commit delete rows by default)
Prompt ====================================================
Prompt
accept a1 Prompt "Hit <ENTER> to continue";
CREATE GLOBAL TEMPORARY TABLE mytemptab1 (
id NUMBER
, name VARCHAR2(500)
, average_salary NUMBER(15,2)
)
/
Prompt ================================================
Prompt CREATE TEMPORARY TABLE: on commit delete rows...
Prompt ================================================
Prompt
accept a1 Prompt "Hit <ENTER> to continue";
CREATE GLOBAL TEMPORARY TABLE mytemptab2 (
id NUMBER
, name VARCHAR2(500)
, average_salary NUMBER(15,2)
) ON COMMIT DELETE ROWS
/
Prompt ==================================================
Prompt CREATE TEMPORARY TABLE: on commit preserve rows...
Prompt ==================================================
Prompt
accept a1 Prompt "Hit <ENTER> to continue";
CREATE GLOBAL TEMPORARY TABLE mytemptab3 (
id NUMBER
, name VARCHAR2(500)
, average_salary NUMBER(15,2)
) ON COMMIT PRESERVE ROWS
/

View File

@@ -0,0 +1,244 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : example_create_user_tables.sql |
-- | CLASS : Examples |
-- | PURPOSE : Yet another SQL script that demonstrates how to sample tables |
-- | and a PL/SQL routine that populates those tables. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
/*
** +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*/
/*
CONNECT /
CREATE TABLESPACE users
DATAFILE '/u10/app/oradata/ORA901/users01.dbf' SIZE 10M
/
CREATE TABLESPACE idx
DATAFILE '/u09/app/oradata/ORA901/idx01.dbf' SIZE 10M
/
CREATE USER jhunter IDENTIFIED BY jhunter
DEFAULT TABLESPACE users
TEMPORARY TABLESPACE temp
/
GRANT dba, resource, connect TO jhunter
/
*/
/*
** +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*/
CONNECT jhunter/jhunter
/*
** +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*/
DROP TABLE user_names CASCADE CONSTRAINTS
/
CREATE TABLE user_names (
name_intr_no NUMBER(15)
, name VARCHAR2(30)
, age NUMBER(3)
, update_log_date DATE
)
TABLESPACE users
STORAGE (
INITIAL 64K
NEXT 64K
MINEXTENTS 1
MAXEXTENTS 100
PCTINCREASE 0
)
/
ALTER TABLE user_names
ADD CONSTRAINT user_names_pk PRIMARY KEY(name_intr_no)
USING INDEX
TABLESPACE idx
STORAGE (
INITIAL 28K
NEXT 28K
MINEXTENTS 1
MAXEXTENTS 100
PCTINCREASE 0
)
/
ALTER TABLE user_names
MODIFY ( name CONSTRAINT user_names_nn1 NOT NULL
, age CONSTRAINT user_names_nn2 NOT NULL
, update_log_date CONSTRAINT user_names_nn3 NOT NULL
)
/
/*
** +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*/
DROP TABLE user_names_phone
/
CREATE TABLE user_names_phone (
name_intr_no number(15)
, phone_number varchar2(12)
, country_code varchar2(15)
)
TABLESPACE users
STORAGE (
INITIAL 64K
NEXT 64K
MINEXTENTS 1
MAXEXTENTS 100
PCTINCREASE 0
)
/
ALTER TABLE user_names_phone
ADD CONSTRAINT user_names_phone_pk PRIMARY KEY(name_intr_no, phone_number)
USING INDEX
TABLESPACE idx
STORAGE (
INITIAL 28K
NEXT 28K
MINEXTENTS 1
MAXEXTENTS 100
PCTINCREASE 0
)
/
ALTER TABLE user_names_phone
MODIFY ( country_code CONSTRAINT user_names_phone_nn1 NOT NULL
)
/
ALTER TABLE user_names_phone
ADD CONSTRAINT user_names_phone_fk1 FOREIGN KEY (name_intr_no)
REFERENCES user_names(name_intr_no)
/
/*
** +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*/
DROP TABLE user_names_company
/
CREATE TABLE user_names_company (
name_intr_no number(15)
, company_code varchar2(15)
)
TABLESPACE users
STORAGE (
INITIAL 64K
NEXT 64K
MINEXTENTS 1
MAXEXTENTS 100
PCTINCREASE 0
)
/
/*
** +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*/
create or replace procedure insert_user_names (
num_records IN number)
IS
CURSOR csr1 IS
SELECT max(name_intr_no)
FROM user_names;
max_intr_no NUMBER;
BEGIN
/*
|| ENABLE DBMS_OUTPUT
*/
DBMS_OUTPUT.ENABLE;
/*
|| SET ROLLBACK SEGMENT TO THE LARGEST ONE: rbs2
*/
DECLARE
incomplete_transaction EXCEPTION;
pragma EXCEPTION_INIT (incomplete_transaction, -01453);
BEGIN
SET TRANSACTION USE ROLLBACK SEGMENT rbs2;
EXCEPTION
WHEN incomplete_transaction THEN
ROLLBACK;
DBMS_OUTPUT.PUT_LINE('Needed to rollback previous transaction');
SET TRANSACTION USE ROLLBACK SEGMENT rbs2;
END;
/*
|| INSERT DUMMY RECORDS INTO THE USER DEFINED
|| TABLE: user_names. THE FIRST PARAMETER TO THIS
|| FUNCTION WILL DETERMINE THE NUMBER OF RECORDS
|| TO INSERT.
*/
DECLARE
fail_rollback_segment EXCEPTION;
pragma EXCEPTION_INIT (fail_rollback_segment, -01562);
BEGIN
OPEN csr1;
FETCH csr1 INTO max_intr_no;
CLOSE csr1;
max_intr_no := NVL(max_intr_no,0) + 1;
FOR loop_index IN max_intr_no .. (max_intr_no + (num_records-1))
LOOP
INSERT INTO user_names
VALUES (loop_index, 'Oracle DBA', 30, SYSDATE);
INSERT INTO user_names_phone
VALUES (loop_index, '412-555-1234', 'USA');
INSERT INTO user_names_company
VALUES (loop_index, 'DBA Zone');
IF (MOD(loop_index, 100) = 0) THEN
COMMIT;
DBMS_OUTPUT.PUT_LINE('Commit point reached at: ' || loop_index || '.');
END IF;
END LOOP;
COMMIT;
DBMS_OUTPUT.NEW_LINE;
DBMS_OUTPUT.PUT_LINE('Successfully inserted ' || num_records ||
' records into table: user_names');
EXCEPTION
WHEN fail_rollback_segment THEN
ROLLBACK;
DBMS_OUTPUT.PUT_LINE('Fail to extent rollback segment: RBS2');
END;
END;
/
show errors;

View File

@@ -0,0 +1,152 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : example_database_resource_manager_setup.sql |
-- | CLASS : Examples |
-- | PURPOSE : Example SQL syntax used setup and configure database resource |
-- | manager (DRM). |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
connect system/manager
set serveroutput on
Prompt ====================
Prompt Clean-Up DRM Area...
Prompt ====================
Prompt
accept a1 Prompt "Hit <ENTER> to continue";
alter system set resource_manager_plan=system_plan;
exec DBMS_RESOURCE_MANAGER.create_pending_area;
-- exec dbms_resource_manager.DELETE_PLAN_CASCADE('daytime_plan');
-- exec dbms_resource_manager.DELETE_PLAN_CASCADE('night_weekend_plan');
exec dbms_resource_manager.DELETE_PLAN_DIRECTIVE('daytime_plan', 'oltp_group');
exec dbms_resource_manager.DELETE_PLAN_DIRECTIVE('daytime_plan', 'batch_group');
exec dbms_resource_manager.DELETE_PLAN_DIRECTIVE('daytime_plan', 'other_groups');
exec dbms_resource_manager.DELETE_PLAN_DIRECTIVE('night_weekend_plan', 'oltp_group');
exec dbms_resource_manager.DELETE_PLAN_DIRECTIVE('night_weekend_plan', 'batch_group');
exec dbms_resource_manager.DELETE_PLAN_DIRECTIVE('night_weekend_plan', 'other_groups');
exec dbms_resource_manager.DELETE_PLAN('daytime_plan');
exec dbms_resource_manager.DELETE_PLAN('night_weekend_plan');
exec dbms_resource_manager.DELETE_CONSUMER_GROUP('oltp_group');
exec dbms_resource_manager.DELETE_CONSUMER_GROUP('batch_group');
exec DBMS_RESOURCE_MANAGER.validate_pending_area;
exec DBMS_RESOURCE_MANAGER.submit_pending_area;
Prompt ========================
Prompt Creating Pending Area...
Prompt ========================
Prompt
accept a1 Prompt "Hit <ENTER> to continue";
exec DBMS_RESOURCE_MANAGER.create_pending_area;
Prompt ================================
Prompt Create Resource Plan Template...
Prompt ================================
Prompt
accept a1 Prompt "Hit <ENTER> to continue";
exec DBMS_RESOURCE_MANAGER.create_plan('daytime_plan', 'Plan for daytime processing');
exec DBMS_RESOURCE_MANAGER.create_plan('night_weekend_plan', 'Plan for nights and weekends');
Prompt ==========================================
Prompt Create Resource Consumer Group Template...
Prompt ==========================================
Prompt
accept a1 Prompt "Hit <ENTER> to continue";
exec DBMS_RESOURCE_MANAGER.create_consumer_group('oltp_group', 'data entry specialist');
exec DBMS_RESOURCE_MANAGER.create_consumer_group('batch_group', 'nightly batch jobs');
Prompt ==================================
Prompt Create Resource Plan Directives...
Prompt ==================================
Prompt
accept a1 Prompt "Hit <ENTER> to continue";
exec DBMS_RESOURCE_MANAGER.create_plan_directive('daytime_plan', 'oltp_group', 'Daytime rule for oltp_group users', cpu_p1 => 90, parallel_degree_limit_p1 => 0);
exec DBMS_RESOURCE_MANAGER.create_plan_directive('daytime_plan', 'batch_group', 'Daytime rule for batch_group users', cpu_p1 => 10, parallel_degree_limit_p1 => 0);
exec DBMS_RESOURCE_MANAGER.create_plan_directive('daytime_plan', 'other_groups', 'Daytime rules for all other users/groups', cpu_p2 => 100, parallel_degree_limit_p1 => 0);
exec DBMS_RESOURCE_MANAGER.create_plan_directive('night_weekend_plan', 'oltp_group', 'Night/Weekend rule for oltp_group users', cpu_p1 => 10, parallel_degree_limit_p1 => 0);
exec DBMS_RESOURCE_MANAGER.create_plan_directive('night_weekend_plan', 'batch_group', 'Night/Weekend rule for batch_group users', cpu_p1 => 90, parallel_degree_limit_p1 => 0);
exec DBMS_RESOURCE_MANAGER.create_plan_directive('night_weekend_plan', 'other_groups', 'Night/Weekend rules for all other users/groups', cpu_p2 => 100, parallel_degree_limit_p1 => 0);
Prompt ==================================
Prompt Confirm (Validate) Pending Area...
Prompt ==================================
Prompt
accept a1 Prompt "Hit <ENTER> to continue";
exec DBMS_RESOURCE_MANAGER.validate_pending_area;
Prompt ======================
Prompt Submit Pending Area...
Prompt ======================
Prompt
accept a1 Prompt "Hit <ENTER> to continue";
exec DBMS_RESOURCE_MANAGER.submit_pending_area;
-- exec DBMS_RESOURCE_MANAGER.clear_pending_area;
Prompt =========================================================================
Prompt ALLOW USER SCOTT TO SWITCH BETWEEN (oltp_group and batch_group) GROUPS...
Prompt =========================================================================
Prompt
accept a1 Prompt "Hit <ENTER> to continue";
exec DBMS_RESOURCE_MANAGER_PRIVS.grant_switch_consumer_group('scott', 'oltp_group', FALSE);
exec DBMS_RESOURCE_MANAGER_PRIVS.grant_switch_consumer_group('scott', 'batch_group', FALSE);
Prompt =========================================================
Prompt ASSIGN USER SCOTT TO INITIAL CONSUMER GROUP OF oltp_group...
Prompt =========================================================
Prompt
accept a1 Prompt "Hit <ENTER> to continue";
exec DBMS_RESOURCE_MANAGER.set_initial_consumer_group('scott', 'oltp_group');
Prompt ==============================================
Prompt SWITCH USER SCOTT INTO THE oltp_group GROUP...
Prompt ==============================================
Prompt
accept a1 Prompt "Hit <ENTER> to continue";
exec DBMS_RESOURCE_MANAGER.switch_consumer_group_for_user('scott', 'oltp_group');
Prompt ==============================
Prompt Switch to DAYTIME_PLAN plan...
Prompt ==============================
Prompt
accept a1 Prompt "Hit <ENTER> to continue";
ALTER SYSTEM SET resource_manager_plan=daytime_plan;

View File

@@ -0,0 +1,90 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : example_drop_unused_column.sql |
-- | CLASS : Examples |
-- | PURPOSE : Example SQL syntax used to drop unused columns from a table. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
connect scott/tiger
set serveroutput on
Prompt ======================
Prompt DROP existing table...
Prompt ======================
Prompt
accept a1 Prompt "Hit <ENTER> to continue";
DROP TABLE d_table
/
Prompt =======================
Prompt CREATE TESTING TABLE...
Prompt =======================
Prompt
accept a1 Prompt "Hit <ENTER> to continue";
CREATE TABLE d_table (
id_no NUMBER
, name VARCHAR2(100)
, d_column VARCHAR2(100)
)
/
Prompt ========================
Prompt MARK COLUMN AS UNUSED...
Prompt ========================
Prompt
accept a1 Prompt "Hit <ENTER> to continue";
ALTER TABLE d_table SET UNUSED COLUMN d_column;
Prompt =======================================
Prompt QUERY ALL TABLES WITH UNUSED COLUMNS...
Prompt =======================================
Prompt
accept a1 Prompt "Hit <ENTER> to continue";
SELECT * FROM sys.dba_unused_col_tabs;
Prompt ======================================
Prompt PHYSICALLY REMOVE THE UNUSED COLUMN...
Prompt ======================================
Prompt
accept a1 Prompt "Hit <ENTER> to continue";
ALTER TABLE d_table DROP UNUSED COLUMNS;
Prompt ================================================
Prompt IF YOU WANTED TO PHYSICALLY REMOVE THE COLUMN...
Prompt ================================================
Prompt
accept a1 Prompt "Hit <ENTER> to continue";
-- ALTER TABLE d_table DROP COLUMN d_column;
Prompt =========================================
Prompt OPTIONALLY SYNTAX FOR REMOVING COLUMNS...
Prompt =========================================
Prompt
Prompt ALTER TABLE d_table DROP COLUMN d_column CASCADE CONSTRAINTS;
Prompt ALTER TABLE d_table DROP COLUMN d_column INVALIDATE;
Prompt ALTER TABLE d_table DROP COLUMN d_column CHECKPOINT 1000;
Prompt
accept a1 Prompt "Hit <ENTER> to EXIT";

View File

@@ -0,0 +1,664 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : example_lob_demonstration.sql |
-- | CLASS : Examples |
-- | PURPOSE : Example script that demonstrates how to manipulate LOBs using |
-- | SQL. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
Prompt
Prompt Dropping all testing LOB tables...
Prompt ----------------------------------
DROP TABLE test_lobs;
DROP DIRECTORY tmp_dir;
DROP TABLE long_data;
Prompt Create TEST_LOB table...
Prompt ------------------------
CREATE TABLE test_lobs (
c1 NUMBER
, c2 CLOB
, c3 BFILE
, c4 BLOB
)
LOB (c2) STORE AS (ENABLE STORAGE IN ROW)
LOB (c4) STORE AS (DISABLE STORAGE IN ROW)
/
Prompt Inserting row with NO LOB locators...
Prompt -------------------------------------
INSERT INTO test_lobs
VALUES (1, null, null, null)
/
Prompt Inserting row with LOB locators (locators created but point to nothing) ...
Prompt ---------------------------------------------------------------------------
INSERT INTO test_lobs
VALUES (2, empty_clob(), BFILENAME(null,null), empty_blob())
/
Prompt +------------------------------------------------------------------------+
Prompt | It is possible to insert data directly up to 4K. |
Prompt | Even though you are only really accessing the locator, the data is |
Prompt | stored as appropriate behind the scenes. When inserting directly into |
Prompt | a BLOB either the string must be hex as an implicit HEXTORAW will be |
Prompt | done or you can call UTL_RAW.CAST_TO_RAW('the string') to convert it |
Prompt | for you. Note '48656C6C6F' = 'Hello'. |
Prompt +------------------------------------------------------------------------+
Prompt
INSERT INTO test_lobs
VALUES ( 3
, 'Some data for record 3.'
, BFILENAME(null,null)
, '48656C6C6F'||UTL_RAW.CAST_TO_RAW(' there!'))
/
Prompt +---------------------------------------------------------------------------+
Prompt | Now it is time to select back the data. If you were to try to SELECT |
Prompt | all three columns from the test_lobs table, SQL*Plus would give you an |
Prompt | error: |
Prompt | SQL> SELECT * FROM test_lobs; |
Prompt | SQL> Column or attribute type can not be displayed by SQL*Plus |
Prompt | |
Prompt | SQL*Plus cannot convert the data behind the locator to hex for the BLOB |
Prompt | column (c3) nor can it interpret a locator for a BFILE (even when null). |
Prompt | In order for this query to run successfully, you would need to enter: |
Prompt | |
Prompt | column c2 format a60 wrap |
Prompt | |
Prompt | and ONLY select columns c1 and c2: |
Prompt +---------------------------------------------------------------------------+
Prompt
COLUMN c2 FORMAT a60 WRAP
Prompt Query CLOB records...
Prompt ---------------------
SELECT c1, c2 FROM test_lobs;
Prompt +---------------------------------------------------------------------------+
Prompt | In the above query, we are really fetching only the LOB locator. SQL*Plus |
Prompt | will also then fetch the corresponding data. If we use a 3GL or PL/SQL we |
Prompt | can insert data from a character string variable but not select it into |
Prompt | one. For example: |
Prompt +---------------------------------------------------------------------------+
Prompt
DECLARE
c_lob VARCHAR2(10);
BEGIN
c_lob := 'Record 4.';
INSERT INTO test_lobs
VALUES (4,c_lob,BFILENAME(null,null), EMPTY_BLOB());
END;
/
DECLARE
c_lob VARCHAR2(10);
BEGIN
SELECT c2 INTO c_lob
FROM test_lobs
WHERE c1 = 4;
END;
/
Prompt +-------------------------------------------------------------+
Prompt | NEW IN 8i |
Prompt | ========= |
Prompt | From version 8.1 it is now possible to convert data stored |
Prompt | in longs and long raws to CLOBs and BLOBs respectively. |
Prompt | This is done using the TO_LOB function. |
Prompt +-------------------------------------------------------------+
Prompt
Prompt Create LONG_DATA table...
Prompt -------------------------
CREATE TABLE long_data (
c1 NUMBER
, c2 LONG
)
/
INSERT INTO long_data
VALUES (1, 'This is some long data to be migrated to a CLOB')
/
Prompt TO_LOB may be used in CREATE TABLE AS SELECT or INSERT...SELECT statements
Prompt ---------------------------------------------------------------------------
INSERT INTO test_lobs
SELECT 5, TO_LOB(c2), null, null
FROM long_data
/
Prompt Query CLOB records...
Prompt ---------------------
SELECT c1, c2
FROM test_lobs
WHERE c1 = 5;
ROLLBACK
/
Prompt Creating text file /tmp/rec2.txt...
Prompt -----------------------------------
!echo "This is some data for record 2's BFILE column. The data is\nstored in a file called \"rec2.txt\". The file is placed in \n/tmp.\nThe file comprises a total of 4 lines of text." > /tmp/rec2.txt
Prompt Creating text file /tmp/rec3.txt...
Prompt -----------------------------------
!echo "This is some data for record 3's BFILE column. The data is\nstored in a file called \"rec3.txt\". The file is placed in\n/tmp. The file comprises a total of 5 lines of text and\nwill be used to demonstrate the functionality of the \nDBMS_LOB package." > /tmp/rec3.txt
Prompt First create the ALIAS for the directory /tmp
Prompt ---------------------------------------------
CREATE DIRECTORY tmp_dir AS '/tmp'
/
Prompt +------------------------------------------------------------+
Prompt | Now update the records to associate the BFILE column with |
Prompt | the two files created above. |
Prompt +------------------------------------------------------------+
Prompt
UPDATE test_lobs
SET c3 = BFILENAME('TMP_DIR','rec2.txt')
WHERE c1 = 2
/
UPDATE test_lobs
SET c3 = BFILENAME('TMP_DIR','rec3.txt')
WHERE c1 = 3
/
commit;
Prompt +---------------------------------------------------------------------+
Prompt | Note the files associated with these columns are READ-ONLY through |
Prompt | Oracle. |
Prompt | They must be maintained via the operating system itself. To access |
Prompt | the BFILE columns you must use the DBMS_LOB package or OCI. |
Prompt | |
Prompt | Getting lengths of the LOB data. Notice the zero lengths where |
Prompt | "empty" locators were specified. |
Prompt +---------------------------------------------------------------------+
COLUMN len_c2 FORMAT 9999
COLUMN len_c3 FORMAT 9999
COLUMN len_c4 FORMAT 9999
SELECT
c1
, DBMS_LOB.GETLENGTH(c2) len_c2
, DBMS_LOB.GETLENGTH(c3) len_c3
, DBMS_LOB.GETLENGTH(c4) len_c4
FROM test_lobs
/
Prompt +---------------------------------------------------------------------------------+
Prompt | Using SUBSTR/INSTR - both may be used on all 3 types (CLOB, BLOB and --BFILE) |
Prompt | however for BFILEs the file must first have been opened - hence the functions |
Prompt | may only be used within PL/SQL in this case. |
Prompt | For SUBSTR the parameters are LOB, amount, offset - the opposite to the |
Prompt | standard substr function; for INSTR they are LOB, string, offset, occurence, |
Prompt | the latter 2 defaulting to 1 if omitted. So the following does a substr from |
Prompt | offset 3 in the CLOB for 9 characters and returns the first occurence of the |
Prompt | binary string representing "ello" in the BLOB. |
Prompt +---------------------------------------------------------------------------------+
COLUMN sub_c2 FORMAT a10
COLUMN ins_c4 FORMAT 99
SELECT
c1
, DBMS_LOB.SUBSTR(c2,9,3) sub_c2
, DBMS_LOB.INSTR(c4,UTL_RAW.CAST_TO_RAW('ello'),1,1) ins_c4
FROM test_lobs
/
Prompt +----------------------------------------------------------------+
Prompt | The following PL/SQL block demonstrates some of the DBMS_LOB |
Prompt | functionality. Note the use of "set long 1000" to prevent the |
Prompt | output data from being truncated. |
Prompt +----------------------------------------------------------------+
SET SERVEROUTPUT ON
SET LONG 1000
DECLARE
b_lob BLOB;
c_lob CLOB;
c_lob2 CLOB;
bf BFILE;
buf varchar2(100) :=
'This is some text to put into a CLOB column in the' ||
chr(10) ||
'database. The data spans 2 lines.';
n number;
fn varchar2(50); --Filename
fd varchar2(50); --Directory alias
--Procedure to print out the LOB value from c_lob, one line
--at a time..
PROCEDURE print_clob IS
offset number;
len number;
o_buf varchar2(200);
amount number; --}
f_amt number := 0; --}To hold the amount of data
f_amt2 number; --}to be read or that has been
amt2 number := -1; --}read
BEGIN
len := DBMS_LOB.GETLENGTH(c_lob);
offset := 1;
WHILE len > 0 loop
amount := DBMS_LOB.INSTR(c_lob,chr(10),offset,1);
--Amount returned is the count from the start of the file,
--not from the offset.
IF amount = 0 THEN
--No more linefeeds so need to read remaining data.
amount := len;
amt2 := amount;
ELSE
f_amt2 := amount; --Store position of next LF
amount := amount - f_amt; --Calc position from last LF
f_amt := f_amt2; --Store position for next time
amt2 := amount - 1; --Read up to but not the LF
END IF;
IF amt2 != 0 THEN
--If there is a linefeed as the first character then ignore.
DBMS_LOB.READ(c_lob,amt2,offset,o_buf);
dbms_output.put_line(o_buf);
END IF;
len := len - amount;
offset := offset+amount;
END LOOP;
END;
BEGIN
--For record 1 we did not initialise the locators so do so now.
--Note the RETURNING clause will retrieve the new lob locators so
--we do not need to perform an extra select. The update also
--ensures the corresponding row is locked.
UPDATE test_lobs SET c2 = EMPTY_CLOB(), c4 = EMPTY_BLOB()
WHERE c1 = 1 RETURNING c2, c4 INTO c_lob, b_lob;
--Also select the CLOB locator for record 2.
SELECT c2 INTO c_lob2 FROM test_lobs where c1 = 3;
--Write the above buffer into the CLOB column. Offset is 1, amount
--is the size of the buffer.
DBMS_LOB.WRITE(c_lob,length(buf),1,buf);
--See what we've got - a line at a time.
print_clob;
--Add some more data to the above column and row. First commit what
--we have. Note when we commit, under 8.0, our LOB locators we
--previously held in c_lob, b_lob and c_lob2 will be lost and so must be
--reselected. **NEW 8i**: under 8.1 LOB locators may span transactions
--for read purposes, thus we no longer need to reselect c_lob2.
commit;
--We must lock the row we are going to update through DBMS_LOB.
SELECT c2 INTO c_lob FROM test_lobs WHERE c1 = 1 FOR UPDATE;
--**NEW 8i**: no longer need this select:
--select c2 into c_lob2 from test_lobs where c1 = 3;
--First append a linefeed then some data from another CLOB.
--Under 8.0 this was a two step process, first you had to get the
--the length of the LOB and secondly write the data using an offset
--of the length plus one. **NEW 8i**: with 8.1 you have a WRITEAPPEND
--function that does the two steps in a single call.
--**NEW 8i**: no longer need to get the length:
--n := DBMS_LOB.GETLENGTH(c_lob)+1;
--DBMS_LOB.WRITE(c_lob,1,n,chr(10)); -- 1 char from offset n
DBMS_LOB.WRITEAPPEND(c_lob,1,chr(10)); -- **NEW 8i**
DBMS_LOB.APPEND(c_lob,c_lob2);
dbms_output.put_line(chr(10));
print_clob;
--Compare c_lob2 with the third line of c_lob - they should be
--the same - in which case remove it. Note the TRIM function takes
--the size at which you wish the LOB to end up, NOT how much you
--want to remove.
n := DBMS_LOB.GETLENGTH(c_lob) - DBMS_LOB.GETLENGTH(c_lob2);
IF DBMS_LOB.COMPARE(c_lob,c_lob2,DBMS_LOB.GETLENGTH(c_lob2),n+1,1) = 0 THEN
DBMS_LOB.TRIM(c_lob,n-1);
END IF;
dbms_output.put_line(chr(10));
print_clob;
--Remove the data from the column completely, ie use ERASE to
--remove all bytes from offset 1. Note unlike TRIM, ERASE does not
--cause the length of the LOB to be shortened - all bytes are simply
--set to zero. Thus GETLENGTH will return 0 after TRIM'ing all bytes
--but the original length after ERASE'ing.
n := DBMS_LOB.GETLENGTH(c_lob);
DBMS_LOB.ERASE(c_lob,n,1);
--Add data from c_lob2 plus a trailing linefeed.
DBMS_LOB.COPY(c_lob,c_lob2,DBMS_LOB.GETLENGTH(c_lob2),1,1);
--**NEW 8i**: could simply use WRITEAPPEND here.
n := DBMS_LOB.GETLENGTH(c_lob2)+1;
DBMS_LOB.WRITE(c_lob,1,n,chr(10)); -- 1 char from offset n
--Now append the column with data read from one of the BFILE
--columns.
select c3 into bf from test_lobs where c1 = 3;
--First get and output the file details.
DBMS_LOB.FILEGETNAME(bf,fd,fn);
dbms_output.put_line(chr(10));
dbms_output.put_line('Appending data from file '||fn||
' in directory aliased by '||fd||':');
dbms_output.put_line(chr(10));
--Open the file to read from it - first checking that it does in
--fact still exist in the O/S and that it is not already open.
IF DBMS_LOB.FILEEXISTS(bf) = 1 and
DBMS_LOB.FILEISOPEN(bf) = 0 THEN
DBMS_LOB.FILEOPEN(bf);
END IF;
DBMS_LOB.LOADFROMFILE(c_lob,bf,DBMS_LOB.GETLENGTH(bf),n+1,1);
DBMS_LOB.FILECLOSE(bf); -- could use DBMS_LOB.FILECLOSEALL;
print_clob;
commit;
END;
/
COMMIT;
SELECT c1, c2
FROM test_lobs
/
Prompt +------------------------------------------------------------------------+
Prompt | An important thing to note when using LOB locators within DBMS_LOB |
Prompt | and PL/SQL is that a given locator always gives a read consistent |
Prompt | image from when it was selected. You will see any changes that you |
Prompt | make to the LOB using that locator and DBMS_LOB, but not those made, |
Prompt | even in the same transaction, through other LOB locators pointing to |
Prompt | the same LOB values or made via SQL directly. For example: |
Prompt +------------------------------------------------------------------------+
DECLARE
c_lob CLOB;
BEGIN
SELECT c2
INTO c_lob
FROM test_lobs
WHERE c1 = 1;
DBMS_OUTPUT.PUT_LINE('Before update length of c2 is '||
DBMS_LOB.GETLENGTH(c_lob));
UPDATE TEST_LOBS
SET c2 = 'This is a string.' where c1 = 1;
DBMS_OUTPUT.PUT_LINE('After update length of c2 is '||
DBMS_LOB.GETLENGTH(c_lob));
SELECT c2
INTO c_lob
FROM test_lobs
WHERE c1 = 1;
DBMS_OUTPUT.PUT_LINE('After reselecting locator length of c2 is '||
DBMS_LOB.GETLENGTH(c_lob));
ROLLBACK;
END;
/
COMMIT;
Prompt +--------------------------------------------------------------------------+
Prompt | NEW IN 8i |
Prompt | ========= |
Prompt | The following PL/SQL blocks demonstrate the remaining new DBMS_LOB |
Prompt | functionality introduced in version 8.1. |
Prompt | |
Prompt | Temporary LOBs |
Prompt | ============== |
Prompt | In version 8.1 it is now possible to create temporary LOBs. These are |
Prompt | LOB locators that point to LOB values held in the user's temporary |
Prompt | tablespace. Temporary LOBs are automatically initialised upon creation |
Prompt | and exist for the duration specified in the create command or until |
Prompt | explicitly freed by the user. The duration of a temporary LOB may be |
Prompt | be session or call. At the end of the given duration the temporary |
Prompt | LOB is automatically deleted. Temporary LOBs can be used in the |
Prompt | same way as normal internal LOBs through the DBMS_LOB package (note |
Prompt | there is no temporary version of a BFILE), however being only part of |
Prompt | the temporary tablespace they are not permanently stored in the database |
Prompt | and they cause no rollback or undo information to be generated. |
Prompt | Temporary LOBs may be cached though. Because versioning (ie keeping |
Prompt | copies of pages prior to updates) is not performed for temporary LOBs, |
Prompt | if a temporary LOB locator is copied and then used to update the LOB |
Prompt | value, the whole LOB value must be copied in order to maintain a read |
Prompt | consistent image via both locators. For this reason it is recommended |
Prompt | that whenever LOB locators are passed as IN OUT or OUT parameters to |
Prompt | procedures, functions or methods, NOCOPY is specified so they are |
Prompt | passed by reference. |
Prompt | |
Prompt | The following example uses a temporary LOB to reverse one of the LOB |
Prompt | values in the table and then inserts the reversed LOB as a new row. |
Prompt +--------------------------------------------------------------------------+
DECLARE
c_lob CLOB; --permanent LOB locator
t_lob CLOB; --temporary LOB locator
buf varchar2(32000); --}this example assumes the LOB is
buf2 varchar2(32000); --}less than 32K.
chunk number;
len number;
offset number;
amount number;
BEGIN
SELECT c2 INTO c_lob FROM test_lobs WHERE c1 = 1;
--Create a temporary LOB. The parameters to CREATETEMPORARY are
--locator, use caching or not and duration. Set no caching and a
--duration of call since the temporary LOB is not required outside
--of this PL/SQL block.
DBMS_LOB.CREATETEMPORARY(t_lob,FALSE,DBMS_LOB.CALL); --**NEW 8i**
--**NEW 8i**: Use GETCHUNKSIZE to get the amount of space used in a LOB
--chunk for storing the LOB value. Using this amount for reads and
--writes of the LOB will improve performance.
chunk := DBMS_LOB.GETCHUNKSIZE(c_lob);
DBMS_OUTPUT.PUT_LINE('Chunksize of column c2 is '||chunk);
DBMS_OUTPUT.PUT_LINE('Chunksize of temporary LOB is '||
DBMS_LOB.GETCHUNKSIZE(t_lob)); --for info only
len := DBMS_LOB.GETLENGTH(c_lob);
offset := 1;
buf := null;
WHILE offset < len loop
IF len - (offset-1) > chunk then
amount := chunk;
ELSE
amount := len - (offset-1);
END IF;
buf2 := null;
DBMS_LOB.READ(c_lob,amount,offset,buf2);
buf := buf||buf2;
offset := offset + amount;
END LOOP;
--Reverse the read data and write it to the temporary LOB.
buf2 := null;
FOR i IN reverse 1..len LOOP
buf2 := buf2||substr(buf,i,1);
END LOOP;
--Write the whole lot in one go. Note, if this was a large
--amount of data then ideally it should be written using the
--available chunksize of the temporary LOB.
DBMS_LOB.WRITEAPPEND(t_lob,len,buf2); --**NEW 8i**
--Now insert a new row into the table setting the CLOB column to
--the value of the temporary LOB. This can be done in one of
--two ways:
--(i) A new row can be inserted with an empty locator, the locator
-- retrieved and the LOB value copied with DBMS_LOB.COPY.
--(ii) A new row can be inserted passing the temporary LOB locator
-- as a bind variable to the insert.
--
--Using the second method:
INSERT INTO test_lobs VALUES (5,t_lob,null,null) RETURNING c2 INTO c_lob;
--Free the temporary LOB explicitly.
IF DBMS_LOB.ISTEMPORARY(t_lob) = 1 THEN
DBMS_LOB.FREETEMPORARY(t_lob);
END IF;
DBMS_OUTPUT.PUT_LINE('Length of CLOB inserted into record 5 is '||
DBMS_LOB.GETLENGTH(c_lob));
COMMIT;
END;
/
Prompt Query CLOB records...
Prompt ---------------------
SELECT c1, c2
FROM test_lobs
WHERE c1 = 5
/
Prompt +---------------------------------------------------------------------------+
Prompt | OPEN AND CLOSE OPERATIONS |
Prompt | ========================= |
Prompt | Under version 8.0 the only concept of opening and closing a LOB applies |
Prompt | to BFILEs and the opening and closing of the physical O/S files they |
Prompt | represent. **NEW 8i**: With 8.1 it is now possible to open and close |
Prompt | any type of LOB. The new calls introduced for this functionality are |
Prompt | DBMS_LOB.OPEN, DBMS_LOB.CLOSE and DBMS_LOB.ISOPEN. When the given |
Prompt | locator is a BFILE, these three routines behave as DBMS_LOB.FILEOPEN, |
Prompt | DBMS_LOB.FILECLOSE and DBMS_LOB.FILEISOPEN. When applied to internal |
Prompt | LOBs they have the effect of batching up any writes such that triggers |
Prompt | on an extensible index will not fire until the DBMS_LOB.CLOSE is called. |
Prompt | When a LOB is opened it is with a mode of either read-only or read/write. |
Prompt | Setting this mode to read-only, prevents any writes from being performed |
Prompt | on the LOB in the current transaction until the LOB is closed. Note it |
Prompt | is an error to attempt to open a BFILE for read/write. The concept of |
Prompt | openness itself applies to a LOB rather than a locator, hence a LOB may |
Prompt | only be opened once within a transaction and closed only when open. |
Prompt | Attempting to do otherwise will result in an error. |
Prompt | |
Prompt | NOTE: |
Prompt | ===== |
Prompt | The following code segment will give: |
Prompt | |
Prompt | ORA-22294: cannot update a LOB opened in read-only mode |
Prompt | Closing LOB via locator 2 |
Prompt +---------------------------------------------------------------------------+
DECLARE
c_lob1 CLOB;
c_lob2 CLOB;
BEGIN
-- Select without locking the LOB.
SELECT c2 INTO c_lob1 FROM test_lobs WHERE c1 = 2;
c_lob2 := c_lob1;
-- Open the LOB as read-only using locator 1.
DBMS_LOB.OPEN(c_lob1,DBMS_LOB.LOB_READONLY); --**NEW 8i**
--Writes are not permitted. The following gives an error:
BEGIN
DBMS_LOB.WRITEAPPEND(c_lob1,5,'Hello'); --**NEW 8i**
EXCEPTION
WHEN others THEN
DBMS_OUTPUT.PUT_LINE(sqlerrm);
END;
-- Commit and rollback are allowed because no transaction is started.
-- The LOB will still be open afterwards.
ROLLBACK;
-- Close - can use either locator.
IF DBMS_LOB.ISOPEN(c_lob2) = 1 THEN --**NEW 8i**
DBMS_OUTPUT.PUT_LINE('Closing LOB via locator 2');
DBMS_LOB.CLOSE(c_lob2); --**NEW 8i**
END IF;
IF DBMS_LOB.ISOPEN(c_lob1) = 1 THEN --**NEW 8i**
DBMS_OUTPUT.PUT_LINE('Closing LOB via locator 1');
DBMS_LOB.CLOSE(c_lob1); --**NEW 8i**
END IF;
-- To open for read/write the record in the database must be locked.
SELECT c2 INTO c_lob1 FROM test_lobs WHERE c1 = 2 FOR UPDATE;
DBMS_LOB.OPEN(c_lob1,DBMS_LOB.LOB_READWRITE); --**NEW 8i**
DBMS_LOB.WRITEAPPEND(c_lob1,5,'Hello'); --**NEW 8i**
DBMS_LOB.WRITEAPPEND(c_lob1,7,' there.'); --**NEW 8i**
-- The LOB MUST be closed before committing or rolling back.
DBMS_LOB.CLOSE(c_lob1); --**NEW 8i**
COMMIT;
END;
/
Prompt Query CLOB records...
Prompt ---------------------
SELECT c2
FROM test_lobs
WHERE c1 = 2
/

View File

@@ -0,0 +1,17 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : example_move_table.sql |
-- | CLASS : Examples |
-- | PURPOSE : Example SQL syntax used to move a table to an alternative |
-- | tablespace. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
ALTER TABLE emp MOVE TABLESPACE users2 STORAGE (INITIAL 10M NEXT 1M);

View File

@@ -0,0 +1,71 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : example_partition_range_date_oracle_8.sql |
-- | CLASS : Examples |
-- | PURPOSE : Example SQL syntax used to create and maintain range partitions |
-- | in Oracle8. The table in this example is partitioned by a date |
-- | range. In Oracle8, only range partitions are available. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
CONNECT scott/tiger
/*
** +-----------------------------------+
** | DROP ALL OBJECTS |
** +-----------------------------------+
*/
DROP TABLE emp_date_part CASCADE CONSTRAINTS
/
/*
** +-------------------------------------------------+
** | CREATE (Range) PARTITIONED TABLE |
** | ----------------------------------------------- |
** | Create testing table partitioned by a |
** | "range" of DATE values. |
** | |
** | NOTE: The only functions permitted in the |
** | 'VALUES LESS THAN (value1, value2 ..., valueN)' |
** | clause are TO_DATE and RPAD. |
** +-------------------------------------------------+
*/
CREATE TABLE emp_date_part (
empno NUMBER(15) NOT NULL
, ename VARCHAR2(100)
, sal NUMBER(7,2)
, hire_date DATE NOT NULL
)
TABLESPACE users
STORAGE (
INITIAL 128K
NEXT 128K
PCTINCREASE 0
MAXEXTENTS UNLIMITED
)
PARTITION BY RANGE (hire_date) (
PARTITION emp_date_part_Q1_2001_part
VALUES LESS THAN (TO_DATE('01-APR-2001', 'DD-MON-YYYY'))
TABLESPACE part_1_data_tbs,
PARTITION emp_date_part_Q2_2001_part
VALUES LESS THAN (TO_DATE('01-JUL-2001', 'DD-MON-YYYY'))
TABLESPACE part_2_data_tbs,
PARTITION emp_date_part_Q3_2001_part
VALUES LESS THAN (TO_DATE('01-OCT-2001', 'DD-MON-YYYY'))
TABLESPACE part_3_data_tbs,
PARTITION emp_date_part_Q4_2001_part
VALUES LESS THAN (TO_DATE('01-JAN-2002', 'DD-MON-YYYY'))
TABLESPACE part_4_data_tbs
)
/

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,82 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : example_transport_tablespace.sql |
-- | CLASS : Examples |
-- | PURPOSE : Example script that demonstrates how to use the transportable |
-- | tablespace feature. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
connect "/ as sysdba"
set serveroutput on
Prompt =====================================================
Prompt THE FOLLOWING EXAMPLE WILL TRANSPORT THE TABLESPACES
Prompt "users" and "users2" FROM DATABASE "CUSTDB" TO "DWDB"
Prompt =====================================================
Prompt
Prompt
Prompt ==========================================
Prompt VERIFY TABLESPACE(s) ARE SELF-CONTAINED...
Prompt ==========================================
Prompt
accept a1 Prompt "Hit <ENTER> to continue";
exec DBMS_TTS.TRANSPORT_SET_CHECK('users, users2', TRUE);
SELECT * FROM TRANSPORT_SET_VIOLATIONS;
Prompt ==========================================
Prompt GENERATE A TRANSPORTABLE TABLESPACE SET...
Prompt ==========================================
Prompt
accept a1 Prompt "Hit <ENTER> to continue";
ALTER TABLESPACE users READ ONLY;
ALTER TABLESPACE users2 READ ONLY;
!exp userid=\"sys/change_on_install@custdb_jeffreyh3\" transport_tablespace=y tablespaces=users,users2 triggers=y constraints=y grants=y file=users.dmp
!cp /u10/app/oradata/CUSTDB/users01.dbf /u10/app/oradata/DWDB/users01.dbf
!cp /u10/app/oradata/CUSTDB/users2_02.dbf /u10/app/oradata/DWDB/users2_02.dbf
ALTER TABLESPACE users READ WRITE;
ALTER TABLESPACE users2 READ WRITE;
Prompt ===============================
Prompt LOGGING INTO TARGET DATABASE...
Prompt ===============================
Prompt
accept a1 Prompt "Hit <ENTER> to continue";
connect sys/change_on_install@dwdb_jeffreyh3 as sysdba
Prompt ============================
Prompt IMPORT THE TABLESPACE SET...
Prompt ============================
Prompt
accept a1 Prompt "Hit <ENTER> to continue";
!imp userid=\"sys/change_on_install@dwdb_jeffreyh3 as sysdba\" transport_tablespace=y datafiles='/u10/app/oradata/DWDB/users01.dbf, /u10/app/oradata/DWDB/users2_02.dbf' file=users.dmp
Prompt =================================================
Prompt FINAL CLEANUP. ALTER TABLESPACES TO READ/WRITE...
Prompt =================================================
Prompt
accept a1 Prompt "Hit <ENTER> to continue";
ALTER TABLESPACE users READ WRITE;
ALTER TABLESPACE users2 READ WRITE;

68
idev/fdb_log_files.sql Normal file
View File

@@ -0,0 +1,68 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : fdb_log_files.sql |
-- | CLASS : Flashback Database |
-- | PURPOSE : Provide a list of all Flasback log files. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET TERMOUT OFF;
COLUMN current_instance NEW_VALUE current_instance NOPRINT;
SELECT rpad(sys_context('USERENV', 'INSTANCE_NAME'), 17) current_instance
FROM dual;
SET TERMOUT ON;
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Report : Flashback Database Log Files |
PROMPT | Instance : &current_instance |
PROMPT +------------------------------------------------------------------------+
SET ECHO OFF
SET FEEDBACK 6
SET HEADING ON
SET LINESIZE 180
SET PAGESIZE 50000
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
COLUMN thread# HEADING 'Thread #'
COLUMN sequence# HEADING 'Sequence #'
COLUMN name FORMAT a65 HEADING 'Log File Name'
COLUMN log# HEADING 'Log #'
COLUMN bytes FORMAT 999,999,999,999 HEADING 'Bytes'
COLUMN first_change# HEADING 'First Change #'
COLUMN first_time HEADING 'First Time' JUST RIGHT
BREAK ON thread# SKIP 2
COMPUTE count OF sequence# ON thread#
COMPUTE sum OF bytes ON thread#
SELECT
thread#
, sequence#
, name
, log#
, bytes
, first_change#
, TO_CHAR(first_time, 'DD-MON-YYYY HH24:MI:SS') first_time
FROM
v$flashback_database_logfile
ORDER BY
thread#
, sequence#;

View File

@@ -0,0 +1,62 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : fdb_redo_time_matrix.sql |
-- | CLASS : Flashback Database |
-- | PURPOSE : Provide details on the amount of redo data being collected by |
-- | Oracle Flashback Database over given time frames. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET TERMOUT OFF;
COLUMN current_instance NEW_VALUE current_instance NOPRINT;
SELECT rpad(sys_context('USERENV', 'INSTANCE_NAME'), 17) current_instance
FROM dual;
SET TERMOUT ON;
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Report : Flashback Database Redo Time Matrix |
PROMPT | Instance : &current_instance |
PROMPT +------------------------------------------------------------------------+
SET ECHO OFF
SET FEEDBACK 6
SET HEADING ON
SET LINESIZE 180
SET PAGESIZE 50000
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
COLUMN begin_time FORMAT a21 HEADING 'Begin Time'
COLUMN end_time FORMAT a21 HEADING 'End Time'
COLUMN flashback_data FORMAT 9,999,999,999,999 HEADING 'Flashback Data'
COLUMN db_data FORMAT 9,999,999,999,999 HEADING 'DB Data'
COLUMN redo_data FORMAT 9,999,999,999,999 HEADING 'Redo Data'
COLUMN estimated_flashback_size FORMAT 9,999,999,999,999 HEADING 'Estimated|Flashback Size'
SELECT
TO_CHAR(begin_time, 'DD-MON-YYYY HH24:MI:SS') begin_time
, TO_CHAR(end_time, 'DD-MON-YYYY HH24:MI:SS') end_time
, flashback_data
, db_data
, redo_data
, estimated_flashback_size
FROM
v$flashback_database_stat
ORDER BY
begin_time;

70
idev/fdb_status.sql Normal file
View File

@@ -0,0 +1,70 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : fdb_status.sql |
-- | CLASS : Flashback Database |
-- | PURPOSE : Provide an overview of the current state of the Flashback |
-- | database feature. First check that Flashback Database is |
-- | enabled. Next, provide an overview of the retention policy |
-- | settings and estimated size of the Flashback Logs. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET TERMOUT OFF;
COLUMN current_instance NEW_VALUE current_instance NOPRINT;
SELECT rpad(sys_context('USERENV', 'INSTANCE_NAME'), 17) current_instance
FROM dual;
SET TERMOUT ON;
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Report : Flashback Database Status |
PROMPT | Instance : &current_instance |
PROMPT +------------------------------------------------------------------------+
SET ECHO OFF
SET FEEDBACK 6
SET HEADING ON
SET LINESIZE 180
SET PAGESIZE 50000
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
COLUMN dbid HEADING 'DB ID'
COLUMN name FORMAT a15 HEADING 'DB Name'
COLUMN log_mode FORMAT a18 HEADING 'Log Mode'
COLUMN flashback_on FORMAT a18 HEADING 'Flashback DB On?'
SELECT
dbid
, name
, log_mode
, flashback_on
FROM v$database;
COLUMN oldest_flashback_scn HEADING 'Oldest|Flashback SCN'
COLUMN oldest_flashback_time FORMAT a21 HEADING 'Oldest|Flashback Time' JUST right
COLUMN retention_target FORMAT 999,999 HEADING 'Retention|Target (min)'
COLUMN flashback_size FORMAT 9,999,999,999,999 HEADING 'Flashback|Size'
COLUMN estimated_flashback_size FORMAT 9,999,999,999,999 HEADING 'Estimated|Flashback Size'
SELECT
oldest_flashback_scn
, TO_CHAR(oldest_flashback_time, 'DD-MON-YYYY HH24:MI:SS') oldest_flashback_time
, retention_target
, flashback_size
, estimated_flashback_size
FROM v$flashback_database_log;

80
idev/fra_alerts.sql Normal file
View File

@@ -0,0 +1,80 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : fra_alerts.sql |
-- | CLASS : Flash Recovery Area |
-- | PURPOSE : Provide a list of alerts regarding the Oracle Flash Recovery |
-- | Area. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET TERMOUT OFF;
COLUMN current_instance NEW_VALUE current_instance NOPRINT;
SELECT rpad(sys_context('USERENV', 'INSTANCE_NAME'), 17) current_instance
FROM dual;
SET TERMOUT ON;
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Report : FRA Alerts |
PROMPT | Instance : &current_instance |
PROMPT +------------------------------------------------------------------------+
SET ECHO OFF
SET FEEDBACK 6
SET HEADING ON
SET LINESIZE 180
SET PAGESIZE 50000
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
COLUMN object_type FORMAT a12 HEADING 'Object Type'
COLUMN message_type FORMAT a13 HEADING 'Message Type'
COLUMN message_level HEADING 'Message Level'
COLUMN reason FORMAT a50 HEADING 'Reason' WRAP
COLUMN suggested_action FORMAT a50 HEADING 'Suggested Action' WRAP
prompt
prompt The database issues a warning alert when reclaimable space is less than
prompt 15% and a critical alert when relaimable space is less than 3%. To warn
prompt the DBA of this condition, an entry is added to the alert.log and to the
prompt DBA_OUTSTANDING_ALERTS table (used by Enterprise Manager). However, the
prompt database continues to consume space in the Flash Recovery Area until
prompt there is no reclaimable space left. When the Flash Recovery Area is
prompt completely full, the following error will be reported:
prompt
prompt ORA-19809: limit exceeded for recovery files
prompt ORA-19804: cannot reclaim nnnnn bytes disk space from mmmmm limit
prompt
prompt where nnnnn is the number of bytes required and mmmmm is the disk quota
prompt for the Flash Recovery Area.
prompt
prompt The following Error would be reported in the alert.log
prompt ORA-19815: WARNING: db_recovery_file_dest_size of "size of FRA configured"
prompt bytes is 100.00% used, and has 0 remaining bytes available.
prompt
SELECT
object_type
, message_type
, message_level
, reason
, suggested_action
FROM
dba_outstanding_alerts
/

70
idev/fra_files.sql Normal file
View File

@@ -0,0 +1,70 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : fra_files.sql |
-- | CLASS : Flash Recovery Area |
-- | PURPOSE : Provide a list of all files in the Flash Recovery Area. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET TERMOUT OFF;
COLUMN current_instance NEW_VALUE current_instance NOPRINT;
SELECT rpad(sys_context('USERENV', 'INSTANCE_NAME'), 17) current_instance
FROM dual;
SET TERMOUT ON;
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Report : FRA Files |
PROMPT | Instance : &current_instance |
PROMPT +------------------------------------------------------------------------+
SET ECHO OFF
SET FEEDBACK 6
SET HEADING ON
SET LINESIZE 180
SET PAGESIZE 50000
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
COLUMN name FORMAT a80 HEADING 'File Name'
COLUMN member FORMAT a80 HEADING 'File Name'
COLUMN handle FORMAT a80 HEADING 'File Name'
COLUMN bytes FORMAT 999,999,999,999,999 HEADING 'File Size (Bytes)'
SELECT name, (blocks*block_size) bytes
FROM v$datafile_copy
WHERE is_recovery_dest_file = 'YES'
UNION
SELECT name, null
FROM v$controlfile
WHERE is_recovery_dest_file = 'YES'
UNION
SELECT member, null
FROM v$logfile
WHERE is_recovery_dest_file = 'YES'
UNION
SELECT handle, bytes
FROM v$backup_piece
WHERE is_recovery_dest_file = 'YES'
UNION
SELECT name, (blocks*block_size) bytes
FROM v$archived_log
WHERE is_recovery_dest_file = 'YES'
ORDER BY
1
, 2
/

82
idev/fra_status.sql Normal file
View File

@@ -0,0 +1,82 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : fra_status.sql |
-- | CLASS : Fast Recovery Area |
-- | PURPOSE : Provide an overview of the Oracle Flash Recovery Area. This |
-- | script is RAC enabled. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET TERMOUT OFF;
COLUMN current_instance NEW_VALUE current_instance NOPRINT;
SELECT rpad(sys_context('USERENV', 'INSTANCE_NAME'), 17) current_instance
FROM dual;
SET TERMOUT ON;
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Report : FRA Status |
PROMPT | Instance : &current_instance |
PROMPT | Notes : Current location, disk quota, space in use, space |
PROMPT | reclaimable by deleting files, and number of files in the |
PROMPT | Flash Recovery Area. |
PROMPT +------------------------------------------------------------------------+
SET ECHO OFF
SET FEEDBACK 6
SET HEADING ON
SET LINESIZE 180
SET PAGESIZE 50000
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
COLUMN recovery_file_dest FORMAT a30 HEADING 'Recovery File Dest'
COLUMN space_limit FORMAT 99,999,999,999,999 HEADING 'Space Limit'
COLUMN space_used FORMAT 99,999,999,999,999 HEADING 'Space Used'
COLUMN space_used_pct FORMAT 999.99 HEADING '% Used'
COLUMN space_reclaimable FORMAT 99,999,999,999,999 HEADING 'Space Reclaimable'
COLUMN pct_reclaimable FORMAT 999.99 HEADING '% Reclaimable'
COLUMN number_of_files FORMAT 999,999 HEADING 'Number of Files'
SELECT
f.name recovery_file_dest
, f.space_limit space_limit
, f.space_used space_used
, ROUND((f.space_used / f.space_limit)*100, 2) space_used_pct
, f.space_reclaimable space_reclaimable
, ROUND((f.space_reclaimable / f.space_limit)*100, 2) pct_reclaimable
, f.number_of_files number_of_files
FROM
v$recovery_file_dest f
ORDER BY
f.name;
COLUMN file_type FORMAT a30 HEADING 'File Type'
COLUMN percent_space_used HEADING 'Percent Space Used'
COLUMN percent_space_reclaimable HEADING 'Percent Space Reclaimable'
COLUMN number_of_files FORMAT 999,999 HEADING 'Number of Files'
SELECT
f.file_type
, f.percent_space_used
, f.percent_space_reclaimable
, f.number_of_files
FROM
v$flash_recovery_area_usage f
ORDER BY
f.file_type;

368
idev/help.sql Normal file
View File

@@ -0,0 +1,368 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : help.sql |
-- | CLASS : Database Administration |
-- | PURPOSE : A utility script used to print out the names of all Oracle SQL |
-- | scripts that can be executed from SQL*Plus. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET LINESIZE 145
SET PAGESIZE 9999
SET VERIFY off
prompt
prompt ========================================
prompt Automatic Shared Memory Management
prompt ========================================
prompt asmm_components.sql
prompt
prompt ========================================
prompt Automatic Storage Management
prompt ========================================
prompt asm_alias.sql
prompt asm_clients.sql
prompt asm_diskgroups.sql
prompt asm_disks.sql
prompt asm_disks_perf.sql
prompt asm_drop_files.sql
prompt asm_files.sql
prompt asm_files2.sql
prompt asm_files_10g.sql
prompt asm_templates.sql
prompt
prompt ========================================
prompt Automatic Workload Repository
prompt ========================================
prompt awr_snapshots_dbtime.sql
prompt awr_snapshots_dbtime_xls.sql
prompt
prompt ========================================
prompt Database Administration
prompt ========================================
prompt dba_blocks_used_by_table.sql
prompt dba_column_constraints.sql
prompt dba_compare_schemas.sql
prompt dba_controlfile_records.sql
prompt dba_controlfiles.sql
prompt dba_cr_init.sql
prompt dba_db_growth.sql
prompt dba_directories.sql
prompt dba_errors.sql
prompt dba_file_space_usage.sql
prompt dba_file_space_usage_7.sql
prompt dba_file_use.sql
prompt dba_file_use_7.sql
prompt dba_files.sql
prompt dba_files_all.sql
prompt dba_free_space_frag.sql
prompt dba_highwater_mark.sql
prompt dba_index_fragmentation.sql
prompt dba_index_schema_fragmentation_report.sql
prompt dba_index_stats.sql
prompt dba_invalid_objects.sql
prompt dba_invalid_objects_summary.sql
prompt dba_jobs.sql
prompt dba_object_cache.sql
prompt dba_object_search.sql
prompt dba_object_summary.sql
prompt dba_options.sql
prompt dba_owner_to_tablespace.sql
prompt dba_plsql_package_size.sql
prompt dba_query_hidden_parameters.sql
prompt dba_random_number.sql
prompt dba_rebuild_indexes.sql
prompt dba_recompile_invalid_objects.sql
prompt dba_registry.sql
prompt dba_related_child_tables.sql
prompt dba_row_size.sql
prompt dba_segment_summary.sql
prompt dba_snapshot_database_10g.sql
prompt dba_snapshot_database_8i.sql
prompt dba_snapshot_database_9i.sql
prompt dba_table_info.sql
prompt dba_tables_all.sql
prompt dba_tables_current_user.sql
prompt dba_tables_query_user.sql
prompt dba_tablespace_mapper.sql
prompt dba_tablespace_to_owner.sql
prompt dba_tablespaces.sql
prompt dba_tablespaces_7.sql
prompt dba_tablespaces_8i.sql
prompt dba_top_segments.sql
prompt help.sql
prompt
prompt ========================================
prompt Database Resource Manager
prompt ========================================
prompt rsrc_plan_status_detail.sql
prompt rsrc_plan_status_summary.sql
prompt
prompt ========================================
prompt Examples
prompt ========================================
prompt example_create_clob.sql
prompt example_create_clob_8.sql
prompt example_create_dimension.sql
prompt example_create_emp_dept_custom.sql
prompt example_create_emp_dept_original.sql
prompt example_create_index.sql
prompt example_create_index_organized_table.sql
prompt example_create_materialized_view.sql
prompt example_create_not_null_constraints.sql
prompt example_create_primary_foreign_key.sql
prompt example_create_profile_password_parameters.sql
prompt example_create_profile_resource_parameters.sql
prompt example_create_resource_plan_multi_resource_plan_9i.sql
prompt example_create_sequence.sql
prompt example_create_table.sql
prompt example_create_table_buffer_pools.sql
prompt example_create_tablespace.sql
prompt example_create_temporary_tables.sql
prompt example_create_user_tables.sql
prompt example_database_resource_manager_setup.sql
prompt example_drop_unused_column.sql
prompt example_lob_demonstration.sql
prompt example_move_table.sql
prompt example_partition_range_date_oracle_8.sql
prompt example_partition_range_number_oracle_8.sql
prompt example_transport_tablespace.sql
prompt
prompt ========================================
prompt Flash Recovery Area
prompt ========================================
prompt fra_alerts.sql
prompt fra_files.sql
prompt fra_status.sql
prompt
prompt ========================================
prompt Flashback Database
prompt ========================================
prompt fdb_log_files.sql
prompt fdb_redo_time_matrix.sql
prompt fdb_status.sql
prompt
prompt ========================================
prompt LOBs
prompt ========================================
prompt lob_dump_blob.sql
prompt lob_dump_clob.sql
prompt lob_dump_nclob.sql
prompt lob_fragmentation_user.sql
prompt
prompt ========================================
prompt Locks
prompt ========================================
prompt locks_blocking.sql
prompt locks_blocking2.sql
prompt locks_dml_ddl.sql
prompt locks_dml_lock_time.sql
prompt
prompt ========================================
prompt Multi Threaded Server
prompt ========================================
prompt mts_dispatcher_status.sql
prompt mts_dispatcher_utilization.sql
prompt mts_queue_information.sql
prompt mts_shared_server_statistics.sql
prompt mts_shared_server_utilization.sql
prompt mts_user_connections.sql
prompt
prompt ========================================
prompt Oracle Applications
prompt ========================================
prompt erp_conc_manager_job_status.sql
prompt erp_conc_manager_job_status2.sql
prompt erp_conc_manager_user_query.sql
prompt
prompt ========================================
prompt Oracle Wait Interface
prompt ========================================
prompt owi_event_names.sql
prompt
prompt ========================================
prompt PL SQL
prompt ========================================
prompt plsql_random_numbers.sql
prompt plsql_webdba_utl_pkg.sql
prompt
prompt ========================================
prompt RMAN
prompt ========================================
prompt rman_backup_pieces.sql
prompt rman_backup_sets.sql
prompt rman_backup_sets_8i.sql
prompt rman_configuration.sql
prompt rman_controlfiles.sql
prompt rman_progress.sql
prompt rman_spfiles.sql
prompt
prompt ========================================
prompt RMAN Recovery Catalog
prompt ========================================
prompt rc_databases.sql
prompt
prompt ========================================
prompt Real Application Clusters
prompt ========================================
prompt rac_instances.sql
prompt
prompt ========================================
prompt Security
prompt ========================================
prompt sec_default_passwords.sql
prompt sec_roles.sql
prompt sec_users.sql
prompt
prompt ========================================
prompt Session Management
prompt ========================================
prompt sess_current_user_transactions.sql
prompt sess_query_sql.sql
prompt sess_uncommited_transactions.sql
prompt sess_user_sessions.sql
prompt sess_user_stats.sql
prompt sess_user_trace_file_location.sql
prompt sess_users.sql
prompt sess_users_8i.sql
prompt sess_users_active.sql
prompt sess_users_active_8i.sql
prompt sess_users_active_sql.sql
prompt sess_users_by_cpu.sql
prompt sess_users_by_cursors.sql
prompt sess_users_by_io.sql
prompt sess_users_by_memory.sql
prompt sess_users_by_transactions.sql
prompt sess_waiting.sql
prompt sess_waiting_8i.sql
prompt
prompt ========================================
prompt Statspack
prompt ========================================
prompt sp_auto.sql
prompt sp_auto_15.sql
prompt sp_auto_30.sql
prompt sp_auto_5.sql
prompt sp_list.sql
prompt sp_parameters.sql
prompt sp_purge.sql
prompt sp_purge_30_days_10g.sql
prompt sp_purge_30_days_9i.sql
prompt sp_purge_n_days_10g.sql
prompt sp_purge_n_days_9i.sql
prompt sp_snap.sql
prompt sp_statspack_custom_pkg_10g.sql
prompt sp_statspack_custom_pkg_9i.sql
prompt sp_trunc.sql
prompt
prompt ========================================
prompt Temporary Tablespace
prompt ========================================
prompt temp_sort_segment.sql
prompt temp_sort_users.sql
prompt temp_status.sql
prompt
prompt ========================================
prompt Tuning
prompt ========================================
prompt perf_db_block_buffer_usage.sql
prompt perf_explain_plan.sql
prompt perf_file_io.sql
prompt perf_file_io_7.sql
prompt perf_file_io_efficiency.sql
prompt perf_file_waits.sql
prompt perf_hit_ratio_by_session.sql
prompt perf_hit_ratio_system.sql
prompt perf_log_switch_history_bytes_daily_all.sql
prompt perf_log_switch_history_count_daily.sql
prompt perf_log_switch_history_count_daily_7.sql
prompt perf_log_switch_history_count_daily_all.sql
prompt perf_lru_latch_contention.sql
prompt perf_objects_without_statistics.sql
prompt perf_performance_snapshot.sql
prompt perf_redo_log_contention.sql
prompt perf_sga_free_pool.sql
prompt perf_sga_usage.sql
prompt perf_shared_pool_memory.sql
prompt perf_top_10_procedures.sql
prompt perf_top_10_tables.sql
prompt perf_top_sql_by_buffer_gets.sql
prompt perf_top_sql_by_disk_reads.sql
prompt
prompt ========================================
prompt Undo Segments
prompt ========================================
prompt rollback_segments.sql
prompt rollback_users.sql
prompt undo_contention.sql
prompt undo_segments.sql
prompt undo_users.sql
prompt
prompt ========================================
prompt Workspace Manager
prompt ========================================
prompt wm_create_workspace.sql
prompt wm_disable_versioning.sql
prompt wm_enable_versioning.sql
prompt wm_freeze_workspace.sql
prompt wm_get_workspace.sql
prompt wm_goto_workspace.sql
prompt wm_merge_workspace.sql
prompt wm_refresh_workspace.sql
prompt wm_remove_workspace.sql
prompt wm_rollback_workspace.sql
prompt wm_unfreeze_workspace.sql
prompt wm_workspaces.sql

222
idev/lob_dump_blob.sql Normal file
View File

@@ -0,0 +1,222 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : lob_dump_blob.sql |
-- | CLASS : LOBs |
-- | PURPOSE : This script can be used to dump the contents of a BLOB column. |
-- | The user will be prompted for the OWNER, TABLE_NAME, and |
-- | COLUMN_NAME for the BLOB column to read from. The anonymous |
-- | PL/SQL block will write the contents of the BLOB to a file |
-- | named using the format: OWNER_TABLE_COLUMN_<counter>.out |
-- | An example would be: SCOTT_XML_DOCS_LOG_1.out |
-- | SCOTT_XML_DOCS_LOG_2.out |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET TERMOUT OFF;
COLUMN current_instance NEW_VALUE current_instance NOPRINT;
COLUMN current_user NEW_VALUE current_user NOPRINT;
SELECT rpad(instance_name, 17) current_instance, rpad(user, 13) current_user FROM v$instance;
SET TERMOUT ON;
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Report : Dump the Contents of a BLOB Column |
PROMPT | Instance : &current_instance |
PROMPT | User : &current_user |
PROMPT +------------------------------------------------------------------------+
PROMPT
SET ECHO OFF
SET FEEDBACK 6
SET HEADING ON
SET LINESIZE 180
SET PAGESIZE 50000
SET TERMOUT ON
SET SERVEROUTPUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
ACCEPT oname PROMPT 'Enter Owner Name : '
ACCEPT tname PROMPT 'Enter Table Name : '
ACCEPT cname PROMPT 'Enter Column Name : '
ACCEPT wclause PROMPT 'SQL WHERE clause (including WHERE clause) : '
ACCEPT odir PROMPT 'Enter Output Directory : '
CREATE OR REPLACE DIRECTORY temp_dump_lob_dir AS '&odir';
DECLARE
-- +----------------------------------------------------+
-- | INCOMING VARIABLES |
-- +----------------------------------------------------+
v_oname VARCHAR2(100) := UPPER('&oname');
v_tname VARCHAR2(100) := UPPER('&tname');
v_cname VARCHAR2(100) := UPPER('&cname');
v_outdir VARCHAR2(30) := 'TEMP_DUMP_LOB_DIR';
v_wclause VARCHAR2(4000) := '&wclause';
-- +----------------------------------------------------+
-- | OUTPUT FILE VARIABLES |
-- +----------------------------------------------------+
v_out_filename VARCHAR2(500) := v_oname || '_' || v_tname || '_' || v_cname;
v_out_fileext VARCHAR2(4) := '.out';
v_out_filename_full VARCHAR2(500);
v_out_dirname VARCHAR2(2000);
v_file_count NUMBER := 0;
v_file_handle UTL_FILE.FILE_TYPE;
-- +----------------------------------------------------+
-- | DYNAMIC SQL VARIABLES |
-- +----------------------------------------------------+
TYPE v_lob_cur_typ IS REF CURSOR;
v_lob_cur v_lob_cur_typ;
v_sql_string VARCHAR2(4000);
-- +----------------------------------------------------+
-- | BLOB WRITE VARIABLES |
-- +----------------------------------------------------+
v_blob_loc BLOB;
v_buffer RAW(32767);
v_buffer_size CONSTANT BINARY_INTEGER := 32767;
v_amount BINARY_INTEGER;
v_offset NUMBER(38);
-- +----------------------------------------------------+
-- | EXCEPTIONS |
-- +----------------------------------------------------+
invalid_directory_path EXCEPTION;
PRAGMA EXCEPTION_INIT(invalid_directory_path, -29280);
table_does_not_exist EXCEPTION;
PRAGMA EXCEPTION_INIT(table_does_not_exist, -00942);
invalid_identifier EXCEPTION;
PRAGMA EXCEPTION_INIT(invalid_identifier, -00904);
SQL_cmd_not_prop_ended EXCEPTION;
PRAGMA EXCEPTION_INIT(SQL_cmd_not_prop_ended, -00933);
BEGIN
-- +----------------------------------------------------+
-- | ENABLE SERVER-SIDE OUTPUT |
-- +----------------------------------------------------+
DBMS_OUTPUT.ENABLE(1000000);
SELECT directory_path INTO v_out_dirname FROM all_directories WHERE directory_name = 'TEMP_DUMP_LOB_DIR';
v_sql_string := 'SELECT ' || v_cname || ' FROM ' || v_oname || '.' || v_tname || ' ' || v_wclause;
OPEN v_lob_cur FOR
v_sql_string;
LOOP
FETCH v_lob_cur INTO v_blob_loc;
EXIT WHEN v_lob_cur%NOTFOUND;
v_file_count := v_file_count + 1;
v_out_filename_full := v_out_filename || '_' || v_file_count || v_out_fileext;
v_file_handle := UTL_FILE.FOPEN(v_outdir, v_out_filename_full, 'w', 32767);
v_amount := v_buffer_size;
v_offset := 1;
DECLARE
invalid_LOB_locator EXCEPTION;
PRAGMA EXCEPTION_INIT(invalid_LOB_locator, -06502);
BEGIN
WHILE v_amount >= v_buffer_size
LOOP
DBMS_LOB.READ(
lob_loc => v_blob_loc,
amount => v_amount,
offset => v_offset,
buffer => v_buffer);
v_offset := v_offset + v_amount;
UTL_FILE.PUT_RAW(
file => v_file_handle,
buffer => v_buffer,
autoflush => true);
UTL_FILE.FFLUSH(file => v_file_handle);
END LOOP;
EXCEPTION
WHEN invalid_LOB_locator THEN
UTL_FILE.PUT_LINE(file => v_file_handle, buffer => '+----------------------------+');
UTL_FILE.PUT_LINE(file => v_file_handle, buffer => '| *** ERROR *** |');
UTL_FILE.PUT_LINE(file => v_file_handle, buffer => '+----------------------------+');
UTL_FILE.NEW_LINE(file => v_file_handle);
UTL_FILE.PUT_LINE(file => v_file_handle, buffer => 'Invalid LOB Locator Exception for :');
UTL_FILE.PUT_LINE(file => v_file_handle, buffer => '===================================');
UTL_FILE.PUT_LINE(file => v_file_handle, buffer => ' --> ' || v_oname || '.' || v_tname || '.' || v_cname);
UTL_FILE.NEW_LINE(file => v_file_handle);
UTL_FILE.PUT_LINE(file => v_file_handle, buffer => 'SQL Text:');
UTL_FILE.PUT_LINE(file => v_file_handle, buffer => '===================================');
UTL_FILE.PUT_LINE(file => v_file_handle, buffer => ' --> ' || v_sql_string);
UTL_FILE.FFLUSH(file => v_file_handle);
WHEN others THEN
UTL_FILE.PUT_LINE(file => v_file_handle, buffer => '+----------------------------+');
UTL_FILE.PUT_LINE(file => v_file_handle, buffer => '| *** ERROR *** |');
UTL_FILE.PUT_LINE(file => v_file_handle, buffer => '+----------------------------+');
UTL_FILE.NEW_LINE(file => v_file_handle);
UTL_FILE.PUT_LINE(file => v_file_handle, buffer => 'WHEN OTHERS ERROR');
UTL_FILE.PUT_LINE(file => v_file_handle, buffer => '=================');
UTL_FILE.PUT_LINE(file => v_file_handle, buffer => ' --> SQL CODE : ' || SQLCODE);
UTL_FILE.PUT_LINE(file => v_file_handle, buffer => ' --> SQL ERROR MESSAGE : ' || SQLERRM);
UTL_FILE.FFLUSH(file => v_file_handle);
END;
UTL_FILE.FCLOSE(v_file_handle);
END LOOP;
CLOSE v_lob_cur;
DBMS_OUTPUT.PUT_LINE('Wrote out ' || v_file_count || ' file(s) to ' || v_out_dirname || '.');
EXCEPTION
WHEN invalid_directory_path THEN
DBMS_OUTPUT.PUT_LINE('** ERROR ** : Invalid Directory Path: ' || v_outdir);
WHEN table_does_not_exist THEN
DBMS_OUTPUT.PUT_LINE('** ERROR ** : Table Not Found.');
DBMS_OUTPUT.PUT_LINE('--> SQL: ' || v_sql_string);
WHEN invalid_identifier THEN
DBMS_OUTPUT.PUT_LINE('** ERROR ** : Invalid Identifier.');
DBMS_OUTPUT.PUT_LINE('--> SQL: ' || v_sql_string);
WHEN SQL_cmd_not_prop_ended THEN
DBMS_OUTPUT.PUT_LINE('** ERROR ** : SQL command not properly ended.');
DBMS_OUTPUT.PUT_LINE('--> SQL: ' || v_sql_string);
END;
/
DROP DIRECTORY temp_dump_lob_dir;

Some files were not shown because too many files have changed in this diff Show More