[Oracle Database] - Oracle Database A->Z

December 22, 2018 |

Oracle Database Concept/Installation
Each database has a different concept and we should know that and it helps easy to organize, manage also easy to choose an accordant RMS  for your system.


Oracle Instance and database


 Database Storage Structure

* Physical Storage Structure:
 Data files > Control File > Online redo log file
- Data files: Oracle DB has one or more physical data files. 
- Control File: Contain metadata specifying the physical structure of the database included database name, the names, and location of the database file.
- Online redo log file: is made up of redo entries, which record all changes made to data. 


* Logical Storage Structure:
 Data blocks > Extents >  Segments > Tablespaces.
- Data blocks: data stored in data blocked. 1 data block correspond number byte on disk.
Extents:  An extent is a specific number of logically contiguous data blocks, obtained in a single allocation, used to store a specific type of information.
Segments: A segment is a set of extents allocated for a user object (for example, a table or index), undo data, or temporary data.
Tablespaces: A database is divided into logical storage units called tablespaces. A tablespace is a logical container for a segment. Each tablespace contains at least one data file.

Oracle Database 11c
* Data Type
+ Character
char(s), nchar(s)
varchar2(s), nvarchar2(s)

+ Number (p is the precision and s is the scale)
number(p,s): p = 1 to 38, s = -84 to 124

+BOOLEAN : NULL, TRUE, FALSE
<var1> BOOLEAN; //declare with null
<var2> BOOLEAN NOT NULL := TRUE;
<var3> BOOLEAN NOT NULL := FALSE;


Ex:

department_id number(10),
department_name varchar2(50) NOT NULL,

Ref: https://www.techonthenet.com/oracle/datatypes.php

========================================================================
INDEX
An index is an optional structure, associated with a table or table cluster, that can sometimes speed data access.

Create index:
CREATE INDEX <INDEX_NAME> ON <TABLE> (COLUMN1, COLUMN2,...);
Ex:
CREATE INDEX members_last_name_i
   ON members(last_name);

Type of Indexes

B-tree indexes

B-trees, short for balanced trees. B-tree index is an ordered list of values divided into ranges.
B-Tree has 2 types: Branch Blocks and Leaf Block.
- Branch Blocks: for searching
- Leaf Block: for store values.


========================================================================
 Source:
https://docs.oracle.com/cd/E11882_01/server.112/e40540/intro.htm#CNCPT914

========================================================================

Create Synonym

CREATE SYNONYM <NAME> ON FOR schema.object;
Ex:
User A has table Customer.
User B want to use Customer from User A:

No Synonym:
Select * from a.customer;

— create synonym for user B
CREATE SYNONYM customer FOR a.customer;

With Synonym:
Select * from customer;


DATE-TIME
TO_CHAR(datetime);

========================================================================

RMAN tool

The RMAN executable is automatically installed with the database and is typically located in the same directory as the other database executables. For example, the RMAN client on Linux is located in $ORACLE_HOME/bin.
 
Retention policy
RMAN > show all;
 
========================================================================

Other

1. Show table structure/columns
describe <table_name>; // in SQL Plus
DESC <table_name>;
2. Table space is full
sqlplus /as sysdba
alter tablespace USERS add datafile '+DATA' size 100M autoextend on;

3. Check and delete archivelog
// using rman target
rman target /

// check archivelog
crosscheck archivelog all;

// check backup log
crosscheck backupset;

//delete archivelog backup has expired.
delete expired backupset;

delete obsolete;

//delete archivelog has expired.
delete expired archivelog all;

delete archivelog all completed before ‘sysdate-7’;

//Check disk group
set lin 250 
col name format a10 
col USABLE_FILE_GB format 999,999.00 
col TOTAL_GB format 999,999.00 
col FREE_GB format 999,999.00 
col USABLE_CALC_GB format 999,999.00 


