Adsense

Showing posts with label command. Show all posts
Showing posts with label command. Show all posts

Sunday, November 30, 2014

How to display the number of rows affected in DB2 INSERT / DELETE / UPDATE / MERGE commands

 By default, DB2 does not print the number of records affected when we run the DML  commands like INSERT,  DELETE, UPDATE or MERGE in the command prompt. So to display number of records affected when you run the above DML commands, you can use  following options.

You  can use the option m, in the command itself as given below

db2 -m update employee set payscale='42000-3%-72000' where doj<='1976-01-01'
  Number of rows affected : 50
DB20000I  The SQL command completed successfully.


Also, You can use the below db2set command to set the command options "m" permanently for all instances and databases,


db2set DB2OPTIONS=-m

db2stop

db2start




Or you can update the options m to ON  permanently using the update command options.

db2 update command options using m ON

            In windows, if you may get the  below error OR your changes done to the command option may not be  retained when you run the above command,

error :   db2 update command options using m ON SQL0104N  An unexpected token "m" was found following "USING".  Expected tokens may include:  "A".  SQLSTATE=42601. Solution will be

Just go to db2 prompt.

db2=> update command options using m ON

You can cehck the command options using the below command

list command options


db2 => delete from Employee where emp_code='E1022'
  Number of rows affected : 1
DB20000I  The SQL command completed successfully.



Saturday, November 15, 2014

DB2 Gui Tools and Commands to start GUI tools

DB2 Universal Database (UDB) has many graphical tools that make the DBA’s database management job easier and it improves the productivity of the developer in application development. The following are the Gui Tools available in DB2 UDB. 1. Control Center , 2. Command Center , 3. Configuration Assistance , 4. Health Center, 5. Task Center , 6. Development Center , 7. Journal , 8. Memory Visualizer , 9. Information Center , 10. Replication Center

Now We are going to the use of db2 gui tools and how to invoke these Tools
All the GUI tools can be run through Control Center. It is better to invoke the GUI tools directly from the command line. 

1. Control Center : Using the Control Center, We can perform administrative tasks, monitor systems, and develop applications.This is the Master of all DB2 graphical tools We can invoke various DB2 GUI tools directly from the Control Center. Command to invoke Contral Center : db2cc

2. Command Center : Allows you to write and execute DB2 commands and SQL statements interactively. It also lets you write scripts containing DB2 commands &amp; SQL statements and run them immediately or schedule for later execution. Command to invoke Command Center : db2cmdctr

3. Task Center :  Tool to manage the scheduling and execution of DB2 Command and OS scripts. Upon completion of a job, it can create notifications to be sent to e-mail or pager. Command to invoke Task Center : db2tc

4. Journal:  Keeps a running history of all interactive command and script executions submitted using the DB2 GUI tools. Command to invoke Journal : db2journal

5. Memory Visualizer :  Used to monitor the memory allocation of a DB2instance. Command to invoke Memory Visualizer : db2memvis 

6. Health Center: Used to monitor the state and utilization of many parts of the database manager, the databases, and user agents. Command to invoke Health Center : db2hc

7. Development Center :  It has the features and functions that make it easier for developers to build and deploy applications for either Java or Microsoft environments. The Stored Procedure Builder has been included in the Development Center. Command to invoke Development Cente : db2dc 

8. Configure Assistance :  The Configuration Assistant has many new features. One is to connect &amp; access the remote data base locally using TCP/IP . Command to invoke Configure Assistance : db2memvis

9. Replication Center :  We can use to set up and administer our replication environment which include DB2-to-DB2 replication and DB2 and non-DB2 relational databases. Command to invoke Replication Center : db2rc 

10. Information Center : Provides quick access to DB2 product information and is available on all OS for which the DB2 administration tools are available. Command to invoke Information Center : db2ic 

11. Data Studio Client : In latest version, DB2 control center in replaced with Data Studio Client. You may need to install the Data Studio Client separately.

 To start, Data Studio Client, Change to the home directory where you have installed DataStudio. Then run eclipse.exe 

