Step by Step Creating a physical standby database on Oracle 11.2.0.1.0 using RMAN

Creating a physical standby database on Oracle 11.2.0.1.0 using RMAN :-

OS Version:-Red Hat Enterprise Linux Server release 6.4
Oracle version:- Oracle Database 12c Enterprise Edition Release 11.2.0.1.0 64bit
Primary database:- prim   
Standby database:- stand

System Configuration

primary server:-

edit the following files

vi /etc/hosts

192.168.2.102   server1.soumya.com      server1
192.168.2.104   server2.soumya.com      server2

:wq

vi /etc/sysconfig/network
HOSTNAME=server1.soumya.com

:wq

vi /etc/sysconfig/network-scripts/ifcfg-eth0

NETMASK=255.255.255.0
IPADDR=192.168.2.102
GATEWAY=192.168.2.1

:wq

Standby Server:-

edit the following files

vi /etc/hosts

192.168.2.102   server1.soumya.com      server1
192.168.2.104   server2.soumya.com      server2
:wq

vi /etc/sysconfig/network

HOSTNAME=server2.soumya.com

:wq

vi /etc/sysconfig/network-scripts/ifcfg-eth0

NETMASK=255.255.255.0
IPADDR=192.168.2.104
GATEWAY=192.168.2.1

:wq

In both server-- # service network restart
                 # service NetworkManager restart
                 # service iptables stop
                 # chkconfig iptables off
                 #vi /etc/selinux/config and disable selinux .
                  After changing inside the file please restart the server.       
               
We have a database called prim on primary server and  we will install only oracle binaries on
standby server(192.168.2.104).No database should be running in standby server.
                 



Oracle Net configuration:-

Listener.ora configuration for primary database (prim) in primary server (192.168.2.102)

vi $ORACLE_HOME/network/admin/listener.ora

SID_LIST_LISTENER =
  (SID_LIST =
    (SID_DESC =
      (GLOBAL_DBNAME = prim)
      (ORACLE_HOME = /u01/app/oracle/product/11.2.0/db_1)
      (SID_NAME = prim)
    )
  )
LISTENER =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = server1.soumya.com)(PORT = 1521))
  )
ADR_BASE_LISTENER = /u01/app/oracle

:wq

Listener.ora configuration for standby database (stand) in standby server (192.168.2.104)
vi $ORACLE_HOME/network/admin/listener.ora

SID_LIST_LISTENER =
  (SID_LIST =
    (SID_DESC =
      (GLOBAL_DBNAME = stand)
      (ORACLE_HOME = /u01/app/oracle/product/11.2.0/db_1)
      (SID_NAME = stand)
    )
  )
LISTENER =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = server2.soumya.com)(PORT = 1521))
  )
ADR_BASE_LISTENER = /u01/app/oracle

:wq

On both server(192.168.2.102 & 192.168.2.104), add Oracle Net aliases for both databases and aux alias for RMAN DUPLICATE in
tnsnames.ora:

vi $ORACLE_HOME/network/admin/tnsnames.ora

prim =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = server1.soumya.com)(PORT = 1521))
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = prim)
    )
  )

stand =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = server2.soumya.com)(PORT = 1521))
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = stand)
    )
  )

-save & exit(:wq )

Now we will have to start listener in primary and standby server:-

$ lsnrctl start

Check "tnsping prim" & "tnsping stand"  in both server. If output of both command is
coming as "ok" that means oracle net service has been added successfully.

In primary database:-
Put the database in archivelog mode.
SQL> archive log list
Database log mode              No Archive Mode
Automatic archival             Disabled
Archive destination            USE_DB_RECOVERY_FILE_DEST
Oldest online log sequence     2
Current log sequence           4

SQL> shut immediate;
Database closed.
Database dismounted.
ORACLE instance shut down.


SQL> startup mount
ORACLE instance started.

Total System Global Area  629145600 bytes
Fixed Size                  2927528 bytes
Variable Size             511706200 bytes
Database Buffers          109051904 bytes
Redo Buffers                5459968 bytes
Database mounted.

SQL> alter database archivelog;
Database altered.

SQL> archive log list
Database log mode              Archive Mode
Automatic archival             Enabled
Archive destination            USE_DB_RECOVERY_FILE_DEST
Oldest online log sequence     2
Next log sequence to archive   4
Current log sequence           4

SQL> alter database open;

In Primary Database:-

Enable force logging The FORCE LOGGING option to ensure that all the changes made in the database
will be captured and available for recovery in the redo logs.

SQL> alter database force logging;
Database altered.

SQL> select force_logging from v$database;

FORCE_LOGGING
---------------------------------------
YES

Create a password file
$ orapwd file=$ORACLE_HOME/dbs/orapwprim password=redhat
$ cd $ORACLE_HOME/dbs/
$ chmod 775 orapwprim
$ cp orapwprim orapwstand

Now transfer the password file  into standby server using scp command
$ scp orapwstand oracle@192.168.2.104:/u01/app/oracle/product/11.2.0/db_1/dbs/


Add following parameter in pfile for primary database.

create pfile='/u01/app/oracle/product/11.2.0/db_1/dbs/initprim.ora' from spfile;   

vi /u01/app/oracle/product/11.2.0/db_1/dbs/initprim.ora

*.db_name='prim'
*.db_unique_name='prim'
*.log_archive_config='DG_CONFIG=(prim, stand)'
*.log_archive_dest_1='LOCATION=/u01/app/oracle/flash_recovery_area VALID_FOR=(ALL_LOGFILES,ALL_ROLES) DB_UNIQUE_NAME=prim'
*.log_archive_dest_2='SERVICE=stand LGWR ASYNC VALID_FOR=(ALL_LOGFILES,PRIMARY_ROLE) DB_UNIQUE_NAME=stand'
*.log_archive_dest_state_1=enable
*.log_archive_dest_state_2=enable
*.FAL_SERVER=stand
*.FAL_CLIENT=prim
*.db_file_name_convert='/u01/app/oracle/oradata/stand/','/u01/app/oracle/oradata/prim/'
*.log_file_name_convert='/u01/app/oracle/oradata/stand/','/u01/app/oracle/oradata/prim/'
*.standby_file_management=auto   

-save & exit(:wq)

SQL> shut immediate;

SQL>  startup mount pfile='/u01/app/oracle/product/11.2.0/db_1/dbs/initprim.ora';
SQL> create spfile from pfile='/u01/app/oracle/product/11.2.0/db_1/dbs/initprim.ora';

SQL> alter database open;
Total System Global Area  413372416 bytes
Fixed Size                  2213896 bytes
Variable Size             339740664 bytes
Database Buffers           67108864 bytes
Redo Buffers                4308992 bytes
Database mounted.
Database opened.

At Standby database:-
Create the necessary directory structure:-
$ mkdir -p /u01/app/oracle/oradata/stand/
$ mkdir -p /u01/app/oracle/admin/stand/adump
$ mkdir -p /u01/app/oracle/flash_recovery_area/stand/
$ chmod 775 -Rf /u01

Configure .bash_profile
[oracle@server2 ~]$ vi .bash_profile

# .bash_profile

# Get the aliases and functions
if [ -f ~/.bashrc ]; then
        . ~/.bashrc
fi

# User specific environment and startup programs