select name
     , USABLE_FILE_MB/1024 USABLE_FILE_GB
     , total_mb/1024 TOTAL_GB
     , free_mb/1024 FREE_GB
     , 100-round(free_mb/total_mb*100) "usgae(%)"
     , ((FREE_MB - REQUIRED_MIRROR_FREE_MB))/1024 USABLE_CALC_GB
     , state
     , type
     , group_number 
from v$asm_diskgroup; 

//Show Recovery Dest File
show parameter DB_RECOVERY_FILE_DEST_SIZE;

//alter Recovery Dest size
alter system set DB_RECOVERY_FILE_DEST_SIZE = 300G SCOPE=BOTH SID='*';

//Show RMAN backup job details
SELECT session_key, input_type, status, start_time, end_time, elapsed_seconds/3600 hrs
FROM v$rman_backup_job_details;


4. Check archive log by SQLPlus*
Ref:
// cd to <oracle_path>/bin
sqlplus /nolog

connect SYS as SYSDBA

//check log mode
select log_mode from v$database;

//check information of archivelog , see size, path of log.
archive log list;

// show archivelog
SQL> show parameter log_archive_dest;

// show recover
SQL> show parameter recovery;

//show archive log list
SQL> archive log list;

//show use db recovery file dest
SQL > show parameter db_recovery_file_dest;

// Find SPACE_USED, SPACE_LIMIT
SQL> select * from V$RECOVERY_FILE_DEST;
SQL> select NAME,SPACE_LIMIT/1024/1024 TOTAL_MB,SPACE_USED/1024/1024  USED_MB from v$RECOVERY_FILE_DEST;

//change archive log dest
SQL > alter system set LOG_ARCHIVE_DEST = 'location=/<path>'

//Specifying alternate destinations
SQL > 

//Check usage data or Archive log, 
SQL > SELECT * FROM V$RECOVERY_AREA_USAGE;



* Select limit data
Oracle: select * from table where rownum <= 2;
SQL Server: select top 200 * from table;
MySql: select * from table where condition limit 20;
2. ora-00937: not a single-group group function
Ex:
//ora-00937: not a single-group group function
SELECT CUS_NAME, MAX(AGE)
FROM CUSTOMER;

// CORRECT
SELECT CUS_NAME, MAX(AGE)
FROM CUSTOMER
GROUP BY CUS_NAME;

in Mysql, we can use without GROUP;



3. Turn on cache PL/SQL and ouput to Console
SQL> SET SERVEROUTPUT ON SIZE 10000000;
 
on script:
dbms_output.enable(1000000);
dbms_output.disable;
dbms_output.put('message'); // output message
dbms_output.new_line; // create new line
dbms_output.put_line('');  //output message with entered line.

4. Create user on oracle database
When you created a user, remember that username must be UPPERCASE. if it's not, you cannot login.
 

========================================================================

SQL

1.Compare between two date
Select *
From dual a
Where trunc(a.reg_dt) = trunc(current_date)

2. Check table space

#Check tablespace size

//MB
Select (sum(bytes)/1024/1024) Space_allocated
from dba_data_files
where tablespace_name=upper('&tname');

//GB
Select (sum(bytes)/1024/1024/1024) Space_allocated
from dba_data_files
where tablespace_name=upper('&tname');

3. RMAN tool

Back up log
RMAN> backup archivelog until time 'sysdate-2' delete input;

Crosscheck commands:
To crosscheck all backups use:
RMAN> CROSSCHECK BACKUP;

To list any expired backups detected by the CROSSCHECK command use:
RMAN> LIST EXPIRED BACKUP;

To delete any expired backups detected by the CROSSCHECK command use:
RMAN> DELETE EXPIRED BACKUP;

To crosscheck all archive logs use:
RMAN> CROSSCHECK ARCHIVELOG ALL;

To list all expired archive logs detected by the CROSSCHECK command use:
RMAN> LIST EXPIRED ARCHIVELOG ALL;

To delete all expired archive logs detected by the CROSSCHECK command use:
RMAN> DELETE EXPIRED ARCHIVELOG ALL;