For example : F:\Program Files\IBM\DSWC4.1>Eclipse.exe


Commands in Brief :

Control Center : db2cc 
Command Center : db2cmdctr 
Configuration Assistance : db2ca 
Health Center : db2hc 
Task Center : db2tc 
Development Center : db2dc 
Journal :  db2journal 
Memory Visualizer : db2memvis 
Information Center : db2ic 
Replication Center : db2rc 
Data Studio : eclipse.exe

The commands can be used in both Linux &amp; Windows environment. The command can be run in db2 command prompt window .

In windows you can get the command prompt (command line processor (CLP)) by running the command db2cmd.

In Linux,  to invoke the DB2 CLP or issue DB2 command directly from the Linux command prompt, we need to run the db2profile in the profile of the login user ID. For that we need to include the following line in login profile. INSTHOME/sqllib/db2profile Where INSTHOME is the DB2 instance home directory.

Tuesday, October 28, 2014

Create Database in DB2 with Unicode (UTF-8) support - Command

By default, in DB2, databases are created in the code page of the application which creates them. In windows, Simply create a database with the following command

db2 create db employee
            - where employee is the database name.

By default employee database is created with the code page 1252 where as code page 1208 will have utf-8 support. You can see the codeset of a database by giving the following command.

In Windows :  db2 get db cfg for employee | find "code"
In Linux :   db2 get db cfg for employee | grep -i  code

Database code page = 1252
Database code set = IBM-1252


 You can also run the following query to get the code-page.

db2 connect to dbname

db2 "Select codepage from syscat.datatypes where typename = 'VARCHAR'"

which returns 1252


We can create the database with unicode (UTF-8) support by the following ways

1) We can create our database from a Unicode (UTF-8) client (for eg. the UNIVERSAL locale of AIX or set DB2CODEPAGE registry variable on the client to 1208)

2) We can explicitly specify CODESET as "UTF-8" with valid TERRITORY code supported by DB2 Universal Database.

To create a Unicode database named "emp_utf" with the territory code for the US, give the following command.

db2 create db emp_utf using codeset utf-8 territory us collate using system

Now again check the code page with the command

db2 get db cfg for emputf |  | find "code" 

which will give following output

Database code page = 1208
Database code set = utf-8

Note : When a Unicode database is created, CHAR, VARCHAR, LONG VARCHAR, and CLOB data are stored in UTF-8 form, and GRAPHIC, VARGRAPHIC, LONG VARGRAPHIC, and DBCLOB data are stored in UCS-2 big-endian form.

Friday, September 26, 2014

Db2 Terminate Vs Connect Reset , Disconnect

db2 Terminate and db2 connect Reset both break the connection to a database.

             Connect Reset breaks a connection to a database, but does not terminate the back-end process. The Terminate command does both ie. break the connection to a database and terminate the back-end process.

Suppose an application is connected to a database, or a process may be in the middle of a of work. We can use TERMINATE to make the database connection to be lost. When Terminate is issued, an internal commit is also performed.

When issue the command db2stop, it may not stop the database manager, if an application is connected to a database. In this situation, you have to issue db2 Terminate command or db2 connect reset, then issue the command db2stop.

Db2 Disconnect is used to clear the database connection of a particular database or all

Syntax : db2 disconnect dbname

eg. db2 disconnect sample

db2 disconnect all

db2 release all

Note : Even after disconnecting database, some times you may get the error message "Database already in use "  when you execute the commands like   "db2 Restore db databasename , etc ..". 

That means current data base is connected by some other applications. Applications connected to the database can be listed out by the following command

db2 list applications

Auth Id Application Name Appl. Handle Application Id DB Name # of Agents
------- -------------- ---------- ------------------------------ -------- -----

TEST javaw.exe 78 *LOCAL.DB2.110722172106 EMPLOYEE 1

TEST javaw.exe 77 *LOCAL.DB2.110722172103 EMPLOYEE 1


Now you can use db2 "force applications all" This command is used to kill  all the applications forcefully at instance level .

