Moving a table from one tablespace to another

Moving a table from one tablespace to another


There are couple of ways in which a table can be moved to a different tablespace:
   a) One of them is to perform export/import 
   b) Another is to use ‘ALTER TABLE’ command with ‘MOVE tablespace’ clause

If you move a table from one tablespace to another, you need to REBUILD the Related indexes if those indexes are on same tablespace

      1)  Check indexes for a table

SQL> SELECT INDEX_NAME, TABLE_NAME,STATUS FROM ALL_INDEXES WHERE TABLE_NAME = ‘ tab_name’;

Index_name       table_name           status
-----------------       ------------------       ----------
Ind_name            tab_name            valid
A
2)     Check the tablespace in which our table is located

SQL> select tablespace_name,table_name from user_tables where table_name=’TAB_NAME’;


3)    Now moving to another tablesapce

SQL>  ALTER TABLE tab_name MOVE TABLESPACE new_tablespace;


4)    Now check the status of the index again

SQL> SELECT INDEX_NAME, TABLE_NAME,STATUS FROM ALL_INDEXES WHERE TABLE_NAME = ‘ tab_name’;

Index_name       table_name           status
-----------------       ------------------       ----------
Users                 tab_name             Unusable
                                                                              

5)    Rebuild the index in order to make the index valid

SQL>  ALTER INDEX ind_name REBUILD;
 index altered


6)    Check the status of the index again

SQL> SELECT INDEX_NAME, TABLE_NAME,STATUS FROM ALL_INDEXES WHERE TABLE_NAME = ‘ tab_name’;

Index_name       table_name           status
-----------------       ------------------       ----------
ind_name               tab_name           valid

Converting DOS Batch Files to Shell Scripts

 Converting DOS Batch Files to Shell Scripts

Quite a number of programmers learned scripting on a PC running DOS. Even the crippled DOS batch file language allowed writing some fairly powerful scripts and applications, though they often required extensive kludges and workarounds. Occasionally, the need still arises to convert an old DOS batch file to a UNIX shell script. This is generally not difficult, as DOS batch file operators are only a limited subset of the equivalent shell scripting ones.
Table N-1. Batch file keywords / variables / operators, and their shell equivalents
Batch File OperatorShell Script EquivalentMeaning
%$command-line parameter prefix
/-command option flag
\/directory path separator
===(equal-to) string comparison test
!==!!=(not equal-to) string comparison test
||pipe
@set +vdo not echo current command
**filename "wild card"
>>file redirection (overwrite)
>>>>file redirection (append)
<<redirect stdin
%VAR%$VARenvironmental variable
REM#comment
NOT!negate following test
NUL/dev/null"black hole" for burying command output
ECHOechoecho (many more option in Bash)
ECHO.echoecho blank line
ECHO OFFset +vdo not echo command(s) following
FOR %%VAR IN (LIST) DOfor var in [list]; do"for" loop
:LABELnone (unnecessary)label
GOTOnone (use a function)jump to another location in the script
PAUSEsleeppause or wait an interval
CHOICEcase or selectmenu choice
IFifif-test
IF EXIST FILENAMEif [ -e filename ]test if file exists
IF !%N==!if [ -z "$N" ]if replaceable parameter "N" not present
CALLsource or . (dot operator)"include" another script
COMMAND /Csource or . (dot operator)"include" another script (same as CALL)
SETexportset an environmental variable
SHIFTshiftleft shift command-line argument list
SGN-lt or -gtsign (of integer)
ERRORLEVEL$?exit status
CONstdin"console" (stdin)
PRN/dev/lp0(generic) printer device
LPT1/dev/lp0first printer device
COM1/dev/ttyS0first serial port
Batch files usually contain DOS commands. These must be translated into their UNIX equivalents in order to convert a batch file into a shell script.
Table N-2. DOS commands and their UNIX equivalents
DOS CommandUNIX EquivalentEffect
ASSIGNlnlink file or directory
ATTRIBchmodchange file permissions
CDcdchange directory
CHDIRcdchange directory
CLSclearclear screen
COMPdiff, comm, cmpfile compare
COPYcpfile copy
Ctl-CCtl-Cbreak (signal)
Ctl-ZCtl-DEOF (end-of-file)
DELrmdelete file(s)
DELTREErm -rfdelete directory recursively
DIRls -ldirectory listing
ERASErmdelete file(s)
EXITexitexit current process
FCcomm, cmpfile compare
FINDgrepfind strings in files
MDmkdirmake directory
MKDIRmkdirmake directory
MOREmoretext file paging filter
MOVEmvmove
PATH$PATHpath to executables
RENmvrename (move)
RENAMEmvrename (move)
RDrmdirremove directory
RMDIRrmdirremove directory
SORTsortsort file
TIMEdatedisplay system time
TYPEcatoutput file to stdout
XCOPYcp(extended) file copy

