db2 working with databases and database objects

Upload: girish-kumar-nistala

Post on 08-Apr-2018

241 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/6/2019 DB2 Working With Databases and Database Objects

    1/14

    1

    IBM DB2 9

    2008 IBM Corporation

    Section -3) Working withWorking withDatabases and Database ObjectsDatabases and Database Objects

    IBM DB2 9

    2

    Section 3Section 3 -- Working with Databases andWorking with Databases and

    Database Objects (17%)Database Objects (17%)

    Ability to identify and connect to DB2 serversAbility to identify and connect to DB2 servers

    and databasesand databases

    Ability to identify DB2 objectsAbility to identify DB2 objects

    Knowledge of basic characteristics andKnowledge of basic characteristics and

    properties of DB2 objectsproperties of DB2 objects

    Given a DDL SQL statement, ability to identifyGiven a DDL SQL statement, ability to identify

    results (ability to create DB2 objects)results (ability to create DB2 objects)

    IBM DB2 9

    3

    Servers, Instances, and Databases

    During the installation process, program files for a background

    process known as the DB2 Database Manager are physically

    copied to a specific location on the server.

    A DB2 instance is a logical database server environment.

    There can be multiple DB2 instances on a server. Multiple

    Databases can be created within a DB2 instance.

    IBM DB2 9

    4

    More on instances

    The default instance for a particular system is defined by the

    DB2INSTANCE environment variable. Initially for Windows

    default is DB2 and for Linux/Unix it is db2inst1.

    DB2 9 Instance Management Commands:

    Command Purpose

    db2icrt [InstanceName] Creates a new instance

    db2idrop [InstanceName] Deletes (drops) an existing instance

    db2ilist Lists all instances that have been defined

    db2start Starts the DB2 Database Manager background

    processes for the current instance

    db2stop Stops the DB2 Database Manager background

    processes for the current instance

  • 8/6/2019 DB2 Working With Databases and Database Objects

    2/14

    2

    IBM DB2 9

    5

    DB2 Storage Model

    IBM DB2 9

    6

    DB2 Storage Model

    A database is created within an instance.- There may be multiple databases managed by a DB2

    instance

    Logical storage model:- Tables are made up of columns and rows

    - Tables are placed into table spaces

    - Table spaces can contain more than one table

    Physical storage model:- Containeris a physical storage device

    - Can be a directory, a device, or a file

    - Container is assigned to a table space

    IBM DB2 9

    7

    Tablespaces

    A tablespace is a logical layer between data and storagedevices.

    - Consists of one or more containers.

    - Tables, regular data, indexes, and long data reside in

    tablespacesSQL: CREATE / DROP / ALTER TABLESPACE

    To display Table space info:

    - LIST TABLESPACES [SHOW DETAIL]

    Details about containers can be obtained with followingcommand.

    - LIST TABLESPACE CONTAINERS FOR tablespace_id[SHOW DETAIL]

    IBM DB2 9

    8

    Types of Tablespaces

    System-Managed Space (SMS):

    - OSs file system manager allocates and manages the space.

    Database-Managed Space (DMS):

    - Here, the database manager controls the storage space.

    Automatic Storage With DMS:- Databases that are enabled for automatic storage have a set

    of one or more storage paths associated with them.

    - A table space can be defined as "managed by automaticstorage" and its containers assigned and allocated by DB2based on those storage paths.

    - You cannot enable/disable automatic storage once it isdefined for database.

    - Default type in DB2 9.

  • 8/6/2019 DB2 Working With Databases and Database Objects

    3/14

    3

    IBM DB2 9

    9

    IBM DB2 9

    10

    Database

    The database contains following objects:-Tables, views, indexes, schemas, Locks, triggers, stored

    procedures, packages, Buffer pools, log files, table spaces

    Tools, which can help you create DB2 9 database are FirstSteps, Control Center [ Using GUI Wizard ] and CommandLine Processor (CLP).

    Some database commands -

    CREATE DATABASE

    To create a database. (Database name

    can not begin with "SYS", "DBM", or "IBM)

    CONNECT TO To connect to a database

    CONNECT RESET To terminate connection

    DROP DATABASE To drop database

    IBM DB2 9

    11

    With database, DB2 automatically creates

    Three table spaces are created.

    - SYSCATSPACE - This is where the DB2 system

    catalog is kept that tracks all of the metadata

    associated with DB2 objects.

    - TEMPSPACE1 A temporary work area where

    DB2 can place intermediate results.

    - USERSPACE1 A place where all user objects

    (tables, indexes) reside by default.

    Configuration information (DB CFG)

    Log files, History files etc.

    IBM DB2 9

    12

    Cataloging

    DB2 automatically catalogs databases when they arecreated. It catalogs an entry for the DB in the local databasedirectory and another entry in the system database directory.

    Without catalog information, an application cannot connect to a

    DB. DB2 has multiple directories that are used to access DBs.- The database directory contains a list and pointer to where

    all the known databases can be found. (list db directory)

    - The node directory contains information relating to how andwhere remote instances can be found. (list node directory)

    - The Database Connection Services (DCS) Directorycontains information relating to how and where databases onDRDA systems can be found. (list dcs directory)

  • 8/6/2019 DB2 Working With Databases and Database Objects

    4/144

    IBM DB2 9

    13

    3 ways of cataloging a database at a client

    Automated configuration using discovery. This method isnormally used to configure small numbers of clients.

    - Search discovery- Client searches for servers on the network

    - Known discovery- one particular server is queried forinformation about the instances and their databases

    Automated configuration using access profiles. Thismethod is used to configure a large number of clients.

    - Server profiles- created from DB2 servers, containsinformation about all the instances and databases of server

    -Client profiles- used to duplicat the cataloged databasesand/or the client settings from one client to another

    Manual configuration used to exploit some advanced optionsnot available using automation

    IBM DB2 9

    14

    Get connected using Configuration Assistant

    IBM DB2 9

    15

    Configuration Assistant - Search the Network (1)

    IBM DB2 9

    16

    Configuration Assistant - Search the Network (2)

  • 8/6/2019 DB2 Working With Databases and Database Objects

    5/145

    IBM DB2 9

    17

    Configuration Assistant - Search the Network (3)

    Click

    IBM DB2 9

    18

    Configuration Assistant - Search the Network (4)

    Click

    Enter User ID andPassword throughwhich you want toconnect and clickTest Connection

    Result tab will showconnection results.

    IBM DB2 9

    19

    Configuration Assistant Manually (1)

    Enter IP address or

    Machine NameDefault port on

    Windows : 50000

    Click

    IBM DB2 9

    20

    Configuration Assistant - Manually (2)

    Click

    Choose protocol

    (e.g. TCP/IP)

  • 8/6/2019 DB2 Working With Databases and Database Objects

    6/146

    IBM DB2 9

    21

    Configuration Assistant Manually (3)

    Enter Database name

    Click

    Enter : Alias of database

    which don't exist on client

    IBM DB2 9

    22

    Configuration Assistant Manually (4)

    Click

    IBM DB2 9

    23

    Configuration Assistant - Manually (5)

    Click

    IBM DB2 9

    24

    Configuration Assistant Manually (6)

    Click

  • 8/6/2019 DB2 Working With Databases and Database Objects

    7/147

    IBM DB2 9

    25

    Configuration Assistant - Manually (7)

    Click

    Enter User ID andPassword throughwhich you want toconnect and clickTest Connection

    Result tab will showconnection results.

    IBM DB2 9

    26

    Client/Server Connectivity using CLP

    To illustrate connectivity ,we will use a scenario:- INSTANCE is DB2

    - DATABASE is SAMPLE

    - IP ADDRESS is 9.186.128.141

    Settings on the server:

    - Value of DB2COMM is tcpip

    - Services file contains valid TCP/IP port number , in our case

    default is 50000

    Windows client machine:

    - Catalog the server

    - Catalog the database

    IBM DB2 9

    27

    CLP - Cataloging the Server and Database

    Cataloging a server:

    - CATALOG TCPIP NODE db2server

    REMOTE 9.186.128.141 SERVER 50000

    Cataloging a database:

    -CATALOG DATABASE sample AS srv_samp

    AT NODE db2server

    - UNCATALOG DATABASE sample

    Cataloging a DCS database (DRDA Server)

    - CATALOG DCS DATABASE test_db AS dsn_db

    WITH "DB2 z/OS database"

    IBM DB2 9

    28

    Database Objects - Schemas

    Schemas are objects that are used to logically classify and

    group other objects in the database. Schemas have privileges

    associated with them that allow the schema owner to control

    which users can create, alter, and drop objects within them.

    When an object is created without specifying a schema, object

    will be associated with an implicit schema using the

    authorization ID.

    Most database objects are named using a two-part naming

    convention (SCHEMA_NAME.OBJECT_NAME).

    The CURRENT SCHEMA special register contains the default

    qualifier to be used for unqualified objects.

    CREATE SCHEMA inventory

  • 8/6/2019 DB2 Working With Databases and Database Objects

    8/148

    IBM DB2 9

    29

    Database Objects - Tables

    A Table is an unordered set of rows. Rows consist of columns.Each column is based on a data type. Types of tables can be:

    Base tables: User-defined tables designed to hold persistentuser data, created with the CREATE TABLE SQL statement.

    Temporary (Derived) tables: Tables populated with rowsretrieved from one or more base tables in response to a query.

    Temporary (Declared) tables: User-defined tables used tohold non-persistent data temporarily, on behalf of a single

    application. These tables are explicitly created by anapplication when they are needed and implicitly destroyedwhen the application terminates its last database connection.Declared temporary table is created with the DECLAREGLOBAL TEMPORARY TABLE statement.

    IBM DB2 9

    30

    Database Objects - Views

    Views can be seen as virtual tables derived from oneor more tables or views and

    - Created to limit access to sensitive data while allowingmore general access to other data.

    - Views do not contain real data.

    - Can be deletable, updatable, insertable, and read-only.

    - When changes are made to data through a view, the datais changed in underlying table itself.

    -Can be used interchangeably with tables when retrievingdata.

    CREATE VIEW dept_view AS

    SELECT * FROM department

    IBM DB2 9

    31

    Database Objects - Indexes

    An index is an object that contains an ordered set of

    pointers that refer to rows in a base table, based upon

    one or more columns but stored as a separate entity.

    Indexes are used to enforce uniqueness in a table

    (that is, to make sure that there are no duplicatevalues) and to improve performance when retrieving

    information.

    Indexes are maintained automatically by DB2 as

    data is inserted, updated, and deleted.

    CREATE UNIQUE INDEX empno_indx ON

    employees(empno)

    IBM DB2 9

    32

    Database Objects Aliases & Nicknames

    An alias is simply an alternate name for a table or

    view.

    Like tables and views, an alias can be created,

    dropped, and have comments associated with it.

    Aliases can also be created for nicknames that refer

    to tables or views found on federated systems.

    Aliases are publicly referenced names, so no special

    authority or privilege is required to use them.

    CREATE ALIAS empinfo FOR employees

  • 8/6/2019 DB2 Working With Databases and Database Objects

    9/149

    IBM DB2 9

    33

    Database Objects Sequences

    A sequence is an object that is used to generate data valuesautomatically. Unlike an identity column, a sequence is not tied

    to any specific column or any specific table.

    Values generated can be any exact numeric data type that

    has a scale of zero (SMALLINT, BIGINT, INTEGER, or

    DECIMAL).The default increment value is 1.

    The PREVIOUS VALUE expression returns the most recently

    generated value for the specified sequence, while the NEXT

    VALUE expression returns the next sequence value.

    CREATE SEQUENCE emp_id START WITH 100

    INCREMENT BY 10 CACHE 5

    IBM DB2 9

    34

    Database Objects Triggers

    A trigger is used to define a set of actions that are to beexecuted whenever an insert, update, or delete operation isperformed against a table or updatable view.

    Like constraints, triggers are often used to enforce dataintegrity and business rules.

    Unlike constraints, triggers can also be used to update othertables, automatically generate or transform values for insertedor updated rows, and invoke functions to perform tasks suchas issuing errors or alerts.

    Ex. CREATE TRIGGER pay_raiseBEFORE UPDATE ON employees

    FOR EACH ROW

    SET new.salary = salary * 1.1

    IBM DB2 9

    35

    Database Objects Stored Procedures

    An SQL stored procedure is composed entirely of SQL

    statements. It is created by executing one form of the CREATE

    PROCEDURE SQL statement.

    When an SQL stored procedure is used to implement a

    business rule, the logic can be incorporated into any

    application simply by invoking the stored procedure.

    An external stored procedure is a stored procedure that is

    written using a high-level programming language such as C,

    C++, Java, or COBOL.

    External stored procedures can be more powerful than SQL

    stored procedures because they can take advantage of system

    calls and administrative APIs along with SQL statements.

    IBM DB2 9

    36

    Calling a Stored Procedure

    CREATE PROCEDURE get_sales(IN quota INTEGER, OUT retcode CHAR(5))DYNAMIC RESULT SETS 1 LANGUAGE SQL

    BEGIN

    DECLARE sqlstate CHAR(5);

    DECLARE sales_results CURSOR WITH RETURN FORSELECT sales_person, SUM(sales) AS total_sales

    FROM sales GROUP BY sales_personHAVING SUM(sales) > quota;

    DECLARE EXIT HANDLER FOR SQLEXCEPTIONSET retcode = sqlstate; OPEN sales_results;SET retcode = sqlstate;

    END

    CALL get_sales (25, ?)

  • 8/6/2019 DB2 Working With Databases and Database Objects

    10/1410

    IBM DB2 9

    37

    Database Objects Packages

    A package is an object that contains information needed to process SQL

    statements associated with a source code file of an application program.

    During the pre-compile process,

    - a source code file containing embedded SQL statements is converted

    into a source code file that is made up entirely of high-level programming

    language statements.

    - At the same time, a corresponding package that contains the access

    plans that will be used to process each SQL statement embedded in the

    source code file is also produced.

    - This package must reside in a DB2 database that contains the data

    objects referenced by the package before the corresponding applicationcan be executed against that database.

    The process of creating and storing a package in a DB2 database is known

    as binding, and by default, packages are automatically bound to a

    database during the precompile process.

    IBM DB2 9

    38

    Database Objects UDFs

    User-defined functions (UDFs) are special objects that areused to extend and enhance the support provided by the built-

    in functions available with DB2 9.

    Unlike DB2's built-in functions, user-defined functions can take

    advantage of system calls and DB2's administrative APIs.

    User-defined functions are created (or registered) by executing

    the CREATE FUNCTION SQL statement.

    SQL Scalar, Table, or Row. constructed using only SQL

    statements and can return a value, row or table.External Scalar/Table written using a high-level programming

    language such as C, C++, or Java and returns a single value

    or table.

    IBM DB2 9

    39

    Invoking User-Defined Functions

    CREATE FUNCTION jobemployees (job VARCHAR(8))

    RETURNS TABLE (empno CHAR(6),

    firstname VARCHAR(12), lastname VARCHAR(15))

    LANGUAGE SQL READS SQL DATA

    NO EXTERNAL ACTION DETERMINISTIC

    RETURN SELECT empno, firstnme, lastname

    FROM employee

    WHERE employee.job = jobemployees.job;

    Calling function -

    SELECT * FROM TABLE (jobemployees('CLERK'))

    SELECT temp AS tempf, convert_temp(temp, 'F') AS tempcFROM climate_info

    IBM DB2 9

    40

  • 8/6/2019 DB2 Working With Databases and Database Objects

    11/14

  • 8/6/2019 DB2 Working With Databases and Database Objects

    12/1412

    IBM DB2 9

    45

    5) An alias can be an alternate name for which

    two of the following DB2 objects?

    -A. Sequence

    -B. Trigger

    -C. View

    -D. Schema

    -E. Table

    IBM DB2 9

    46

    6) Which of the following DB2 objects can be

    referenced by an INSERT statement togenerate values for a column?

    A. Sequence

    B. Identity column

    C. Trigger

    D. Table function

    IBM DB2 9

    47

    7) Which of the following is NOT an attribute of

    Declared Global Temporary Tables (DGTTs)?

    A. Each application that defines a DGTT has its own

    instance of the DGTT

    B. Two different applications cannot create DGTTs

    that have the same name

    C. DGTTs can only be used by the application that

    creates them, and only for the life of the application

    D. Data stored in a DGTT can exist across transaction

    boundaries

    IBM DB2 9

    48

    8) Which of the following is an accurate statement

    about packages?

    A. Packages provide a logical grouping of database

    objects.

    B. Packages contain control structures that are

    considered the bound form for SQL statements

    C. Packages describe the objects in a DB2 database

    and their relationship to each other

    D. Packages may be used during query optimization

    to improve the performance for a subset of SELECT

    queries

  • 8/6/2019 DB2 Working With Databases and Database Objects

    13/14

    13

    IBM DB2 9

    49

    9) Which of the following events will NOT cause

    a trigger to be activated?

    A. A select operation

    B. An insert operation

    C. An update operation

    D. A delete operation

    IBM DB2 9

    50

    10) Which of the following DB2 objects is NOT

    considered executable using SQL?

    A. Routine

    B. Function

    C. Procedure

    D. Trigger

    IBM DB2 9

    51

    11) Which of the following is NOT an accurate

    statement about views?

    A. Views are publicly referenced names and no

    special authority or privilege is needed to use them.

    B. Views can be used to restrict access to columns in

    a base table that contain sensitive data

    C. Views can be used to store queries that multiple

    applications execute on a regular basis in a database

    D. Views support INSTEAD OF triggers

    IBM DB2 9

    52

    12) Which of the following SQL statements can be

    used to create a DB2 object to store numerical data

    as EURO data?

    A. CREATE NICKNAME euro FOR DECIMAL (9,3)

    B. CREATE ALIAS euro FOR DECIMAL (9,3)

    C. CREATE DISTINCT TYPE euro AS DECIMAL

    (9,3)

    D. CREATE DATA TYPE euro AS DECIMAL (9,3)

  • 8/6/2019 DB2 Working With Databases and Database Objects

    14/14

    14

    IBM DB2 9

    53

    Japanese

    Hebrew

    Thank

    YouEnglish

    MerciFrench

    Russian

    DankeGerman

    GrazieItalian

    GraciasSpanish

    ObrigadoPortuguese

    Arabic

    Simplified Chinese

    Traditional Chinese

    Tamil

    Thai

    Korean