To crosscheck all datafile image copies use:
RMAN> CROSSCHECK DATAFILECOPY ALL;

To list expired datafile copies use:
RMAN> LIST EXPIRED DATAFILECOPY ALL;

To delete expired datafile copies use:
RMAN> DELETE EXPIRED DATAFILECOPY ALL;

To crosscheck all backups of the USERS tablespace use:
RMAN> CROSSCHECK BACKUP OF TABLESPACE USERS;

To list expired backups of the USERS tablespace:
RMAN> LIST EXPIRED BACKUP OF TABLESPACE USERS;

To delete expired backups of the USERS tablespace:
RMAN> DELETE EXPIRED BACKUP OF TABLESPACE USERS;

4. ORA-01012: not logged on error
Ref: https://doyensys.com/blogs/ora-01012-not-logged-on-error/
$ sysresv  // get shared memory ID
$ipcrm -m <ID>
$sqlplus / as sysdba
$ startup // start up instance

5. Check account status of users

select username, account_status
from dba_users
where username = 'your_user_name';

Is updating...
Read more…

Command lines in Windows

September 11, 2018 |







Some cases, we can use command lines so that open tools, access system,... where we cannot open by GUI in windows or linux OS.

I. Command lines in Windows
1. Open Remote Desktop Connection
    Typing the flowing command line below:

C:\Users\<user_name>> mstsc

How to check port of Remote Desktop:
1. Open regedit
2. Go to Navigate to the following registry subkey: HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp
3. find PortNumber
4. You can edit port and restart Remote Desktop Services.

2. Open Microsoft SQL Server Management Studio
    Typing the flowing command line below:


C:\Users\<user_name>> ssms



3. Open other command line window with administator user.
    Typing the flowing command line below:

C:\Users\<user_name>> runas /user:Administrator cmd
and then enter password.
4. Restart a Windows service

net stop workstation

net start workstation

With the command line, we can resolve the issue:
"Multiple connections to a server or shared resource by the same user, using more than one user name, are not allowed".

5. "Netstat" command line.
Netstart command is used show TCP/IP port in windows. We can use for check port which program is using or not.

Displays protocol statistics and current TCP/IP network connections.

NETSTAT [-a] [-b] [-e] [-f] [-n] [-o] [-p proto] [-r] [-s] [-t] [interval]

  -a            Displays all connections and listening ports.
  -b            Displays the executable involved in creating each connection or
                listening port. In some cases well-known executables host
                multiple independent components, and in these cases the
                sequence of components involved in creating the connection
                or listening port is displayed. In this case the executable
                name is in [] at the bottom, on top is the component it called,
                and so forth until TCP/IP was reached. Note that this option
                can be time-consuming and will fail unless you have sufficient
                permissions.
  -e            Displays Ethernet statistics. This may be combined with the -s
                option.
  -f            Displays Fully Qualified Domain Names (FQDN) for foreign
                addresses.
  -n            Displays addresses and port numbers in numerical form.
  -o            Displays the owning process ID associated with each connection.
  -p proto      Shows connections for the protocol specified by proto; proto
                may be any of: TCP, UDP, TCPv6, or UDPv6.  If used with the -s
                option to display per-protocol statistics, proto may be any of:
                IP, IPv6, ICMP, ICMPv6, TCP, TCPv6, UDP, or UDPv6.
  -r            Displays the routing table.
  -s            Displays per-protocol statistics.  By default, statistics are
                shown for IP, IPv6, ICMP, ICMPv6, TCP, TCPv6, UDP, and UDPv6;
                the -p option may be used to specify a subset of the default.
  -t            Displays the current connection offload state.
  interval      Redisplays selected statistics, pausing interval seconds
                between each display.  Press CTRL+C to stop redisplaying
                statistics.  If omitted, netstat will print the current
                configuration information once.
Example:
netstat -ab
netstat -aon

6. "TaskList" command line
TaskList is show task is runing in windows as Task Manager.
 ========================================
c:\>tasklist /?