NoteVirtually all UNIX and shell operators and commands have many more options and enhancements than their DOS and batch file counterparts. Many DOS batch files rely on auxiliary utilities, such as ask.com, a crippled counterpart to read.
DOS supports only a very limited and incompatible subset of filename wild-card expansion, recognizing just the * and ? characters.
Converting a DOS batch file into a shell script is generally straightforward, and the result ofttimes reads better than the original.
Example N-1. VIEWDATA.BAT: DOS Batch File

REM VIEWDATA

REM INSPIRED BY AN EXAMPLE IN "DOS POWERTOOLS"
REM                           BY PAUL SOMERSON


@ECHO OFF

IF !%1==! GOTO VIEWDATA
REM  IF NO COMMAND-LINE ARG...
FIND "%1" C:\BOZO\BOOKLIST.TXT
GOTO EXIT0
REM  PRINT LINE WITH STRING MATCH, THEN EXIT.

:VIEWDATA
TYPE C:\BOZO\BOOKLIST.TXT | MORE
REM  SHOW ENTIRE FILE, 1 PAGE AT A TIME.

:EXIT0
The script conversion is somewhat of an improvement. [1]
Example N-2. viewdata.sh: Shell Script Conversion of VIEWDATA.BAT

#!/bin/bash
# viewdata.sh
# Conversion of VIEWDATA.BAT to shell script.

DATAFILE=/home/bozo/datafiles/book-collection.data
ARGNO=1

# @ECHO OFF                 Command unnecessary here.