PATH=$PATH:$HOME/bin

export PATH
export TMP=/tmp
export TMPDIR=$TMP
export ORACLE_HOSTNAME=server2.soumya.com
export ORACLE_UNQNAME=stand
export ORACLE_BASE=/u01/app/oracle
export ORACLE_HOME=$ORACLE_BASE/product/11.2.0/db_1
export ORACLE_SID=stand
export PATH=/usr/sbin:$ORACLE_HOME/bin:$PATH
export LD_LIBRARY_PATH=$ORACLE_HOME/lib:/lib:/usr/lib:/usr/lib64
export CLASSPATH=$ORACLE_HOME/jlib:$ORACLE_HOME/rdbms/jlib

Now start the instance in nomount mode with minimal options

vi initstand.ora
DB_NAME=prim
DB_UNIQUE_NAME=stand
DB_BLOCK_SIZE=8192

:wq


SQL> startup nomount pfile='/home/oracle/initstand.ora';
ORACLE instance started.

Total System Global Area  413372416 bytes
Fixed Size                  2213896 bytes
Variable Size             339740664 bytes
Database Buffers           67108864 bytes
Redo Buffers                4308992 bytes

At primary database:-
Add the standby redologs.
SQL>  select group#, members , bytes /1024 /1024 from v$log;

    GROUP#    MEMBERS BYTES/1024/1024
---------- ---------- ---------------
         1          1              50
         2          1              50
         3          1              50
       
SQL> select group# , member from v$logfile;
    GROUP# MEMBER
---------- --------------------------------------------------
         3 /u01/app/oracle/oradata/prim/redo03.log
         2 /u01/app/oracle/oradata/prim/redo02.log
         1 /u01/app/oracle/oradata/prim/redo01.log       
       
       
SQL> alter database add standby logfile group 4 '/u01/app/oracle/oradata/prim/redos4A.log' size 50M;
SQL> alter database add standby logfile group 5 '/u01/app/oracle/oradata/prim/redos5A.log' size 50M;
SQL> alter database add standby logfile group 6 '/u01/app/oracle/oradata/prim/redos6A.log' size 50M;
SQL> alter database add standby logfile group 7 '/u01/app/oracle/oradata/prim/redos7A.log' size 50M;

SQL> select group# , member from v$logfile;
    GROUP# MEMBER
---------- --------------------------------------------------------------------------------
         3 /u01/app/oracle/oradata/prim/redo03.log
         2 /u01/app/oracle/oradata/prim/redo02.log
         1 /u01/app/oracle/oradata/prim/redo01.log
         4 /u01/app/oracle/oradata/prim/redos4A.log
         5 /u01/app/oracle/oradata/prim/redos5A.log
         6 /u01/app/oracle/oradata/prim/redos6A.log
         7 /u01/app/oracle/oradata/prim/redos7A.log


At standby database:-
Now once the redoglogs have been created in primary database,we will create the following RMAN run commands and  the changes to the standby’s spfile in this RMAN block.

[oracle@server2 ]rman target sys/redhat@prim auxiliary sys/redhat@stand   
Recovery Manager: Release 11.2.0.1.0 - Production on Mon Sep 7 14:43:25 2015

Copyright (c) 1982, 2009, Oracle and/or its affiliates.  All rights reserved.

connected to target database: PRIM (DBID=4130009889)
connected to auxiliary database: PRIM (not mounted)

RMAN>run {
allocate channel prmy1 type disk;
allocate channel prmy2 type disk;
allocate channel prmy3 type disk;
allocate channel prmy4 type disk;
allocate auxiliary channel stby type disk;
duplicate target database for standby from active database
spfile
parameter_value_convert 'prim','stand'
set db_unique_name='stand'
set db_file_name_convert='/u01/app/oracle/oradata/prim/','/u01/app/oracle/oradata/stand/'
set log_file_name_convert='/u01/app/oracle/oradata/prim/','/u01/app/oracle/oradata/stand/'
set control_files='/u01/app/oracle/oradata/stand/control01.ctl','/u01/app/oracle/oradata/stand/control02.ctl'
set log_archive_max_processes='10'
set fal_client='stand'
set fal_server='prim'
set standby_file_management='AUTO'
set log_archive_config='dg_config=(prim,stand)'
set log_archive_dest_2='service=prim ASYNC valid_for=(ONLINE_LOGFILE,PRIMARY_ROLE) db_unique_name=prim'
;
}

using target database control file instead of recovery catalog
allocated channel: prmy1
channel prmy1: SID=32 device type=DISK

allocated channel: prmy2
channel prmy2: SID=33 device type=DISK

allocated channel: prmy3
channel prmy3: SID=34 device type=DISK

allocated channel: prmy4
channel prmy4: SID=35 device type=DISK

allocated channel: stby
channel stby: SID=19 device type=DISK

Starting Duplicate Db at 16-MAY-13

contents of Memory Script:
{
 backup as copy reuse
 targetfile '/u01/app/oracle/product/11.2.0/db_1/dbs/orapwprim' auxiliary format
 '/u01/app/oracle/product/11.2.0/db_1/dbs/orapwstand' targetfile
 '/u01/app/oracle/product/11.2.0/db_1/dbs/spfileprim.ora' auxiliary format
 '/u01/app/oracle/product/11.2.0/db_1/dbs/spfilestand.ora' ;
 sql clone "alter system set spfile= ''/u01/app/oracle/product/11.2.0/db_1/dbs/spfilestand.ora''";
}
executing Memory Script

Starting backup at 16-MAY-13
Finished backup at 16-MAY-13

sql statement: alter system set spfile= ''/u01/app/oracle/product/11.2.0/db_1/dbs/spfilestand.ora''