TASKLIST [/S system [/U username [/P [password]]]]
         [/M [module] | /SVC | /V] [/FI filter] [/FO format] [/NH]

Description:
    This tool displays a list of currently running processes on
    either a local or remote machine.

Parameter List:
   /S     system           Specifies the remote system to connect to.

   /U     [domain\]user    Specifies the user context under which
                           the command should execute.

   /P     [password]       Specifies the password for the given
                           user context. Prompts for input if omitted.

   /M     [module]         Lists all tasks currently using the given
                           exe/dll name. If the module name is not
                           specified all loaded modules are displayed.

   /SVC                    Displays services hosted in each process.

   /V                      Displays verbose task information.

   /FI    filter           Displays a set of tasks that match a
                           given criteria specified by the filter.

   /FO    format           Specifies the output format.
                           Valid values: "TABLE", "LIST", "CSV".

   /NH                     Specifies that the "Column Header" should
                           not be displayed in the output.
                           Valid only for "TABLE" and "CSV" formats.

   /?                      Displays this help message.

Filters:
    Filter Name     Valid Operators           Valid Value(s)
    -----------     ---------------           --------------------------
    STATUS          eq, ne                    RUNNING |
                                              NOT RESPONDING | UNKNOWN
    IMAGENAME       eq, ne                    Image name
    PID             eq, ne, gt, lt, ge, le    PID value
    SESSION         eq, ne, gt, lt, ge, le    Session number
    SESSIONNAME     eq, ne                    Session name
    CPUTIME         eq, ne, gt, lt, ge, le    CPU time in the format
                                              of hh:mm:ss.
                                              hh - hours,
                                              mm - minutes, ss - seconds
    MEMUSAGE        eq, ne, gt, lt, ge, le    Memory usage in KB
    USERNAME        eq, ne                    User name in [domain\]user
                                              format
    SERVICES        eq, ne                    Service name
    WINDOWTITLE     eq, ne                    Window title
    MODULES         eq, ne                    DLL name

NOTE: "WINDOWTITLE" and "STATUS" filters are not supported when querying
      a remote machine.

Examples:
    TASKLIST
    TASKLIST /M
    TASKLIST /V /FO CSV
    TASKLIST /SVC /FO LIST
    TASKLIST /M wbem*
    TASKLIST /S system /FO LIST
    TASKLIST /S system /U domain\username /FO CSV /NH
    TASKLIST /S system /U username /P password /FO TABLE /NH
    TASKLIST /FI "USERNAME ne NT AUTHORITY\SYSTEM" /FI "STATUS eq running""
=======================================
 Example:
c:\>tasklist

Image Name                     PID Session Name        Session#    Mem Usage
========================= ======== ================ =========== ============
System Idle Process              0 Services                   0         24 K
System                           4 Services                   0        964 K
smss.exe                       356 Services                   0      1,240 K
csrss.exe                      472 Services                   0      5,368 K
wininit.exe                    544 Services                   0      4,836 K
csrss.exe                      552 Console                    1     12,436 K
services.exe                   600 Services                   0     10,428 K
lsass.exe                      616 Services                   0     14,536 K
lsm.exe                        624 Services                   0      6,344 K
winlogon.exe                   684 Console                    1      6,968 K
svchost.exe                    768 Services                   0      9,468 K
nvvsvc.exe                     848 Services                   0      7,308 K
nvSCPAPISvr.exe                872 Services                   0      5,792 K


7. "Taskkill" command line.
TaskKill is used to kill a program is runing. We can kill follow by PID or program name.

TASKKILL [/S system [/U username [/P [password]]]]
         { [/FI filter] [/PID processid | /IM imagename] } [/T] [/F]

Description:
    This tool is used to terminate tasks by process id (PID) or image name.