if [ $# -lt "$ARGNO" ]    # IF !%1==! GOTO VIEWDATA
then
  less $DATAFILE          # TYPE C:\MYDIR\BOOKLIST.TXT | MORE
else
  grep "$1" $DATAFILE     # FIND "%1" C:\MYDIR\BOOKLIST.TXT
fi  

exit 0                    # :EXIT0

#  GOTOs, labels, smoke-and-mirrors, and flimflam unnecessary.
#  The converted script is short, sweet, and clean,
#+ which is more than can be said for the original.

The 101 Most Useful Websites

The Most Useful Websites and Web Apps

  1. ctrlq.org/screenshots – for capturing screenshots of web pages on mobile and desktops.
  2. dictation.io – online voice recognition in the browser itself.
  3. zerodollarmovies.com – find full-length movies on YouTube.
  4. screenr.com – record movies of your desktop and send them straight to YouTube.
  5. goo.gl – shorten long URLs and convert URLs into QR codes.
  6. unfurlr.come – find the original URL that’s hiding behind a short URL.
  7. qClock – find the local time of a city using Google Maps.
  8. copypastecharacter.com – copy special characters that aren’t on your keyboard.
  9. codeacademy.com – the best place to learn coding online.
  10. lovelycharts.com – create flowcharts, network diagrams, sitemaps, etc.
  11. iconfinder.com – find icons of all sizes.
  12. office.com – download templates, clipart and images for your Office documents.
  13. followupthen.com – the easiest way to setup email reminders.
  14. jotti.org – scan any suspicious file or email attachment for viruses.
  15. wolframalpha.com – gets answers directly without searching   – see more wolfram tips.
  16. printwhatyoulike.com – print web pages without the clutter.
  17. ctrlq.save – save online files to Dropbox or Google Drive directly.
  18. ctrql.rss – a search engine for RSS feeds.
  19. e.ggtimer.com – a simple online timer for your daily needs.
  20. coralcdn.org – if a site is down due to heavy traffic, try accessing it through coral CDN.
  21. random.org – pick random numbers, flip coins, and more.
  22. pdfescape.com – lets you can quickly edit PDFs in the browser itself.
  23. tubemogul.com – simultaneously upload videos to YouTube and other video sites.
  24. scr.im – share you email address online without worrying about spam.
  25. spypig.com – now get read receipts for your email.
  26. myfonts.com/WhatTheFont – quickly determine the font name from an image.
  27. google.com/webfonts – a good collection of open source fonts.
  28. regex.info – find data hidden in your photographs – see more EXIF tools.
  29. livestream.com – broadcast events live over the web, including your desktop screen.
  30. iwantmyname.com – helps you search domains across all TLDs.
  31. homestyler.com – design from scratch or re-model your home in 3d.
  32. join.me – share you screen with anyone over the web.
  33. onlineocr.net – recognize text from scanned PDFs – see other OCR tools.
  34. flightstats.com – Track flight status at airports worldwide.
  35. wetransfer.com – for sharing really big files online.
  36. hundredzeros.com – the site lets you download free Kindle books.
  37. polishmywriting.com – check your writing for spelling or grammatical errors.
  38. marker.to – easily highlight the important parts of a web page for sharing.
  39. typewith.me – work on the same document with multiple people.
  40. whichdateworks.com – planning an event? find a date that works for all.
  41. everytimezone.com – a less confusing view of the world time zones.
  42. gtmetrix.com – the perfect tool for measuring your site performance online.
  43. noteflight.com – print music sheets, write your own music online (review).
  44. imo.im – chat with your buddies on Skype, Facebook, Google Talk, etc. from one place.
  45. translate.google.com – translate web pages, PDFs and Office documents.
  46. kleki.com – create paintings and sketches with a wide variety of brushes.
  47. similarsites.com – discover new sites that are similar to what you like already.
  48. wordle.net – quick summarize long pieces of text with tag clouds.
  49. bubbl.us – create mind-maps, brainstorm ideas in the browser.
  50. kuler.adobe.com – get color ideas, also extract colors from photographs.
  51. liveshare.com – share your photos in an album instantly.
  52. lmgtfy.com – when your friends are too lazy to use Google on their own.
  53. midomi.com – when you need to find the name of a song.
  54. google.com/history – see your past searches, also among most important Google URLs
  55. bing.com/images – automatically find perfectly-sized wallpapers for mobiles.
  56. faxzero.com – send an online fax for free – see more fax services.
  57. feedmyinbox.com – get RSS feeds as an email newsletter.
  58. ge.tt – qiuckly send a file to someone, they can even preview it before downloading.
  59. pipebytes.com – transfer files of any size without uploading to a third-party server.
  60. tinychat.com – setup a private chat room in micro-seconds.
  61. privnote.com – create text notes that will self-destruct after being read.
  62. boxoh.com – track the status of any shipment on Google Maps – alternative.
  63. mondrian.io – create vector drawings in the browser
  64. draw.io – create diagrams and flowcharts in the browser, export your drawings to Google Drive and Dropbox.
  65. downforeveryoneorjustme.com – find if your favorite website is offline or not?
  66. ewhois.com – find the other websites of a person with reverse Analytics lookup.
  67. whoishostingthis.com – find the web host of any website.
  68. labnol.org – software tutorials and how-to guides.
  69. disposablewebpage.com – create a temporary web page that self-destruct.
  70. urbandictionary.com – find definitions of slangs and informal words.
  71. seatguru.com – consult this site before choosing a seat for your next flight.
  72. unsplash.com – download images absolutely free.
  73. zoom.it – view very high-resolution images in your browser without scrolling.
  74. scribblemaps.com – create custom Google Maps easily.
  75. alertful.com – quickly setup email reminders for important events.
  76. picmonkey.com – Picnik is offline but PicMonkey is an even better image editor.
  77. formspring.me – you can ask or answer personal questions here.
  78. sumopaint.com – an excellent layer-based online image editor.
  79. snopes.com – find if that email offer you received is real or just another scam.
  80. typingweb.com – master touch-typing with these practice sessions.
  81. mailvu.com – send video emails to anyone using your web cam.
  82. timerime.com – create timelines with audio, video and images.
  83. stupeflix.com – make a movie out of your images, audio and video clips.
  84. safeweb.norton.com – check the trust level of any website.
  85. teuxdeux.com – a beautiful to-do app that looks like your paper dairy.
  86. deadurl.com – you’ll need this when your bookmarked web pages are deleted.
  87. minutes.io – quickly capture effective notes during meetings.
  88. youtube.com/leanback – Watch YouTube channels in TV mode.
  89. youtube.com/disco – quickly create a video playlist of your favorite artist.
  90. talltweets.com – Send tweets longer than 140 characters.
  91. pancake.io – create a free and simple website using your Dropbox account.
  92. builtwith.com – find the technology stack to know everything about a website.
  93. woorank.com – research a website from the SEO perspective.
  94. mixlr.com – broadcast live audio over the web.
  95. radbox.me – bookmark online videos and watch them later (review).
  96. tagmydoc.com – add QR codes to your documents and presentations (review).
  97. notes.io – the easiest way to write short text notes in the browser.
  98. ctrlq.org/html-mail – send rich-text mails to anyone, anonymously.
  99. fiverr.com – hire people to do little things for $5.
  100. otixo.com – easily manage your online files on Dropbox, Google Docs, etc.
  101. ifttt.com – create a connection between all your online accounts.



DATA PUMP

1)   Import 11g data dump into 10g