To force a particular application with application handle 78
db2  "force application(78)"

Thursday, September 18, 2014

Db2 export command example to export data to external file format (del , ixf )

Suppose you want to transfer data from a db2 database table to another db2 database or within the same database, one of the solution is to use db2 export / import command . Using db2 export / import you can move your data to excel also.

DB2 export command exports data selected by SQL statement from a table or view to an external files in the format of del, asc (ascii format), wsf, ixf etc.. del - delimited , wsf - worksheet format , ixf - Integration Exchange Format.

The DEL format uses delimiter and column separator and decimal point. The default string delimiter is double quote " and column separator is comma(,) and Decimal Point is dot(.), you can also specify your own string delimiter & column separator, decimal point. Another format supported by DB2 is   IXF (Integration Exchange Format). It is a generic relational database exchange format which supports an end-of-record delimiter . IXF architecture supports to exchange of relational database structures and data. IXF is used for transferring data across platforms. The following examples illustrates the use of Export command. You can see more about db2 import command at db2 import.

Example 1 : Export all rows in the Employee table to the file emp.ixf with message file msgs.txt for writing the messages or warnings

              db2 export to emp.ixf of ixf messages msgs.txt select * from employee

Example 2:The following command exports all rows in the Employee table to the file emp.del.

               db2 export to emp.del of del select * from employee