Parameter List:

    /S    system           Specifies the remote system to connect to.

    /U    [domain\]user    Specifies the user context under which the
                           command should execute.

    /P    [password]       Specifies the password for the given user
                           context. Prompts for input if omitted.

    /FI   filter           Applies a filter to select a set of tasks.
                           Allows "*" to be used. ex. imagename eq acme*

    /PID  processid        Specifies the PID of the process to be terminated.
                           Use TaskList to get the PID.

    /IM   imagename        Specifies the image name of the process
                           to be terminated. Wildcard '*' can be used
                           to specify all tasks or image names.

    /T                     Terminates the specified process and any
                           child processes which were started by it.

    /F                     Specifies to forcefully terminate the process(es).

    /?                     Displays this help message.

Filters:
    Filter Name   Valid Operators           Valid Value(s)
    -----------   ---------------           -------------------------
    STATUS        eq, ne                    RUNNING |
                                            NOT RESPONDING | UNKNOWN
    IMAGENAME     eq, ne                    Image name
    PID           eq, ne, gt, lt, ge, le    PID value
    SESSION       eq, ne, gt, lt, ge, le    Session number.
    CPUTIME       eq, ne, gt, lt, ge, le    CPU time in the format
                                            of hh:mm:ss.
                                            hh - hours,
                                            mm - minutes, ss - seconds
    MEMUSAGE      eq, ne, gt, lt, ge, le    Memory usage in KB
    USERNAME      eq, ne                    User name in [domain\]user
                                            format
    MODULES       eq, ne                    DLL name
    SERVICES      eq, ne                    Service name
    WINDOWTITLE   eq, ne                    Window title

    NOTE
    ----
    1) Wildcard '*' for /IM switch is accepted only when a filter is applied.
    2) Termination of remote processes will always be done forcefully (/F).
    3) "WINDOWTITLE" and "STATUS" filters are not considered when a remote
       machine is specified.

Examples:
    TASKKILL /IM notepad.exe
    TASKKILL /PID 1230 /PID 1241 /PID 1253 /T
    TASKKILL /F /IM cmd.exe /T
    TASKKILL /F /FI "PID ge 1000" /FI "WINDOWTITLE ne untitle*"
    TASKKILL /F /FI "USERNAME eq NT AUTHORITY\SYSTEM" /IM notepad.exe
    TASKKILL /S system /U domain\username /FI "USERNAME ne NT*" /IM *
    TASKKILL /S system /U username /P password /FI "IMAGENAME eq note*"

8. Set IP V4
netsh interface ipv4 set address name="Wi-Fi" static <IP> 255.255.255.0 <DEFAULT_GATE_WAY>
netsh interface ipv4 set dns name="Wi-Fi" static 8.8.8.8
netsh interface ipv4 set dns name="Wi-Fi" static 8.8.4.4 index=2


9. Add user Logon Service
To add "Log on as a service" permissions:
- Run Start > Control Panel > Administrative Tools > Local Security Policy
- Select  Local Policies > User Rights Assignment > Log on as a service
Click Add User or Group, and then add the appropriate account to the list of accounts that possess the Log on as a service right.

10. Check Share in Windows
$ net share
Share name   Resource                        Remark

-------------------------------------------------------------------------------
C$           C:\                             Default share
D$           D:\                             Default share
IPC$                                         Remote IPC
ADMIN$       C:\Windows                      Remote Admin
The command completed successfully.

11. Disable/Enable copy/past clipboard


1. Run the Local Group Policy Editor: gpedit.msc
2. Go to Computer Configuration -> Administrative Templates -> Windows Components -> Remote Desktop Services -> Remote Desktop Session Host -> Device and Resource Redirection;

12. Enable telnet client by cmd
$ dism /online /Disable-Feature /FeatureName:TelnetClient
$ dism /online /Enable-Feature /FeatureName:TelnetClient
13. Bypass Windows 11 Requirement check

1. Enter Shift + F10 
2. Enter regedit
3. Go to HEKY_LOCAL_MACHINE\SYSTEM\Setup
4. Created folder "LabConfig"
5. Create D-word 32 byte key : BypassTPMCheck > set value 1
    Create D-word 32 byte key : BypassSecureBootCheck> set value 1