You can use Oracle data dump to export data dump from 11g server, and import into 10g using the data Pump parameter called Version. When you use Version, Datapump exports all objects that are compatible for your target version

So, If your database is 11g and you want to export 11g and import into 10g

from 11g db ,


$  expdp  Test_schema_name/passs directory=datapump  schemas=Test_schema_name Version=10.2.0.4.0.

Once the export is done, you do the regular import from 10g server.




2)   Import multiple dump files

If the size of the dump file is large, usually they will be split into smaller chunks for easier ftp upload/download.

If you are trying to import a dump file that is split into many chunks, then you need to modify the DUMPFILE paratermeter to include %U

Ex:  If the dump files are named EXP_PROD_1.dmp, EXP_PROD_2.dmp etc ,    then  DUMPFILE=EXP_PROD_%U.DMP




3)   How to kill data pump jobs

When you import or export using data pump impdp or expdp commands, the import/export is done by a job. You have an option to provide a job name using JOB_NAME parameter too

Following sql will give you the list of data pump jobs

select * from dba_datapump_jobs
If you want to kill your impdp or expdp

1) Make sure that your impdp/expdp command prompt window is active
2) Press Control-C , It will pause the job. Don't press another Control-C or close the command prompt. This will just close the window, but the job will still be running in the background
3) Type Kill_Job
ex:
 Import> kill_job
Are you sure you wish to stop this job (y/n): y
If by mistake, you closed the window and your import/export job is still running,

1) Get the name of the job using
select * from dba_datapump_jobs


2) Open a new command prompt window. If you want to kill your import job type
impdp username/password@database attach=name_of_the_job


3) Once you are attached to job, Type Kill_Job
ex:
 Import> kill_job
Are you sure you wish to stop this job (y/n): y

And your job is killed, it will no longer show in dba_datapump_jobs


4) REUSE_DUMPFILE :( Overwrite existing dumpfile)

This is the option with data pump expdp utility. Normally when you perform the export using expdp utility and if the dumpfile is present in the export directory it will throw an error “ORA-27038: created file already exists”. This situation happens when you wanted to perform the repetitive exports using the same dumpfile. Oracle provides an option reuse_dumpfile=[Y/N] to avoid this error. You should mention the parameter value as Y to overwrite the existing dump file. By default the option considered as N.

          $ expdp   scott/tiger   directory=exp_dir     dumpfile = x.dmp     table s= example    reuse_dumpfiles = y

DBA SCRIPTS

1) DROP USER OBJECTS:

conn username/password --->>> MANDATORY to connect as a user

declare
cursor fkc is  select  table_name,
constraint_name
from  user_constraints
where constraint_type ='R';
tname user_constraints.table_name%TYPE;
cname user_constraints.constraint_name%TYPE;
begin
open fkc;
loop
fetch fkc into tname, cname;
exit when fkc%NOTFOUND;
dbms_output.put_line('alter table '||tname||' drop constraint '||cname);
execute immediate 'alter table '||tname||' drop constraint '||cname;
end loop;
close fkc;

end;
/