contents of Memory Script:
{
 sql clone "alter system set audit_file_dest =
 ''/u01/app/oracle/oradata/dump/stand/adump'' comment=
 '''' scope=spfile";
 sql clone "alter system set diagnostic_dest =
 ''/u01/app/oracle/oradata/dump/stand'' comment=
 '''' scope=spfile";
 sql clone "alter system set log_archive_dest_1 =
 ''location=use_db_recovery_file_dest valid_for=(ALL_LOGFILES,ALL_ROLES) DB_UNIQUE_NAME=stand'' comment=
 '''' scope=spfile";
 sql clone "alter system set db_unique_name =
 ''stand'' comment=
 '''' scope=spfile";
 sql clone "alter system set db_file_name_convert =
 ''/u01/app/oracle/oradata/prim/prim/datafile/'', ''/u01/app/oracle/oradata/stand/stand/datafile/'' comment=
 '''' scope=spfile";
 sql clone "alter system set log_file_name_convert =
 ''/u01/app/oracle/oradata/prim/prim/onlinelog/'', ''/u01/app/oracle/oradata/stand/stand/onlinelog/'' comment=
 '''' scope=spfile";
 sql clone "alter system set control_files =
 ''/u01/app/oracle/oradata/stand/control/control01.ctl'', ''/u01/app/oracle/oradata/stand/control/control02.ctl'' comment=
 '''' scope=spfile";
 sql clone "alter system set log_archive_max_processes =
 10 comment=
 '''' scope=spfile";
 sql clone "alter system set fal_client =
 ''stand'' comment=
 '''' scope=spfile";
 sql clone "alter system set fal_server =
 ''prim'' comment=
 '''' scope=spfile";
 sql clone "alter system set standby_file_management =
 ''AUTO'' comment=
 '''' scope=spfile";
 sql clone "alter system set log_archive_config =
 ''dg_config=(prim,stand)'' comment=
 '''' scope=spfile";
 sql clone "alter system set log_archive_dest_2 =
 ''service=prim ASYNC valid_for=(ONLINE_LOGFILE,PRIMARY_ROLE) db_unique_name=prim'' comment=
 '''' scope=spfile";
 shutdown clone immediate;
 startup clone nomount;
}
executing Memory Script

sql statement: alter system set audit_file_dest = ''/u01/app/oracle/oradata/dump/stand/adump'' comment= '''' scope=spfile

sql statement: alter system set diagnostic_dest = ''/u01/app/oracle/oradata/dump/stand'' comment= '''' scope=spfile

sql statement: alter system set log_archive_dest_1 = ''location=use_db_recovery_file_dest valid_for=(ALL_LOGFILES,ALL_ROLES) DB_UNIQUE_NAME=stand'' comment= '''' scope=spfile

sql statement: alter system set db_unique_name = ''stand'' comment= '''' scope=spfile

sql statement: alter system set db_file_name_convert = ''/u01/app/oracle/oradata/prim/prim/datafile/'', ''/u01/app/oracle/oradata/stand/stand/datafile/'' comment= '''' scope=spfile

sql statement: alter system set log_file_name_convert = ''/u01/app/oracle/oradata/prim/prim/onlinelog/'', ''/u01/app/oracle/oradata/stand/stand/onlinelog/'' comment= '''' scope=spfile

sql statement: alter system set control_files = ''/u01/app/oracle/oradata/stand/control/control01.ctl'', ''/u01/app/oracle/oradata/stand/control/control02.ctl'' comment= '''' scope=spfile

sql statement: alter system set log_archive_max_processes = 10 comment= '''' scope=spfile

sql statement: alter system set fal_client = ''stand'' comment= '''' scope=spfile

sql statement: alter system set fal_server = ''prim'' comment= '''' scope=spfile

sql statement: alter system set standby_file_management = ''AUTO'' comment= '''' scope=spfile

sql statement: alter system set log_archive_config = ''dg_config=(prim,stand)'' comment= '''' scope=spfile

sql statement: alter system set log_archive_dest_2 = ''service=prim ASYNC valid_for=(ONLINE_LOGFILE,PRIMARY_ROLE) db_unique_name=prim'' comment= '''' scope=spfile

Oracle instance shut down

connected to auxiliary database (not started)
Oracle instance started

Total System Global Area 534462464 bytes

Fixed Size 2230072 bytes
Variable Size 163580104 bytes
Database Buffers 364904448 bytes
Redo Buffers 3747840 bytes
allocated channel: stby
channel stby: SID=18 device type=DISK

contents of Memory Script:
{
 backup as copy current controlfile for standby auxiliary format '/u01/app/oracle/oradata/stand/control/control01.ctl';
 restore clone controlfile to '/u01/app/oracle/oradata/stand/control/control02.ctl' from
 '/u01/app/oracle/oradata/stand/control/control01.ctl';
}
executing Memory Script

Starting backup at 16-MAY-13
channel prmy1: starting datafile copy
copying standby control file
output file name=/u01/app/oracle/product/11.2.0/dbhome_1/dbs/snapcf_prim.f tag=TAG20130516T084319 RECID=7 STAMP=815561001
channel prmy1: datafile copy complete, elapsed time: 00:00:07
Finished backup at 16-MAY-13

Starting restore at 16-MAY-13

channel stby: copied control file copy
Finished restore at 16-MAY-13

contents of Memory Script:
{
 sql clone 'alter database mount standby database';
}
executing Memory Script

sql statement: alter database mount standby database

contents of Memory Script:
{
 set newname for tempfile 1 to
 "/u01/app/oracle/oradata/stand/stand/datafile/o1_mf_temp_8qbok7fk_.tmp";
 switch clone tempfile all;
 set newname for datafile 1 to
 "/u01/app/oracle/oradata/stand/stand/datafile/o1_mf_system_8ocl7bho_.dbf";
 set newname for datafile 2 to
 "/u01/app/oracle/oradata/stand/stand/datafile/o1_mf_sysaux_8ocl7k6n_.dbf";
 set newname for datafile 3 to
 "/u01/app/oracle/oradata/stand/stand/datafile/o1_mf_sys_undo_8ocl7q6c_.dbf";
 set newname for datafile 4 to
 "/u01/app/oracle/oradata/stand/stand/datafile/o1_mf_users_8qbolh3g_.dbf";
 backup as copy reuse
 datafile 1 auxiliary format
 "/u01/app/oracle/oradata/stand/stand/datafile/o1_mf_system_8ocl7bho_.dbf" datafile
 2 auxiliary format
 "/u01/app/oracle/oradata/stand/stand/datafile/o1_mf_sysaux_8ocl7k6n_.dbf" datafile
 3 auxiliary format
 "/u01/app/oracle/oradata/stand/stand/datafile/o1_mf_sys_undo_8ocl7q6c_.dbf" datafile
 4 auxiliary format
 "/u01/app/oracle/oradata/stand/stand/datafile/o1_mf_users_8qbolh3g_.dbf" ;
 sql 'alter system archive log current';
}
executing Memory Script

executing command: SET NEWNAME

renamed tempfile 1 to /u01/app/oracle/oradata/stand/stand/datafile/o1_mf_temp_8qbok7fk_.tmp in control file

executing command: SET NEWNAME

executing command: SET NEWNAME

executing command: SET NEWNAME

executing command: SET NEWNAME

Starting backup at 16-MAY-13
channel prmy1: starting datafile copy
input datafile file number=00001 name=/u01/app/oracle/oradata/prim/prim/datafile/o1_mf_system_8ocl7bho_.dbf
channel prmy2: starting datafile copy
input datafile file number=00002 name=/u01/app/oracle/oradata/prim/prim/datafile/o1_mf_sysaux_8ocl7k6n_.dbf
channel prmy3: starting datafile copy
input datafile file number=00003 name=/u01/app/oracle/oradata/prim/prim/datafile/o1_mf_sys_undo_8ocl7q6c_.dbf
channel prmy4: starting datafile copy
input datafile file number=00004 name=/u01/app/oracle/oradata/prim/prim/datafile/o1_mf_users_8qbolh3g_.dbf
output file name=/u01/app/oracle/oradata/stand/stand/datafile/o1_mf_sys_undo_8ocl7q6c_.dbf tag=TAG20130516T084335
channel prmy3: datafile copy complete, elapsed time: 00:00:45
output file name=/u01/app/oracle/oradata/stand/stand/datafile/o1_mf_users_8qbolh3g_.dbf tag=TAG20130516T084335
channel prmy4: datafile copy complete, elapsed time: 00:00:55
output file name=/u01/app/oracle/oradata/stand/stand/datafile/o1_mf_system_8ocl7bho_.dbf tag=TAG20130516T084335
channel prmy1: datafile copy complete, elapsed time: 00:01:05
output file name=/u01/app/oracle/oradata/stand/stand/datafile/o1_mf_sysaux_8ocl7k6n_.dbf tag=TAG20130516T084335
channel prmy2: datafile copy complete, elapsed time: 00:01:05
Finished backup at 16-MAY-13

sql statement: alter system archive log current

contents of Memory Script:
{
 switch clone datafile all;
}
executing Memory Script

datafile 1 switched to datafile copy
input datafile copy RECID=7 STAMP=815561103 file name=/u01/app/oracle/oradata/stand/stand/datafile/o1_mf_system_8ocl7bho_.dbf
datafile 2 switched to datafile copy
input datafile copy RECID=8 STAMP=815561104 file name=/u01/app/oracle/oradata/stand/stand/datafile/o1_mf_sysaux_8ocl7k6n_.dbf
datafile 3 switched to datafile copy
input datafile copy RECID=9 STAMP=815561104 file name=/u01/app/oracle/oradata/stand/stand/datafile/o1_mf_sys_undo_8ocl7q6c_.dbf
datafile 4 switched to datafile copy
input datafile copy RECID=10 STAMP=815561104 file name=/u01/app/oracle/oradata/stand/stand/datafile/o1_mf_users_8qbolh3g_.dbf
Finished Duplicate Db at 16-MAY-13
released channel: prmy1
released channel: prmy2
released channel: prmy3
released channel: prmy4
released channel: stby

RMAN> exit

Now at standby database:-

SQL>shut immediate;
SQL>startup mount
SQL>alter database recover managed standby database disconnect from session;

Now for real time apply:-

SQL> alter database recover managed standby database cancel;

SQL> alter database open;

SQL> alter database recover managed standby database using current logfile disconnect from session;

SQL>select open_mode from v$database; (Output : read only with apply)


There are various ways to see if this is working or not. You can use it in the following query to see what was the last archive received/applied in the Standby Database.

On standby database

SQL> SELECT 'Last Applied : ' Logs,
TO_CHAR(next_time,'DD-MON-YY:HH24:MI:SS') TIME,thread#,sequence#
FROM v$archived_log
WHERE sequence# =
(SELECT MAX(sequence#) FROM v$archived_log WHERE applied='YES'
)
UNION
SELECT 'Last Received : ' Logs,
TO_CHAR(next_time,'DD-MON-YY:HH24:MI:SS') TIME,thread#,sequence#
FROM v$archived_log
WHERE sequence# =
(SELECT MAX(sequence#) FROM v$archived_log );

LOGS             TIME                  THREAD#  SEQUENCE#
---------------- ------------------ ---------- ----------
Last Applied :   07-SEP-15:11:53:22          1         17
Last Received :  07-SEP-15:11:53:22          1         17
While in the Primary Database, you can check what is the current sequence and what is the pending sequence to be applied.

On primary database

SQL> SELECT
 (SELECT name FROM V$DATABASE
 ) name,
 (SELECT MAX (sequence#) FROM v$archived_log WHERE dest_id = 1
 ) Current_primary_seq,
 (SELECT MAX (sequence#)
 FROM v$archived_log
 WHERE TRUNC(next_time) > SYSDATE - 1
 AND dest_id = 2
 ) max_stby,
 (SELECT NVL (
 (SELECT MAX (sequence#) - MIN (sequence#)
 FROM v$archived_log
 WHERE TRUNC(next_time) > SYSDATE - 1
 AND dest_id = 2
 AND applied = 'NO'
 ), 0)
 FROM DUAL
 ) "To be applied",
 (
 (SELECT MAX (sequence#) FROM v$archived_log WHERE dest_id = 1
 ) -
 (SELECT MAX (sequence#) FROM v$archived_log WHERE dest_id = 2
 )) "To be Shipped"
FROM DUAL;

NAME      CURRENT_PRIMARY_SEQ   MAX_STBY To be applied To be Shipped
--------- ------------------- ---------- ------------- -------------
PRIM                       17         17             0             0


Finally Test on primary database to check if the datas are being replicated to standby or not
SQL> create user soumya identified by soumya;
SQL>grant connect , resource to soumya;
SQL> conn soumya/soumya
SQL>create table test (id number);
SQL>insert into test values(1);
SQL> /
SQL> /
SQL> commit;

Now on standby database:-
sqlplus soumya/soumya

SQL> select * from test;

        ID
----------
         1
         1
       
So we can see the datas are applying on standby real time.



Please share your ideas and opinions about this topic.

If you like this post, then please share with others.
Please subscribe on email for every updates on mail.      

How to install Oracle 12C database on RHEL 6.4

Requirements :-

*) For large-scale installation we need to use multicore processors with High availability.
*) Recommended minimum RAM needed for Oracle is 2GB or more.
*) Swap must be enabled double the size of RAM.
*)Disk space must be more than 8GB, its depends on edition which are we going to choose for installing.
*)/tmp directory must have free space more than 1GB for error free installation.
*)Supported Linux operating systems are RHEL, Centos, Oracle.
*)Both x86_64 and i686 packages are required for installation.

Step 1:-Set up Hostname and bind it.

[root@server3 ~]# vi /etc/sysconfig/network
NETWORKING=yes
HOSTNAME=server3.soumya.com

-save & exit(:wq)

[root@server3 ~]$ vi /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.2.104   server3.soumya.com      server3

-save & exit(:wq)


Step 2:-Disable firewall and put selinux on permissisve or disabled mode.
[root@server3 ~]$ service iptables stop
[root@server3 ~] service iptables save

[root@server3 ~]# cat /etc/sysconfig/selinux

# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
#     enforcing - SELinux security policy is enforced.
#     permissive - SELinux prints warnings instead of enforcing.
#     disabled - No SELinux policy is loaded.
SELINUX=disabled
# SELINUXTYPE= can take one of these two values:
#     targeted - Targeted processes are protected,
#     mls - Multi Level Security protection.
SELINUXTYPE=targeted

**Remeber you need to restart the server for the changed selinux settings to put on effect.

Step 3:-Install the required packages using YUM

# From Public Yum
yum install binutils -y
yum install compat-libcap1 -y
yum install compat-libstdc++-33 -y
yum install compat-libstdc++-33.i686 -y
yum install gcc -y
yum install gcc-c++ -y
yum install glibc -y
yum install glibc.i686 -y
yum install glibc-devel -y
yum install glibc-devel.i686 -y
yum install ksh -y
yum install libgcc -y
yum install libgcc.i686 -y
yum install libstdc++ -y
yum install libstdc++.i686 -y
yum install libstdc++-devel -y
yum install libstdc++-devel.i686 -y
yum install libaio -y
yum install libaio.i686 -y
yum install libaio-devel -y
yum install libaio-devel.i686 -y
yum install libXext -y
yum install libXext.i686 -y
yum install libXtst -y
yum install libXtst.i686 -y
yum install libX11 -y
yum install libX11.i686 -y
yum install libXau -y
yum install libXau.i686 -y
yum install libxcb -y
yum install libxcb.i686 -y
yum install libXi -y
yum install libXi.i686 -y
yum install make -y
yum install sysstat -y
yum install unixODBC -y
yum install unixODBC-devel -y

Step 4:- Change the kernel parameters .
Add or amend the following lines in the "/etc/sysctl.conf" file.

[root@server3 ~]# vi
fs.file-max = 6815744
kernel.sem = 250 32000 100 128
kernel.shmmni = 4096
kernel.shmall = 1073741824
kernel.shmmax = 4398046511104
net.core.rmem_default = 262144
net.core.rmem_max = 4194304
net.core.wmem_default = 262144
net.core.wmem_max = 1048576
fs.aio-max-nr = 1048576
net.ipv4.ip_local_port_range = 9000 65500

-save & exit(:wq)

Run the following command to change the current kernel parameters.

[root@server3 ~]# /sbin/sysctl -p


Add the following lines to the "/etc/security/limits.conf" file.

[root@server3 ~]#vi /etc/security/limits.conf
oracle   soft   nofile    1024
oracle   hard   nofile    65536
oracle   soft   nproc    16384
oracle   hard   nproc    16384
oracle   soft   stack    10240
oracle   hard   stack    32768

-save & exit(:wq)

Step 5:-Create required groups and users.

[root@server3 ~]#groupadd -g 520 oinstall
[root@server3 ~]#groupadd -g 521 dba
[root@server3 ~]#groupadd -g 522 oper
[root@server3 ~]#useradd -u 520 -g oinstall -G dba,oper oracle
[root@server3 ~]# passwd oracle
Changing password for user oracle.
New password: *****


Add the following lines to the "/etc/security/limits.d/90-nproc.conf" file.

[root@server3 ~]#vi /etc/security/limits.d/90-nproc.conf
# Change number of process
* soft    nproc    1024
# To this
    *  nproc 16384
-save & exit(:wq)


Step 6:- Create required directories and assign them proper permission / ownerships.

[root@server3 ~]# mkdir -p /u01/app/oracle/product/12.1.0.2/db_1
[root@server3 ~]# chown -Rf oracle:oinstall /u01
[root@server3 ~]# chmod -Rf 775 /u01

Step 7:-Configure bash profile for oracle user.

[root@server3 ~]#vi /home/oracle/.bash_profile
# .bash_profile

# Get the aliases and functions
if [ -f ~/.bashrc ]; then
        . ~/.bashrc
fi

# User specific environment and startup programs

PATH=$PATH:$HOME/bin
export TMP=/u01/tmp
export TMPDIR=$TMP
export ORACLE_HOSTNAME=server3.soumya.com
export ORACLE_UNQNAME=ora12c
export ORACLE_BASE=/u01/app/oracle
export ORACLE_HOME=$ORACLE_BASE/product/12.1.0.2/db_1
export ORACLE_SID=ora12c
export PATH=/usr/sbin:$ORACLE_HOME/bin:$PATH
export LD_LIBRARY_PATH=$ORACLE_HOME/lib:/lib:/usr/lib:/usr/lib64
export CLASSPATH=$ORACLE_HOME/jlib:$ORACLE_HOME/rdbms/jlib

-save & exit(:wq)


Step 7:-Now switch to the directory where the installation file exists extract it.

[root@server3 ~]# cd /u01/
[root@server3 u01]# ls -ltr
total 2625116
-rwxrwxr-x  1 oracle oinstall 1673544724 Mar  1 21:57 linuxamd64_12102_database_1of2.zip
-rwxrwxr-x  1 oracle oinstall 1014530602 Mar  2 19:14 linuxamd64_12102_database_2of2.zip
drwxr-xr-x  4 oracle oinstall       4096 Mar  6 16:22 app

Unzip the installation files.
[root@server3 ~]#unzip linuxamd64_12102_database_1of2.zip
[root@server3 ~]#unzip linuxamd64_12102_database_2of2.zip

Step 8.Now Open X-Manager and start the installation.
*For x-manager make sure "xterm, xorg" packages are installed.

From Xmanager console:-
[root@server3 ~]#su - oracle
[oracle@server3 u01]$ cd database/
[oracle@server3 database]$ ls -ltr
total 36
-rwxrwxr-x  1 oracle oinstall  500 Feb  7  2013 welcome.html
-rwxrwxr-x  1 oracle oinstall 8533 Jul  7  2014 runInstaller
drwxrwxr-x  2 oracle oinstall 4096 Jul  7  2014 rpm
drwxrwxr-x  2 oracle oinstall 4096 Jul  7  2014 sshsetup
drwxrwxr-x  2 oracle oinstall 4096 Jul  7  2014 response
drwxrwxr-x 14 oracle oinstall 4096 Jul  7  2014 stage
drwxrwxr-x  4 oracle oinstall 4096 Mar  6 14:57 install

[oracle@server3 database]$sh runInstaller
In installation window
Step 1 :-Configure security updates => Untick the option "I wish to receive security updates via My oracle support"
Step 2 :-Installation option => Select Create & configure Database.(Incase if you want to configure database choose install database software only )
Step 3 :-System Class => Select Server Class.
Step 4 :-Grid installation option => Select Single instance database installation.
Step 5 :-Install Type => Select Typical install
Step 6 :-Typical installation =>
Make sure at this step we have following paths selected
Oracle_Base =/u01/app/oracle
Software location=/u01/app/oracle/product/12.1.0.2/db_1
Storage type= File system
Database file location=/u01/app/oracle/oradata
OSDBA Group=dba
Global database name=ora12c
Password=provide password
Select option Pluggable Database name=pdbora12c

Step 7 :- It should not make any issue regarding packages or other checks.
Step 8 :- Install.
While the installation is going on it will ask to run following two scripts from root user.
/u01/app/oracle/product/12.1.0.2/db_1/root.sh
/u01/app/oraInventory/oraInstroot.sh

The whole process would take some time..


[oracle@server3 ~]$ sqlplus / as sysdba

SQL*Plus: Release 12.1.0.2.0 Production on Fri Mar 6 18:17:49 2015

Copyright (c) 1982, 2014, Oracle.  All rights reserved.


Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.2.0 - 64bit Production
With the Partitioning, OLAP, Advanced Analytics and Real Application Testing options

SQL> select instance_name from v$instance;

INSTANCE_NAME
----------------
ora12c


Please share your ideas and opinions about this topic.

If you like this post, then please share with others.
Please subscribe on email for every updates on mail.





How to Enable and Disable Database Options in oracle 11g


Installation of Oracle Database 11g Release 2 Software installs all the licensable database options. Though installed, not all the licensable database options are enabled by default.
During installation, installer gives an option for users to enable the licensable database options that are not enabled in a default installation.

SQL> SET LINESIZE 200
SQL> select * from v$option where value ='FALSE';
PARAMETER                                                         VALUE
---------------------------------------                       --------------------------------------
Real Application Clusters                                        FALSE
Automatic Storage Management                            FALSE
Oracle Label Security                                               FALSE
Real Application Testing                                          FALSE

So we see the disabled options are listed above.

To enable an option lets say "Real Application Testing" we would follow the following process.

Step 1:-Stop the database, Database Control console process, and listener.

SQL> shut immediate;
Database closed.
Database dismounted.
ORACLE instance shut down.

[oracle@configsrv2 ~]$ emctl stop dbconsole
[oracle@configsrv2 ~]$ lsnrctl stop


Step 2:-
[oracle@configsrv2 ~]$ cd $ORACLE_HOME/rdbms/lib
[oracle@configsrv2 ~]$ make -f ins_rdbms.mk rat_on ioracle
After hitting the above command it would take some time as this would enable the Real Application Testing option  for the database.

Step 3:-
Once the execution of the above command is done ; we need to start the database, listener and Database Control console process.
[oracle@configsrv2 ~]$ lsnrctl start
SQL> startup
SQL> select * from v$option where parameter='Real Application Testing';

PARAMETER                                                        VALUE
---------------------------------------------------------------- ----------------------------------------------------------------
Real Application Testing                                         TRUE



To disable a certain option:-
SQL> select * from v$option where value ='TRUE';

PARAMETER                                                        VALUE
---------------------------------------------------------------- ----------------------------------------------------------------
Partitioning                                                     TRUE
Objects                                                          TRUE
Advanced replication                                             TRUE
Bit-mapped indexes                                               TRUE
Connection multiplexing                                          TRUE
Connection pooling                                               TRUE
Database queuing                                                 TRUE
Incremental backup and recovery                                  TRUE
Instead-of triggers                                              TRUE
Parallel backup and recovery                                     TRUE
Parallel execution                                               TRUE

Here lets disable Partitioning in our database

Step 1:-
So, Stop the database, Database Control console process, and listener.

[oracle@configsrv2 ~]$ lsnrctl stop
[oracle@configsrv2 ~]$ emctl stop dbconsole
SQL> shut immediate;
Database closed.
Database dismounted.
ORACLE instance shut down.

Step 2:-
[oracle@configsrv2 ~]$ cd $ORACLE_HOME/rdbms/lib
[oracle@configsrv2 ~]$ make -f ins_rdbms.mk part_off ioracle
After hitting the above command it would take some time as this would enable the Partitioning option for the database.

Step 3:-
Once the execution of the above command is done ; we need to start the database, listener and Database Control console process.
[oracle@configsrv2 ~]$ lsnrctl start
SQL> startup
SQL> select * from v$option where parameter='Partitioning';

PARAMETER                                                        VALUE
---------------------------------------------------------------- ----------------------------------------------------------------
Partitioning                                                     FALSE

So we can see the option Partitioning has been disabled for the database.


Here is the list of database options and switches:
Database Option                    ON            OFF
Data Mining                        dm_on        dm_off
Data Mining Scoring Engine        dmse_on        dmse_off
Database Vault                    dv_on        dv_off
Label Security                    bac_on        lbac_off
Partitioning                    part_on        part_off
Real Application Clusters        rac_on        rac_off
Spatial    s                        do_on        sdo_off
Real Application Testing        rat_on        rat_off
OLAP                            olap_on        olap_off
Automatic Storage Management    asm_on        asm_off
Context Management Text            ctx_on        ctx_off




Please share your ideas and opinions about this topic.

If you like this post, then please share with others.
Please subscribe on email for every updates on mail.

Install PostgreSQL on RHEL 6.4


OS Version: Rhel 6.4
PostgreSQL Version:- 9.4

Step 1:-Download the repository
yum install http://yum.postgresql.org/9.4/redhat/rhel-6-x86_64/pgdg-centos94-9.4-1.noarch.rpm

vi /etc/yum.repos.d/centos.repo
add the following lines
[centos-6-base]
name=CentOS-$releasever - Base
mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=os
baseurl=http://mirror.centos.org/centos/$releasever/os/$basearch/
enabled=1


step 2:- Install Postgresql required packages:-
#yum install postgresql94-server postgresql94-contrib
Incase if the above command gives error regarding the public key, we can use the following command
cd /etc/pki/rpm-gpg
rpm --import RPM-GPG-KEY-CentOS-6

#yum install postgresql94-server

# service postgresql-9.4 initdb
or
# service postgresql initdb

# chkconfig postgresql-9.4 on

Step 3:-Start postgresql:-
[root@infosystem ~]# service postgresql-9.4 start
Starting postgresql service: [  OK  ]

Check status of postgresql:-
[root@infosystem ~]# service postgresql status
postmaster (pid  4260) is running...

Step 4:- Log into postgre
#su - postgres
$ psql

To create a  user:-
postgres=# CREATE USER soumya WITH password 'redhat';
CREATE ROLE

To check  version:-
SELECT version ();

To change postgres password:-
postgres=# \password postgres
Enter new password:
Enter it again:

To create a table:-
postgres=#CREATE TABLE COMPANY(
   ID INT PRIMARY KEY     NOT NULL,
   NAME           TEXT    NOT NULL,
   AGE            INT     NOT NULL,
   ADDRESS        CHAR(50),
   SALARY         REAL
);

To view created tables:-
postgres=#\d

                  List of relations
 Schema |          Name          |   Type   |  Owner
--------+------------------------+----------+----------
 public | article                | table    | postgres
 public | article_article_id_seq | sequence | postgres
 public | company                | table    | postgres
 public | department             | table    | postgres
(4 rows)


To create a database:-
postgres=#  CREATE DATABASE mydb WITH OWNER soumya;
CREATE DATABASE

To see all databases:-

postgres=# \l
List of databases
   Name    |  Owner   | Encoding |  Collation  |    Ctype    |   Access privileges
-----------+----------+----------+-------------+-------------+-----------------------
 mydb      | ramesh   | UTF8     | en_US.UTF-8 | en_US.UTF-8 |
 mydb1     | soumya   | UTF8     | en_US.UTF-8 | en_US.UTF-8 |
 postgres  | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 |
 template0 | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres
                                                             : postgres=CTc/postgres
 template1 | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres
                                                             : postgres=CTc/postgres

To drop a database:-
postgres=# drop database mydb;
DROP DATABASE

To backup all database:-
pg_dumpall > all.sql

To verify the backup:-
bash-4.1$ grep "^[\]connect" all.sql
\connect postgres
\connect mydb1
\connect postgres
\connect template1

To create a table under a schema:-
create schema soumya;
set search_path to soumya;
create table foo (id int);

To backup a particular db:-
pg_dump kmi > kmi.sql[mydb1 is db name for  which i'm taking the backup]

SELECT * FROM pg_stat_activity WHERE datname='mydb1';


Restore all the postgres databases

$ psql -f alldb.sql

Restore a single postgres table:-

$ psql -f kmi.sql kmi



Please share your ideas and opinions about this topic.

If you like this post, then please share with others.
Please subscribe on email for every updates on mail.

AWS AMI Backup shell script

Prerequisites:
=============

Step: 1. Install Java :

# yum -y install java-1.7.0-openjdk
# export JAVA_HOME=/usr/lib/jvm/jre-1.7.0-openjdk.x86_64
# java -version

Step: 2. Download & Unzip Amazon EC2 CLI Tools :

# yum -y install wget zip unzip
# cd /tmp
# wget http://s3.amazonaws.com/ec2-downloads/ec2-api-tools.zip
# unzip ec2-api-tools.zip

Step: 3. Install the Amazon EC2 CLI Tools :

# mkdir /usr/local/ec2
# mv ec2-api-tools-1.7.5.0 /usr/local/ec2/apitools/

Step: 4. Set variables :

# export EC2_HOME=/usr/local/ec2/apitools
# export PATH=$PATH:$EC2_HOME/bin

Step: 5. Add variables to Startup Script :

# cd etc/profile.d/
# vi aws.sh

export JAVA_HOME=/usr/lib/jvm/jre-1.7.0-openjdk.x86_64
export EC2_HOME=/usr/local/ec2/apitools
export PATH=$PATH:$EC2_HOME/bin

-- Save & Quit (:wq)

# chmod +x aws.sh
# sounce aws.sh

Step: 6. Logged in into AWS Web Panel.

Step: 7. Go to IAM Panel.

-- Click on Users (tab)
-- Create New Users.
-- Give User Name.
-- Click on Create.
-- Download the Credential.
-- Close.
-- Click on Newly Created User.
-- Permission (tab)
-- Click on Attach Policy.
-- Search (AmazonEC2FullAccess) & Select it.
-- Attach Policy.

Access Key ID:  Provide your Access Key Id
Secret Access Key:  Provide your Secret Access Key

Step: 8. Finally Create AMI Auto Backup Script :

# vi /backups/scripts/aws-ami-backup.sh

#!/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/ec2/apitools/bin

# Please use env | grep EC2_HOME to find out your system's setting
EC2_HOME=/usr/local/ec2/apitools

# Please use env | grep JAVA_HOME to find out your system's setting
JAVA_HOME=/usr/lib/jvm/jre-1.7.0-openjdk.x86_64
date=`date +%d-%m-%Y_%H-%M-%S`
export EC2_HOME JAVA_HOME
export AWS_ACCESS_KEY=Provide your Access Key Id
export AWS_SECRET_KEY=Provide your Secret Access Key

# Regions reference: http://docs.aws.amazon.com/general/latest/gr/rande.html
region="ap-southeast-1"

# You can find your instance ID at AWS Manage Console
instanceID="i-c706e305"

# Your prefer AMI Name prefix
amiNamePrefix="SOUMYA-SOUMYATEST-AMI_$date"

# Your prefer AMI Description

amiDescription="Daily AMI backup"

# If you want to keep 7 days AMI backups, please set routine true otherwise set it false
routine=true

if [ $routine = true ]; then
    # Setup AMI Name
    amiName=$amiNamePrefix

    # Get AMI ID
    amiIDs=$(ec2-describe-images --region $region | grep 'ami-[a-z0-9]' | grep "$amiName" |cut -f 2)

    # Get Snapshot ID
    if [[ ! -z $amiIDs ]]; then
        snapshotIDs=$(ec2-describe-snapshots --region $region | grep $amiIDs | cut -f 2)
    fi
else
    # Setup AMI Name
    amiName=$amiNamePrefix

    # Get AMI ID
    amiIDs=$(ec2-describe-images --region $region | grep 'ami-[a-z0-9]' | cut -f 2)

    # Get Snapshot ID
    if [[ ! -z $amiIDs ]]; then
        snapshotIDs=$(ec2-describe-snapshots --region $region | cut -f 2)
    fi
fi

if [[ ! -z $amiIDs ]]; then
    # Deregister AMI
    for amiID in $amiIDs
    do
        ec2-deregister --region $region $amiID
    done

    # Delete snapshot
    for snapshotID in $snapshotIDs
    do
        ec2-delete-snapshot --region $region $snapshotID
    done
fi

# Create AMI
ec2-create-image $instanceID --region $region --name "$amiName" -d "$amiDescription" --no-reboot > /tmp/AMIBackup.txt

# Name Tag
amiid=`cat /tmp/AMIBackup.txt | cut -f2`
ec2addtag $amiid --tag Name=$amiName --region $region

-- Save & Quit (:wq)

# chmod 755 /backups/scripts/aws-ami-backup.sh

Step: 9. Schedule in Crontab :

# crontab -e

0 0 * * * /backups/scripts/aws-ami-backup.sh

-- Save & Quit (:wq)

Step: 10. Retstart the Cron Service :

# service crond restart

Done...!!!




Please share your ideas and opinions about this topic.

If you like this post, then please share with others.
Please subscribe on email for every updates on mail.

Migrating SQL Users from one SQL Server To Another SQL Server Instance

Migraing SQL Users from one SQL Server To Another SQL Server Instance
=============================================================

Here i am Migrating User "soumya" from one SQL Server to Another SQL Server.

On Source Database:

-- Logged in as sa/system User
-- Expand Databases
-- Expand System Databases
-- Right click on master database
-- New Query.
-- Paste the below lines & Click Execute.

USE master
GO
IF OBJECT_ID ('sp_hexadecimal') IS NOT NULL
  DROP PROCEDURE sp_hexadecimal
GO
CREATE PROCEDURE sp_hexadecimal
    @binvalue varbinary(256),
    @hexvalue varchar (514) OUTPUT
AS
DECLARE @charvalue varchar (514)
DECLARE @i int
DECLARE @length int
DECLARE @hexstring char(16)
SELECT @charvalue = '0x'
SELECT @i = 1
SELECT @length = DATALENGTH (@binvalue)
SELECT @hexstring = '0123456789ABCDEF'
WHILE (@i <= @length)
BEGIN
  DECLARE @tempint int
  DECLARE @firstint int
  DECLARE @secondint int
  SELECT @tempint = CONVERT(int, SUBSTRING(@binvalue,@i,1))
  SELECT @firstint = FLOOR(@tempint/16)
  SELECT @secondint = @tempint - (@firstint*16)
  SELECT @charvalue = @charvalue +
    SUBSTRING(@hexstring, @firstint+1, 1) +
    SUBSTRING(@hexstring, @secondint+1, 1)
  SELECT @i = @i + 1
END

SELECT @hexvalue = @charvalue
GO

IF OBJECT_ID ('sp_help_revlogin') IS NOT NULL
  DROP PROCEDURE sp_help_revlogin
GO
CREATE PROCEDURE sp_help_revlogin @login_name sysname = NULL AS
DECLARE @name sysname
DECLARE @type varchar (1)
DECLARE @hasaccess int
DECLARE @denylogin int
DECLARE @is_disabled int
DECLARE @PWD_varbinary  varbinary (256)
DECLARE @PWD_string  varchar (514)
DECLARE @SID_varbinary varbinary (85)
DECLARE @SID_string varchar (514)
DECLARE @tmpstr  varchar (1024)
DECLARE @is_policy_checked varchar (3)
DECLARE @is_expiration_checked varchar (3)

DECLARE @defaultdb sysname

IF (@login_name IS NULL)
  DECLARE login_curs CURSOR FOR

      SELECT p.sid, p.name, p.type, p.is_disabled, p.default_database_name, l.hasaccess, l.denylogin FROM
sys.server_principals p LEFT JOIN sys.syslogins l
      ON ( l.name = p.name ) WHERE p.type IN ( 'S', 'G', 'U' ) AND p.name <> 'sa'
ELSE
  DECLARE login_curs CURSOR FOR


      SELECT p.sid, p.name, p.type, p.is_disabled, p.default_database_name, l.hasaccess, l.denylogin FROM
sys.server_principals p LEFT JOIN sys.syslogins l
      ON ( l.name = p.name ) WHERE p.type IN ( 'S', 'G', 'U' ) AND p.name = @login_name
OPEN login_curs

FETCH NEXT FROM login_curs INTO @SID_varbinary, @name, @type, @is_disabled, @defaultdb, @hasaccess, @denylogin
IF (@@fetch_status = -1)
BEGIN
  PRINT 'No login(s) found.'
  CLOSE login_curs
  DEALLOCATE login_curs
  RETURN -1
END
SET @tmpstr = '/* sp_help_revlogin script '
PRINT @tmpstr
SET @tmpstr = '** Generated ' + CONVERT (varchar, GETDATE()) + ' on ' + @@SERVERNAME + ' */'
PRINT @tmpstr
PRINT ''
WHILE (@@fetch_status <> -1)
BEGIN
  IF (@@fetch_status <> -2)
  BEGIN
    PRINT ''
    SET @tmpstr = '-- Login: ' + @name
    PRINT @tmpstr
    IF (@type IN ( 'G', 'U'))
    BEGIN -- NT authenticated account/group

      SET @tmpstr = 'CREATE LOGIN ' + QUOTENAME( @name ) + ' FROM WINDOWS WITH DEFAULT_DATABASE = [' + @defaultdb + ']'
    END
    ELSE BEGIN -- SQL Server authentication
        -- obtain password and sid
            SET @PWD_varbinary = CAST( LOGINPROPERTY( @name, 'PasswordHash' ) AS varbinary (256) )
        EXEC sp_hexadecimal @PWD_varbinary, @PWD_string OUT
        EXEC sp_hexadecimal @SID_varbinary,@SID_string OUT

        -- obtain password policy state
        SELECT @is_policy_checked = CASE is_policy_checked WHEN 1 THEN 'ON' WHEN 0 THEN 'OFF' ELSE NULL END FROM sys.sql_logins WHERE name = @name
        SELECT @is_expiration_checked = CASE is_expiration_checked WHEN 1 THEN 'ON' WHEN 0 THEN 'OFF' ELSE NULL END FROM sys.sql_logins WHERE name = @name

            SET @tmpstr = 'CREATE LOGIN ' + QUOTENAME( @name ) + ' WITH PASSWORD = ' + @PWD_string + ' HASHED, SID = ' + @SID_string + ', DEFAULT_DATABASE = [' + @defaultdb + ']'

        IF ( @is_policy_checked IS NOT NULL )
        BEGIN
          SET @tmpstr = @tmpstr + ', CHECK_POLICY = ' + @is_policy_checked
        END
        IF ( @is_expiration_checked IS NOT NULL )
        BEGIN
          SET @tmpstr = @tmpstr + ', CHECK_EXPIRATION = ' + @is_expiration_checked
        END
    END
    IF (@denylogin = 1)
    BEGIN -- login is denied access
      SET @tmpstr = @tmpstr + '; DENY CONNECT SQL TO ' + QUOTENAME( @name )
    END
    ELSE IF (@hasaccess = 0)
    BEGIN -- login exists but does not have access
      SET @tmpstr = @tmpstr + '; REVOKE CONNECT SQL TO ' + QUOTENAME( @name )
    END
    IF (@is_disabled = 1)
    BEGIN -- login is disabled
      SET @tmpstr = @tmpstr + '; ALTER LOGIN ' + QUOTENAME( @name ) + ' DISABLE'
    END
    PRINT @tmpstr
  END

  FETCH NEXT FROM login_curs INTO @SID_varbinary, @name, @type, @is_disabled, @defaultdb, @hasaccess, @denylogin
   END
CLOSE login_curs
DEALLOCATE login_curs
RETURN 0
GO

-- After Successfully Executed the Command.
-- Expand master database.
-- Expand Programmability.
-- Expand Stored Procedures.
-- Click New Query.
-- Drag & Drop "dbo.sp_help_revlogin" on New Query Box.
-- Finally Click on Execute.
-- Copy the User Information.
-- Go To Another SQL Server Instance.
-- Expand Databases.
-- Expand System Databases.
-- Right click on master database.
-- New Query.
-- Paste the User Information & Click on Execute.

-- Login: soumya
CREATE LOGIN [soumya] WITH PASSWORD = 0x0100C0256FC7444529ADF74C8E7275968871444D6C1CE4ACA9CE HASHED, SID = 0x895CC8F6C6C9FE4D9188EF23B80E625B, DEFAULT_DATABASE = [master], CHECK_POLICY = OFF, CHECK_EXPIRATION = OFF

Now in Destination server:-

Copy and Paste the above user creation tsql command to create the "soumya" user with its password:

CREATE LOGIN [soumya] WITH PASSWORD = 0x0100C0256FC7444529ADF74C8E7275968871444D6C1CE4ACA9CE HASHED, SID = 0x895CC8F6C6C9FE4D9188EF23B80E625B, DEFAULT_DATABASE = [master], CHECK_POLICY = OFF, CHECK_EXPIRATION = OFF

Done...!!!





Please share your ideas and opinions about this topic.

If you like this post, then please share with others.
Please subscribe on email for every updates on mail.

How to install MongoDB on RHEL 6

How to install MongoDB on RHEL 6:-

Os version _ Rhel 6.4
MongoDB Version:-2.6.7

Step:1 System Login as root user. We are checking system OS type and system bits type.

# uname –a
Linux server1.soumya.com 2.6.32-358.el6.x86_64 #1 SMP Tue Jan 29 11:47:41 EST 2013 x86_64 x86_64 x86_64 GNU/Linux

# cat /etc/issue
Red Hat Enterprise Linux Server release 6.4 (Santiago)
Kernel \r on an \m


Step:2 Now we are creating a yum repo file .like /etc/yum.repos.d/mongodb.repo

# vi /etc/yum.repos.d/mongodb.repo
[mongodb]
name=mongodb Repository
baseurl=http://downloads-distro.mongodb.org/repo/redhat/os/x86_64
gpgcheck=0
enabled=1

--save & exit(:wq)

Step:3 Now we install mongodb client and server using yum

# yum install mongo-*

If you face any error while installing the rpms do the following
# yum erase mongo*
yum shell
> install mongodb-org
> remove mongo-10gen
> remove mongo-10gen-server
> run

Step:4 Now we can configure and basic setting in Mongodb Database Server

# vi /etc/mongod.conf
logappend=true
logpath=logpath=/var/log/mongodb/mongod.log
port=27017
dbpath=/var/lib/mongo
smallfiles = true
:wq

Step:5 Start Mongodb Server

# /etc/init.d/mongod start
# chkconfig mongod on

Open another terminal and type
#mongo


Show all database:-
>show dbs

Define a database name as soumya:-
>use soumya

then to check your current db name:-
>db

To add the created db in dblist we need to add collection in this database.For instance, create a document in a customers collection like this:
db.customers.save({"firstName":"Alvin", "lastName":"Alexander"})

Next, verify that your document was created with this command:
db.customers.find()

Now check your db name:-
>show dbs

Now to add a new user in a db:-
>use pizza
>db.createUser( { user: "soumya",
              pwd: "redhat2",
              roles: [ "readWrite", "dbAdmin" ]
            } )

To check all the users in your current db:-
>show users
or
db.system.users.find()

To drop the database pizzas:-
use pizzas;
>db.dropDatabase()

To check current version:-
db.version()

Done..



Please share your ideas and opinions about this topic. If you like this post, then please share with others. Please subscribe on email for every updates on mail.

Related Posts Plugin for WordPress, Blogger...