Example 3: The following command exports all rows in the Employee table to the file employee.del using the column delimiter semi colon(;) and string delimiter single quote (') and the decimal point comma,

              db2 export to employee.del of del modified by chardel'' coldel; decpt, select * from employee

    Output of the above is command is as follows.

'1002';'XYZ';+00050003,00;+00060000,00
'1003';'ABC';+00048750,00;+00055550,00

Some of the Parameters  applicable to DB2 Export command:

                MESSAGES message-file : Specifies the destination file to be created for writing warnings and error messages which is generated during an export operation. If the file already exists, then warnings & errors are appended. If msg file is omitted, the messages are written on the console. 

         In the Example 1, msgs.txt is created for information . Sample msgs.txt file has the messages of SQL3104N  
                 The Export utility is beginning to export data to file "emp.ixf". , SQL3105N The Export utility has finished exporting "2" rows.

METHOD N col-name : Specifies 1 or more column names to be written in the output file. If it is not specified, the column names in the table are used. This is valid only for WSF and IXF files . 

    Example : db2 export to emp.ixf of ixf method N (empcode , empname) messages msgs.txt select * from employee

MODIFIED BY filetype-mod : Specifies file type of DEL , IXF , WSF

DB2 Basic Commands with Example

DB2 Basic Commands

1. db2cmd -  Opens db2 command window

2. db2start   - to start the database manager instance

3. db2stop  -  to stop the database manager instance

4. db2stop force - to stop the database manager instance forcefully

5. db2cc - starts the db2 control center

6. db2 list db directory - lists all the databases created in the db server

          -To list databases that start with "SAL"
                Linux : db2 list db directory | grep -i "SAL"
               Windows :  db2 list db directory | find /i "SAL"

7. db2 list tables -  lists all the tables of a connected database
         
          -To list tables that start with "EMP"

                Linux : db2 list tables | grep -i "EMP"
               Windows :  db2 list tables | find /i "EMP"

8. db2 list applications - lists the applications connected
             
           - To count number of applications connected

                   Linux : db2 list applications | grep -c DB2INST1
                   Window: db2 list applications | find /c "SCHEMA NAME'

9. db2 get db cfg - displays the configurations of the connected database.

             -To display configurations related to LOG

                  Linux : db2 get db cfg | grep -i LOG
                  Windows: db2 get db cfg | find /i "LOG"
             

10. db2 get db cfg for databasename - displays the configurations of a database mentioned.

11. db2 get dbm cfg - shows the database level configuration settings

12. db2 terminate -  ends the process the server held open to the client, and drops all resources

13. db2 connect reset - stops the connection to database COMMITs the database.

14. db2licm -l  - displays  the db2 licence details

15. db2 activate db 


16. db2level -  shows the db2 Version detail

17. db2 CALL GET_DBSIZE_INFO(?, ?, ?, -1) -  to get the size of the database sizelists SNAP SHOT TIMESTAMP, DATABASE SIZE, DATABASE CAPACITY


18. db2 list command options - displays the available  Command Line Processor (DB2CMD) settings.


Database creation & Backup Restore Commands:

1. db2 create db databasename  - creates the database

2. db2 create db databasename using codeset utf-8 territory us collate using system - creates the database with utf-8 support

3. db2 backup db dbname - to make offline backup of the database

4. db2 restore db databasename taken at timestamp into sourcedb replace existing -  to restore the database backup into source database.

5. db2move databasename export -  exports the data

6. db2move dbname import  - imports the exported data to the database

7. db2 list history backup all for databasename -shows recent backups and where they are stored

8. db2ckbkp dbimage name -checks the integrity of a backup image

9. db2 restore db incremental automatic taken at - Restores from incremental backup automatic

10. db2ckrst -d -t  - to restore an incremental backup manually this command will give you the required previous backups.

11. db2 list table spaces  -lists all the table spaces of a connected database


Thursday, March 28, 2013

Stored Procedure in db2 and benefits. Create Procedure command with example

A stored procedure is a subroutine that can be called by an application with an SQL CALL statement . A stored procedure is stored in the database itself. Stored Procedures are invoked by executing the CALL statement with a reference to a procedure. The storedprocedure can be called locally or remotely. 


Avoidance of network traffic :
 In client server architecture, applications access the remote database over the network. This results in poor performance because it returns a lot of unnecessary data to the client. But when using stored procedure, as stored procedure runs on the server, only the results the client application needs are returned. This reduces the network traffic, also Stored Procedures groups SQL statements together which can also save on network traffic. A typical application requires two trips across the network for each SQL statement. Grouping of SQL statements reduces the trips across the network which results in better performance for applications. 

Access to features that exist only on the server : Stored procedures can have access to commands that run only on the server, such as LIST DB DIRECTORY and LIST TABLES. It can take the advantages of increased memory and disk space on server machines and they can access any additional software installed on the server.

Define Business rules common to several application : You can use stored procedures to define business rules that are common to several applications similar to triggers and constraints. When an application calls the stored procedure, it will process data based on the rules defined in the stored procedure. If you need to change the rules, you only need to make the change once in the stored procedure, not in every application that calls the stored procedure.

Protection from SQL injection attacks: Stored procedures reduces the risk of sql injection attacks. Stored procedure parameters will be treated as data even if an attacker inserts SQL commands

Helps for workload distribution: It splits the application logic and encourages an even distribution of the computational workload.Stored procedures can be developed using DB2 development center (in db2 8.2) , a GUI based or you can create using CLP . Now let us see how to create and run a Stored Procedures using Command Line Processor (CLP ) . 

Example 1 : Stored Procedure to filter job seekers applications based on the conditions like Date of Birth of the candidate should be between the given two input dates and qualification should be equal to the given input string. The Stored Procedure will accept three input parameters MinDate , MaxDate and Qualification. Output will be the result sets. 

 
CREATE PROCEDURE Shortlist (mindate date , maxdate date, qual  varchar(20))     SPECIFIC sp5    DYNAMIC RESULT SETS 1 
P1: BEGIN
    DECLARE cursor1 CURSOR WITH RETURN FOR   select * from applications where dob>=mindate and dob<=maxdate and qualification=qual;
    OPEN cursor1;
END P1 
@

Store the above lines in a file named sp1.sql. If you run the above script file using the command 
                         db2 -tvf sp1.sql,
                          you may get the error like    DB21028E The cursor "CURSOR1" has not been declared. DB21007E End of file reached while reading the command. 

To solve the above error, select an alternate terminating character for the Command Line Processor (DB2 CLP), other than the default terminating character which is semicolon (;) , to use in the script. For example, the above create procedure statement, @ is used as a terminating character. Now run the DB2 CLP script containing the CREATE PROCEDURE statement from the command line, using the following CLP command:

db2 -td <terminating-character> -vf <CLP-script-name> 

       to run the above Stored Procedure, issue the command 
          db2 -td@ -vf sp1.sql 
                               where @ is a terminating character for the procedure. Now the Stored Procedure (sp1.sql) is created. To run the above stored procedure , issue the command 

db2 call Shortlist('1970-01-01', '1980-01-01', 'BE') ,

      running the command returns all the records whose dob<='1970-01-01' and dob<='1980-01-01' and qualification='BE'

Example 2 : To update employee's salary based on the grade.  Accepts input employee code and grade . 

 
CREATE PROCEDURE SALARY_UPDATE  (IN emp_code varchar(10), IN grade SMALLINT)    LANGUAGE SQL
    BEGIN
      DECLARE error CONDITION FOR SQLSTATE '02000';
      DECLARE EXIT HANDLER FOR error  SIGNAL SQLSTATE '20001' SET MESSAGE_TEXT = 'Employee code does not exist';
      IF (grade = 1)  THEN UPDATE emp3   SET salary = salary + (salary*15/100)   WHERE empcode= emp_code;
      ELSEIF (grade = 2)   THEN UPDATE emp3     SET salary = salary + (salary*10/100)   WHERE empcode= emp_code;
      ELSEIF (grade=3) THEN UPDATE emp3   SET salary = salary + (salary*5/100)    WHERE empcode= emp_code;
      END IF;
    END
@   

Store the above script in a file named sp2.sql

Run the above script by the command 
                           db2 -td@ -vf sp2.sql.            and run the procedure by 
                            db2 call SALARY_UPDATE('1132', 1)   
                                         -where empcode is 1132 and grade is 1.  So the salary will be updated by 15% increment. 

Suppose the employee code does not exist in the table , then the default error
                SQL0100W No row was found for FETCH, UPDATE or DELETE; or the result of a query is an empty table. SQLSTATE=02000      will be thrown. 

  SQLSTATE is 02000 

Now we can change the default error message with own error message like Employee code does not exist . . For the the following lines are used. error variable is declared, if the SQLSTATE=02000. For that error, we are setting a new message as "Employee code doe not exist" and SQLSTATE as 20001.

DECLARE error CONDITION FOR SQLSTATE '02000'; 

DECLARE EXIT HANDLER FOR error SIGNAL SQLSTATE '20001' SET MESSAGE_TEXT = 'Employee code doe not exist'; .  So the following error will be thrown, if no records found. 

SQL0438N Application raised error with diagnostic text: "Employee code does not exist". SQLSTATE=20001

Example 3 : The above two stored procedures return the result sets as output. Now let us see the a different example , to calculate sum of salaries of a particular employee's whose designation matches the given input string . (for eg. UDC , LDC, ...)

 
CREATE PROCEDURE totalsalary(IN Desig char(20)  , OUT totalsalary INTEGER)   LANGUAGE SQL
  BEGIN
    DECLARE SQLSTATE CHAR(5) DEFAULT '00000';
    DECLARE tot_sal INTEGER;
    DECLARE empsalary INTEGER;
    DECLARE cursor1 CURSOR FOR SELECT SALARY FROM EMP3 where Designation=Desig;
      SET tot_sal= 0;
     OPEN cursor1;
     FETCH FROM cursor1 INTO empsalary;
     WHILE(SQLSTATE = '00000') DO
        SET tot_sal = tot_sal+ empsalary;
        FETCH FROM cursor1 INTO empsalary; 
     END WHILE;
     CLOSE cursor1;
     SET totalsalary=tot_sal;
  END%

In the above script, termination charater is %, so run the script with command 
                                db2 -td% -vf sp3.sql
            It accepts two parameters. One is for input , another is for output. We have set SQLSTATE to '00000'. So the while loop continues until the SQLSTATE changes. The SQLSTATE changes when the cursor has no further rows. when there is no rows , it throws exception with SQLSTAT 02000. Now the while loop terminates.