14. How to enable enable nested vtx/amd-v in Virtual Box.
- Go to virtualbox installation folder
- VBoxManage modifyvm <VirtualMachineName> --nested-hw-virt on

15. Tail of log
Windows powershell
Get-Content <file> -Wait

16. Recovering USB when you install bootable linux 
Open windows cmd by administrator
$ diskpart
$ list disk
$ select disk <N>
$ clean

=> Go to Disk Management in Windows and set path and format it.

17. Merge multiple files  in windows
$ copy /b file1.txt +file2.txt final_file.txt
$ copy /b *.txt final-text.txt

18. Virtual box command line
//Convert Virtual Box format to Hyper-V format
$ VBoxManage clonehd "E:\HoQuocTri\Backup\1.VM Backup\20241028\CentOS8-VCARE-Services-disk001.vmdk" "E:\Tools\Hyper-V\viCare-Services\CentOS8-VCARE-Services-disk001.vhd" --format VHD

19. Config VPN L2TP behind NAT
$ Run > regedit
$ Change Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\PolicyAgent
AssumeUDPEncapsulationContextOnSendRule = 2
$ Restart Computer
Note: Rember update windows after changed. It need update .Net




Read more…

[Database] - UPDATE STATISTICS for all SQL Server Databases

July 14, 2018 |


Run update statistics for SQL Server database.
Step 1: Run following the SQL script below:
DECLARE @SQL VARCHAR(1000DECLARE @DB sysname 
DECLARE curDB CURSOR FORWARD_ONLY STATIC FOR 
   SELECT 
[name] 
   
FROM master..sysdatabases
   
WHERE [name] NOT IN ('model''tempdb')
   
ORDER BY [name]
    
OPEN curDB  FETCH NEXT FROM curDB INTO @DB  WHILE @@FETCH_STATUS 
   
BEGIN 
       SELECT 
@SQL 'USE [' @DB +']' CHAR(13) + 'EXEC sp_updatestats' CHAR(13
       
PRINT @SQL 
       
FETCH NEXT FROM curDB INTO @DB 
   
END 
   
CLOSE 
curDB  DEALLOCATE 
curDB


Results:
USE [Dummy] EXEC sp_UpdateStats
USE [master] EXEC sp_UpdateStats
USE [msdb] EXEC sp_UpdateStats
USE [MSSQLTips] EXEC sp_UpdateStats
USE [MSSQLTips_DUPE] EXEC sp_UpdateStats
USE [Northwind] EXEC sp_UpdateStats
USE [Sitka] EXEC sp_UpdateStats
USE [Utility] EXEC 
sp_UpdateStats


Step 2: Copy and run database which you want to update statistics.

If you want to know how to use run update statistic alse problem and solution, please access to link below:

The article use source from: https://www.mssqltips.com/sqlservertip/1606/execute-update-statistics-for-all-sql-server-databases/

Read more…

[Java] - Encode/Decode Base64 String

July 14, 2018 |


I. Encode image to base64 string
 Convert an image to base64 string so that send via SOAP Message, RESTFul or save to database.

Codes:
 public String encodeToString(BufferedImage image, String type) {
        String imageString = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        try {
            ImageIO.write(image, type, bos);
            byte[] imageBytes = bos.toByteArray();

            BASE64Encoder encoder = new BASE64Encoder();
            imageString = encoder.encode(imageBytes);

            //imageString = Base64.getEncoder().encodeToString(imageBytes);

            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return imageString;
    }


II. Decode base64 string to image
 Decode base64 sring to image so that display on UI or other.

Codes:
 private BufferedImage decodeToImage(String imageString) {
        BufferedImage image = null;
        byte[] imageByte;
        try {
            BASE64Decoder decoder = new BASE64Decoder();
            imageByte = decoder.decodeBuffer(imageString);

            //imageByte = Base64.getDecoder().decode(imageString);
            ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
            image = ImageIO.read(bis);
            bis.close();
        } catch (Exception e) {
            LOGGER.err(e.toString());
            return null;
        }
      
        return image;
    }


Updating...
Read more…

[SQL] - Aggregate SQL Server

May 25, 2018 |

This article just note the SQL script in the work progress.

1. Drop INDEX
* SQL Server
-- Check a index is existing or not before drop it.
IF EXISTS (SELECT * FROM sys.indexes WHERE  object_id = OBJECT_ID(N'<table_name') AND name = N'<index_name>'))
    DROP INDEX <index_name> ON <table_name>

2. Drop TABLE
* SQL Server 
-- check a table is existing or not before drop it.
IF EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'table_name'))
    DROP TABLE <table_name>