declare
cursor fkc is  select  object_name,
object_type
from  user_objects
where object_name not in
('INDEX','PACKAGE BODY');
obj_name user_objects.object_name%TYPE;
obj_type user_objects.object_type%TYPE;
begin
open fkc;
loop
fetch fkc into obj_name, obj_type;
exit when fkc%NOTFOUND;
dbms_output.put_line('Drop '||obj_type||' '||obj_name);
begin
  execute immediate 'Drop '||obj_type||' '||obj_name;
exception
  when others then null;
end;
end loop;
close fkc;
end;
/

PURGE RECYCLEBIN;

DECLARE

the_job user_jobs.job%TYPE;
cursor c1 is select job from user_jobs;
BEGIN
open c1;
loop
fetch c1 into the_job;
exit when c1%NOTFOUND;
dbms_job.remove(the_job);
end loop;
close c1;
END;
/

VERIFY :

     set heading off
SQL >   select 'Objects left in schema : ' from dual;
SQL>    select object_name,object_type from user_objects;

SQL>   select 'Jobs left in schema: ' from dual;
SQL>   select job,what from user_jobs;


2) User privileges & Grantee :

SELECT grantee, privilege, admin_option
FROM sys.dba_sys_privs
WHERE (privilege LIKE '% ANY %'
OR privilege IN ('BECOME USER', 'UNLIMITED TABLESPACE')
OR admin_option = 'YES')
AND grantee NOT IN ('SYS', 'SYSTEM', 'OUTLN', 'AQ_ADMINISTRATOR_ROLE',
'DBA', 'EXP_FULL_DATABASE', 'IMP_FULL_DATABASE',
'OEM_MONITOR', 'CTXSYS', 'DBSNMP', 'IFSSYS',
'IFSSYS$CM', 'MDSYS', 'ORDPLUGINS', 'ORDSYS',
'TIMESERIES_DBA')



3) Free Space :
//** This script lists all Tablespaces and its datafiles with their free and used space **//

SET SERVEROUTPUT ON
SET PAGESIZE 1000
SET LINESIZE 255
SET FEEDBACK OFF

SELECT Substr(df.tablespace_name,1,20) "Tablespace Name",
       Substr(df.file_name,1,40) "File Name",
       Round(df.bytes/1024/1024,2) "Size (M)",
       Round(e.used_bytes/1024/1024,2) "Used (M)",
       Round(f.free_bytes/1024/1024,2) "Free (M)",
       Rpad(' '|| Rpad ('X',Round(e.used_bytes*10/df.bytes,0), 'X'),11,'-') "% Used"
FROM   DBA_DATA_FILES  df,
       (SELECT file_id, Sum(Decode(bytes,NULL,0,bytes)) used_bytes
           FROM dba_extents  GROUP by file_id)  e,
       (SELECT Max(bytes) free_bytes, file_id
           FROM dba_free_space   GROUP BY file_id) f
WHERE  e.file_id (+) = df.file_id
AND    df.file_id  = f.file_id (+)
ORDER BY df.tablespace_name, df.file_name;


4) Tablespaces :

//** This script lists all Tablespaces with their Sizes **// 

SELECT /* + RULE */  df.tablespace_name "Tablespace",
       df.bytes / (1024 * 1024) "Size (MB)",
       SUM(fs.bytes) / (1024 * 1024) "Free (MB)",
       Nvl(Round(SUM(fs.bytes) * 100 / df.bytes),1) "% Free",
       Round((df.bytes - SUM(fs.bytes)) * 100 / df.bytes) "% Used"
  FROM dba_free_space fs,
       (SELECT tablespace_name,SUM(bytes) bytes
          FROM dba_data_files
         GROUP BY tablespace_name) df
 WHERE fs.tablespace_name (+)  = df.tablespace_name
 GROUP BY df.tablespace_name,df.bytes
UNION ALL
SELECT /* + RULE */ df.tablespace_name tspace,
       fs.bytes / (1024 * 1024),
       SUM(df.bytes_free) / (1024 * 1024),
       Nvl(Round((SUM(fs.bytes) - df.bytes_used) * 100 / fs.bytes), 1),
       Round((SUM(fs.bytes) - df.bytes_free) * 100 / fs.bytes)
  FROM dba_temp_files fs,
       (SELECT tablespace_name,bytes_free,bytes_used
          FROM v$temp_space_header
         GROUP BY tablespace_name,bytes_free,bytes_used) df
 WHERE fs.tablespace_name (+)  = df.tablespace_name
 GROUP BY df.tablespace_name,fs.bytes,df.bytes_free,df.bytes_used
 ORDER BY 4 DESC;