3. Drop COLUMN
* SQL Server 
-- drop a column if its doesn't has any contraint.
IF EXISTS (Select 1 From sys.columns Where name = '<column_name>' And object_id = OBJECT_ID('<table_name>'))
BEGIN
  ALTER TABLE <table_name> DROP COLUMN <column_name>;
END

-- drop a column if its has contraints.
IF EXISTS (Select 1 From sys.columns Where name = '<column_name>' And object_id = OBJECT_ID('<table_name>'))
BEGIN
  DECLARE @def varchar(256);
  SELECT @def = name FROM sys.default_constraints WHERE parent_object_id = OBJECT_ID('<table_name>') AND COL_NAME(parent_object_id, parent_column_id) = '<column_name>';

  if @def is not null
  EXEC('ALTER TABLE <table_name> DROP CONSTRAINT ' + @def);

  ALTER TABLE <table_name> DROP COLUMN <column_name>;
END


4. Drop CONSTRAINT
* SQL Server 
--drop a contraint
ALTER TABLE <table_name> DROP CONSTRAINT <constraint_name>

-- Check a column is contraint on a table. If its exist, drop and create contraint.
IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS C JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS K
ON C.TABLE_NAME = K.TABLE_NAME AND C.CONSTRAINT_CATALOG = K.CONSTRAINT_CATALOG AND C.CONSTRAINT_SCHEMA = K.CONSTRAINT_SCHEMA
AND C.CONSTRAINT_NAME = K.CONSTRAINT_NAME WHERE C.CONSTRAINT_TYPE = 'PRIMARY KEY' AND K.COLUMN_NAME = '<column_name>'
and K.TABLE_NAME = '<table_name>')
BEGIN
    declare @pkey varchar(50);
    SELECT top 1 @pkey=c.CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS C JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS K
    ON C.TABLE_NAME = K.TABLE_NAME AND C.CONSTRAINT_CATALOG = K.CONSTRAINT_CATALOG AND C.CONSTRAINT_SCHEMA = K.CONSTRAINT_SCHEMA
    AND C.CONSTRAINT_NAME = K.CONSTRAINT_NAME WHERE C.CONSTRAINT_TYPE = 'PRIMARY KEY' and K.TABLE_NAME = '<table_name>'

    if(@pkey is not null)
        exec('ALTER TABLE <table_name> DROP CONSTRAINT ' + @pkey);
    else
        set @pkey='pk_<table_name>';

    exec('ALTER TABLE <table_name> ADD CONSTRAINT ' + @pkey + ' PRIMARY KEY CLUSTERED (column_name_1, column_name_2,.., column_name_n) WITH (FILLFACTOR = 80)');
END

-- rename column_1 to column_2 and make them a part of primary key
IF EXISTS (SELECT 1 FROM sys.columns WHERE name = 'column_1' AND object_id = OBJECT_ID('table_1'))
BEGIN
  DECLARE @pk_name varchar(300);
  SELECT @pk_name = name FROM sysobjects WHERE xtype = 'PK' AND parent_obj = (object_id('table_1'));

  if @pk_name is not null
    exec('ALTER TABLE table_1 DROP CONSTRAINT ' + @pk_name);
  else
    SET @pk_name='pk_table_1';
 
  EXEC sp_rename 'table_1.column_1', 'column_2', 'COLUMN';
 
  exec('ALTER TABLE table_1 ADD CONSTRAINT ' + @pk_name + ' PRIMARY KEY CLUSTERED (column_1, column_2,..., column_n) WITH (FILLFACTOR = 80)');
END




Updating...
Read more…

[Tools] - Java VisualVM

May 12, 2018 |



Java VisualVM help us monitor resource in Java Application as show performance.
To open Java VisualVM, following the step below:

1. Go to C:\Program Files\Java\<jdk version>\bin (Java JDK 64bit )or C:\Program Files (x86)\Java\<jdk version>\bin (Java JDK x86).
Note: This tool avaible from JDK 8 or older, JDK 9 is not avaible.
2. Find and open jvisualvm.exe
3. The Java VisualJM window display

Java VisualVM


+ From Application tab > Local: Show Java Applications are running.
Note: If you open Java VisualVM with current JDK version, there are only show the Java Applications that are running on this JDK.
+ Monitor: The Java VisualVM show the resources which the Java apps is used as memory, CPU, Network,...
+ Sampler tab (Useful): The Java VisualVM take a sampler about the resources of Java App. You can use take performance your app. You will be known exactly the java classes are taken performance.
Read more…

[Java Design Pattern] [Creational Pattern] - Factory Method

May 09, 2018 |
Creational Pattern - Factory Method Pattern
Purpose: The Factory Method Pattern gives us a way encapsulate the instancetiation of concrete types. Instead you delcare new direct object, you use Factory class to create a new object.

Factory Method concept UML. (Source: Software Architecture Design Patterns in Java.pdf)





Example 1:


IVehicle
package com.designpattern.creational.factorymethod;

public interface IVehicle {
    void run();
}

Vehicle
package com.designpattern.creational.factorymethod;

public class Vehicle implements IVehicle {
   
    private String color;
   
    @Override
    public void run() {
        System.out.println("Not Run");
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }
}

Bike
package com.designpattern.creational.factorymethod;

public class Bike extends Vehicle {
   
    @Override
    public void run() {
        // TODO Auto-generated method stub
        System.out.println("Bike is running...");
    }

}

Car
package com.designpattern.creational.factorymethod;

public class Car extends Vehicle {

    @Override
    public void run() {
        // TODO Auto-generated method stub
        System.out.println("Car is running...");
    }
}

Motobike

package com.designpattern.creational.factorymethod;

public class Motobike extends Vehicle {
   
    @Override
    public void run() {
        // TODO Auto-generated method stub
        System.out.println("Motobike is running...");
    }
}

VechicleFactory
package com.designpattern.creational.factorymethod;

public class VehicleFactory {

    public static Vehicle createVehicle(String s) {
        Vehicle vehicle = null;
       
        if ("bike".equals(s)) {
            vehicle = new Bike();
        } else if ("motobike".equals(s)) {
            vehicle = new Motobike();
        } else if ("car".equals(s)) {
            vehicle = new Car();
        } else {
            vehicle = new Vehicle();
        }

        return vehicle;

    }
}

VehicleMain
package com.designpattern.creational.factorymethod;

public class VehicleMain {
    public static void main(String[] args) {
        Vehicle bike =   VehicleFactory.createVehicle("bike");
        bike.run();
      
        Vehicle motobike = VehicleFactory.createVehicle("motobike");
        motobike.run();
      
        Vehicle car = VehicleFactory.createVehicle("car");
        car.run();

    }
}

Result:
Bike is running...
Motobike is running...
Car is running...



Read more…

[English] - Possessive adjective, Possessive Pronoun, Possessive Case.

April 28, 2018 |
 Ref: https://elight.edu.vn/tinh-tu-so-huu
I. Overview

Pronoun
Possessive Adj
Possessive Pronoun
I
My
Mine
You
Your
Your
He
His
His
She
Her
Hers
It
Its
Its
We
Our
Ours
They
Their
Theirs





 II. Possessive Case 
 1. 's or s'
      's: cho một chủ sở hữu
      s': cho nhiều sỡ hữu.

updating...
Read more…