5) Locked_objects :


SET LINESIZE 500
SET PAGESIZE 1000
SET VERIFY OFF

COLUMN owner FORMAT A20
COLUMN username FORMAT A20
COLUMN object_owner FORMAT A20
COLUMN object_name FORMAT A30
COLUMN locked_mode FORMAT A15

SELECT b.session_id AS sid,
       NVL(b.oracle_username, '(oracle)') AS username,
       a.owner AS object_owner,
       a.object_name,
       Decode(b.locked_mode, 0, 'None',
                             1, 'Null (NULL)',
                             2, 'Row-S (SS)',
                             3, 'Row-X (SX)',
                             4, 'Share (S)',
                             5, 'S/Row-X (SSX)',
                             6, 'Exclusive (X)',
                             b.locked_mode) locked_mode,
       b.os_user_name
FROM   dba_objects a,
       v$locked_object b
WHERE  a.object_id = b.object_id
ORDER BY 1, 2, 3, 4;

SET PAGESIZE 14
SET VERIFY ON



6) Data Pump Monitoring Script : 

select sid, serial#, sofar, totalwork, dp.owner_name, dp.state, dp.job_mode
from gv$session_longops sl, gv$datapump_job dp
where sl.opname = dp.job_name and sofar != totalwork;

7) RMAN Job Monitoring Script :
SQL >  SELECT SID, SERIAL#, CONTEXT, SOFAR, TOTALWORK,ROUND(SOFAR/TOTALWORK*100,2) "%_COMPLETE"
        FROM V$SESSION_LONGOPS
        WHERE OPNAME LIKE 'RMAN%'  AND OPNAME NOT LIKE '%aggregate%' 
              AND TOTALWORK != 0 AND SOFAR <> TOTALWORK ;

To see the Rman status and SID:

SQL >  SELECT s.SID, p.SPID, s.CLIENT_INFO FROM V$PROCESS p, V$SESSION s
       WHERE p.ADDR = s.PADDR AND CLIENT_INFO LIKE 'rman%';



8) To see what USERS are Running :
SELECT a.sid, a.serial#, a.username, b.sql_text FROM v$session a, v$sqlarea b
WHERE a.sql_address=b.address;

**** To see for a particular USER, what he is running *******

SELECT a.sid, a.serial#, a.username, b.sql_text FROM v$session a, v$sqlarea b
WHERE a.sql_address=b.address and a.username = '<username>';


9) Find FREE/USED/TOTAL size of oracle database : 

(used space):
----------------
SQL> select sum(bytes)/1024/1024/1024 GB from dba_segments;


(free space):
---------------
SQL> select sum(bytes)/1024/1024/1024 GB from dba_free_space;


(Total database size):
---------------------------
SQL> select sum(bytes)/1024/1024/1024 GB from dba_data_files;

  +

(Temp size):
---------------
SQL> select SUM(bytes_used)/1024/1024/1024 GBused, SUM(bytes_free)/1024/1024/1024 GBfree from  v$temp_space_header;

(or)

SELECT SUM (a.log_space + b.data_space + c.tempspace) "Total_DB_Size (G)"
   FROM (SELECT ROUND (SUM (BYTES/1024/1024/1024), 2) data_space  FROM dba_data_files) b,(SELECT ROUND (SUM (BYTES*members/1024/1024/1024), 2) log_space  FROM v$log) a, (SELECT NVL(ROUND(SUM(BYTES/1024/1024/1024),2), 0) tempspace
     FROM dba_temp_files) c;


10) RMAN Cold Backup :



Rman target / nocatalog
Rman > configure controlfile autobackup on;
Rman >  run {
2>  allocate channel d1 type disk;
3> Backup full tag full_offline_bkup
4> Format ‘/var/backup/corppsdb/rman/db_t%t_s%s_p%p’
5> Database plus archivelog;
6> Release channel d1;
}