algacisnews.algacis.com/citm_uploads/all units of client server .pdfa problem. in this dynamic...

220
PAPER III – CLIENT – SERVER PROGRAMMING UNIT – I SYSTEM ANALYSIS AND DESIGN (SAD) System Concepts-Development Life Cycle- Feasibility Study-Design Implementation and Evaluation. System specification and Analysis-Decision Trees and Tables. UNIT – II INTRODUCTION TO PACKAGES AND RDBMS Package and Review – Introduction to RDBMS – Codd’s Rules. Data Integrity – Data Consistancy – Problems in Normalizations. Entity – Relation (ER) modeling – Relational Model. UNIT III ORACLE BASED PROGRAMMING CONCEPTS Introduction to SQL – Data definition language (DDL) – Data manipulation language (DML) – Data control language, Creation – Deletion – Modifications- View subject – Query – Sub query – Correlated sub query. Introduction to PL/SQL – Control structures-Cursors-Procedure’s- Functions-Triggers-Packages. UNIT – IV GRAPHICAL USER INTERFACE & LANGUAGE REFERENCE Introduction to Graphical User Interface - Introduction to Visual Basic – Structures of a Visual Basic Applications – Drawing Tools – Setting Properties - Variables – Visual Basic Data types. UNIT – V PROGRAMMING IN VISUAL BASIC Visual Basic Language Reference – Exploring Visual Basic Toolbox – Creating a Stand Alone Visual Basic Application – Error – Handling and Debugging – File Input/output – Graphics Techniques with Visual Basic – Database Access and Management. 1. System Concept System is defined as a set of elements arranged in an orderly manner to accomplish an objective. System is not a randomly arranged set. It is arranged with some logic governed by rules, regulations, principles and policies. Such an arrangement is also influenced by the objective the system desires to achieve. Systems are created to solve problems. One can think of the systems approach as an organized way of dealing with

Upload: others

Post on 08-Jul-2020

0 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

PAPER III – CLIENT – SERVER PROGRAMMING

UNIT – I SYSTEM ANALYSIS AND DESIGN (SAD)

System Concepts-Development Life Cycle- Feasibility Study-Design Implementation and Evaluation. System specification and Analysis-Decision Trees and Tables.

UNIT – II INTRODUCTION TO PACKAGES AND RDBMS

Package and Review – Introduction to RDBMS – Codd’s Rules. Data Integrity – Data Consistancy – Problems in Normalizations. Entity – Relation (ER) modeling – Relational Model.

UNIT III ORACLE BASED PROGRAMMING CONCEPTS

Introduction to SQL – Data definition language (DDL) – Data manipulation language (DML) – Data control language, Creation – Deletion – Modifications- View subject – Query – Sub query – Correlated sub query. Introduction to PL/SQL – Control structures-Cursors-Procedure’s- Functions-Triggers-Packages.

UNIT – IV GRAPHICAL USER INTERFACE & LANGUAGE REFERENCE

Introduction to Graphical User Interface - Introduction to Visual Basic – Structures of a Visual Basic Applications – Drawing Tools – Setting Properties - Variables – Visual Basic Data types.

UNIT – V PROGRAMMING IN VISUAL BASIC

Visual Basic Language Reference – Exploring Visual Basic Toolbox – Creating a Stand Alone Visual Basic Application – Error – Handling and Debugging – File Input/output – Graphics Techniques with Visual Basic – Database Access and Management.

1. System Concept

System is defined as a set of elements arranged in an orderly manner to accomplish an objective. System is not a randomly arranged set. It is arranged with some logic governed by rules, regulations, principles and policies. Such an arrangement is also influenced by the objective the system desires to achieve. Systems are created to solve problems. One can think of the systems approach as an organized way of dealing with

Page 2: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

a problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development activities.

For example, if a computer system is designed to perform commercial data processing, then the elements will be data entry devices, a CPU, a disk, a memory, application programs and a printer. If a computer is designed to achieve the objective of design, engineering and drawing processing, then the elements will be the graphic processor, and the languages suitable for engineering and design applications, and plotters for drawing the output.

However, a clear statement of objectives brings a precision and an order into the selection of elements and their arrangements in the system. Any disorder would create a disturbance in the system, affecting the accomplishment of the objectives.

If a system in any field is analyzed. It will be observed that it has three basic parts, which are organized in an orderly manner. These three parts can be represented in a model as shown:-

A system may have single input and multiple outputs or may have several inputs and outputs. All the systems operate in an environment. The environment may influence the system in its design and performance. When a system is designed to achieve certain objectives, it automatically sets the boundaries for itself. The understanding of boundaries of the system is essential to bring clarity in explaining the system components and their arrangements.

A collection of component that work together to realize some objectives forms a system. In a system the different components are connected with each other and they are interdependent. For example, human body represents a complete natural system. We are also bound by many national systems such as political system, economic system, educational system and so forth. The objective of the system demands that some output is produced as a result of processing the suitable inputs. A well designed system also includes an additional element referred to as ‘control’ that provides a feedback to achieve desired objectives of the system.

The system can be classified in different categories based on the predictability of its output and the degree of information exchange with the environment. A system is called deterministic when the inputs, the process and outputs are known with certainty.

Page 3: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

In a deterministic system, when the output can only be predicted in probabilistic terms. The accounting system is a probabilistic one. A deterministic system operates in a predictable manner while a probabilistic system behavior is not predictable.

If a system is functioning is separated from the environment, then the system does not have any exchange with the environment nor is it influenced by the environmental changes then it is called an open system. All kinds of accounting systems, for example, cash, stocks, attendance of employees, are closed systems. Most of the systems based on rules and principles are closed systems.

The systems which are required to respond to changes in the environment such as marketing, communication and forecasting are open systems. All open systems must have a self-organizing ability and a sensitivity to absorb and adjust to the business organization systems of manufacturing are closed systems.

The information system is a combination of a person (the user of information), the hardware –software system is a closed deterministic system but in combination with the user it is an open and a probabilistic system.

Generally, the deterministic systems are closed, and the probabilistic systems are open. The deterministic and the closed systems are easy to computerize as they are based on facts and their behavior can be predicted with certainty. A fixed deposit accounting system, an invoicing system, and share accounting systems are examples of closed and deterministic system.

The probabilistic system and the open systems are complex in every aspect. Hence, they call for considerable amount of checks and controls so that the system behavior on the performance can be controlled. All such systems must ideally have self organizing corrective system to keep the system going its desired path.

For example, the pricing systems are probabilistic and open. They are to be so designed that the changes in the taxes and duties, the purchase price and the supply positions are taken care of, in the sales price computation. Since the pricing system operates under the influence of the environment, it has to be designed with flexible computing routines to determine the price. The building of self-organizing processing routines to respond to the environmental influences is a complex task both in terms of design and operations of the system.

Page 4: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

System analysis

System analysis may be understood as a process of collecting and interpreting facts, identifying problems and using the information to recommend improvements in the system. In other words system analysis means identification, understanding and examine the system for achieving predetermined goals/objectives of the system. System analysis is carried out with the following two objectives:-

1. To know how a system currently operates and

2. To identify the users requirements in the proposed system

Basically, system analysis is a detailed study of all important business aspects under consideration and the existing system, and thus, the study becomes a basis for the proposed system (may be a modified or an altogether new system). System analysis is regarded as a logical process. The emphasis in this phase is an investigation to know how the system is currently operating and to determine what must be done to solve the problem.

The system analysis phase is very important in the total development efforts of a system. The user may be aware of the problem but may not know how to solve it. During system analysis, the developer (system designer) works with the user to develop a logical model of the system. A system analyst, because of his technical background, may move too quickly to program design to make the system prematurely physical, which is not desirable and may affect the ultimate success of the system. In order to avoid this, the system analyst must involve the user at this stage to get complex information about the system. This can be achieved if a logical model of the system is developed on the basis of detailed study. Such a study (analysis) should be done by using various modern tools and techniques, such as data flow diagrams, data dictionary, and rough description of the relevant algorithm the final requirement of proposed information system.

System analysis is a process of collecting factual data, understanding the process involved, identifying problems and recommending feasible suggestion for improving the system functioning. This involves studying the business processes, gathering operational data, understand the information flow, finding out bottlenecks and evolving solutions for overcoming the weakness of the system so as to achieve the organizational

Page 5: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

goals. System analysis also includes subdividing of complex process involving the entire system, identification of data store and manual process.

The major objectives of system analysis are to find answers for each business process: what is being done how is it being done, who is doing it, when is he doing it, why is it being done and how can it be improved? It is more of a thinking process and involves the creative skills of the system analyst. It attempts to give birth to a new efficient system that satisfies the current needs of the user and has scope for future growth within the organizational constraints. The result of this process is a logical system design. System analysis is an interactive process that continues until a preferred and acceptable solution emerges.

SYSTEM DESIGN

Based on the user requirements and the detailed analysis of the existing system, the new system must be designed. This is the phase of system designing. It is the most crucial phase in the development of a system. The logical system design arrived at as a result of system analysis is converted into physical system design. Normally, the design proceeds in two stages:

PRELIMINARY OR GENERAL DESIGN

In the preliminary or general design, the features of the new system are specified. The costs of implementing these features and the benefits to be derived are estimated. If the project is still considered to be feasible (possible), we move to the detailed design stage.

STRUCTURED OR DETAILED DESIGN

In the detailed design stage, computer oriented work begins in earnest. At this stage the design of the system becomes more structured. Structure design is a blue print of a computer system solution to a given problem having the same components and inter-relationships among the same components as the original problem. Input, output, databases, forms, codifications schemes and processing specifications are drawn up in detail. In the design stage, the programming language and the hardware and software platform in which the new system will run are also decide.

The system design involves:-

Page 6: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

I. Defining precisely the required system output

II. Determining the data requirement for producing the output

III. Determining the medium and format of files and databases

IV. Devising processing methods and use of software to produce output

V. Determine the methods of data capture data input

VI. Designing input forms

VII. Designing codification schemed

VIII. Detailed manual procedures

IX. Documenting the design

SYSTEM ANALYSIS AND DESIGN

SAD, as performed by the system analysts, seeks to understand what human need to analyze data input or data flow systematically, process information in the context of a particular business. Furthermore, system analysis and design is used to analyze, design and implements in the support of users and the functioning of business that can be accomplished through the use of computerized information system.

Installing a system without proper planning leads to great user dissatisfaction and frequently causes the system to fall into disuse. System analysis and design lends structure to the analysis and design of information systems, a costly endeavor that might otherwise have been done in a haphazard way. It can be thought of as a series of processes systematically undertaken to improve a business through the use of computerized information system. SAD involves working with current and eventual users of information system to support them in working with technologies in an organizational setting.

THE NEED FOR SYSTEM ANALYSIS

When you are asked to computerized a system, it is necessary to analyze the system from different angles. The analysis of the system is the basic necessity for an efficient system design. The need for analysis stems from the following point of view:-

Page 7: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

System objective: it is necessary to define the system objectives. Many a times, it is observed that the systems are historically in operation and have lost their main purpose of achievement of the objectives. The users of the system and the personnel involved are not in a position to define the objectives. Since you are going to develop a computer based system, it is necessary to redefine or reset the objectives as a reference point in context of current business requirement.

System boundaries: it is necessary to establish the system boundaries which would define the scope and the coverage of the system. This helps to short out and understand the functional boundaries in the system, and the people involved in the system. It also helps to identify the inputs and the outputs of the various subsystems, covering the entire system.

System importance: it is necessary to understand the importance of the system in the organization. This would help the designer to decide the design feature of the system. It would be possible then to position the system in relation to the other systems for deciding the design, strategy and development.

Nature of the system: the analysis of the system will help the system designer to conclude whether the system is closed type or an open, and a deterministic or a probabilistic. Such an understanding of the system is necessary prior to design the process to ensure the necessary design architecture.

Role of the system as an interface: the system, many a times, acts as an interface to the other systems. It is necessary to understand the existing role of the system, as an interface, to safeguard the interests of the other systems. Any modification or changes made should not affect the functioning or the objectives of the other system.

Participation of the user: the strategic purpose of the analysis of the people to a new development. System analysis process provides a sense of participation to the people. This helps in breaking the resistance to the new development and it also then ensures the commitment to the new development and it also then ensures the commitment to the new system.

Understanding of resource needs: the analysis of the system helps in defining the resource requirement in terms of hardware and software. Hence, if any additional resources are required, this would mean an investment from the point of view of return

Page 8: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

on such investment. If the return on such investment from the point of view of return on such an investment. If the return on the investment is not attractive, the management may drop the project.

Assessment of feasibility (practicability): the analysis of the system helps to establish the feasibility from different angles. The system should satisfy the technical economic and operational feasibility. Many a time, the systems are feasible from the technical and economic point of view, but they may be infeasible from the operational point of view. The assessment of feasibility will have the investment and the system designer’s time. It would also save the embracement to the system designer as he is viewed as the key figure in such project.

2. SYSTEM DEVELOPMENT LIFE CYCLE

System life cycle is an organizational process of developing and maintaining systems. It helps in establishing a system project plan, because it gives overall list of processes and sub-processes required for developing a system. System development life cycle means combination of various activities. In other words we can say that various activities put together are referred as system development life cycle. In the System Analysis and Design terminology, the system development life cycle also means software development life cycle. Following are the different phases of system development life cycle:

Preliminary study

1. Feasibility study

2. Detailed system study

3. System analysis

4. System design

5. Coding

6. Testing

7. Implementation

8. Maintenance

Page 9: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

PHASES OF SYSTEM DEVELOPMENT LIFE CYCLE

Let us now describe the different phases and related activities of system development life cycle.

(a) Preliminary System Study

Preliminary system study is the first stage of system development life cycle. This is a brief investigation of the system under consideration and gives a clear picture of what actually the physical system is? In practice, the initial system study involves the preparation of a ‘System Proposal’ which lists the Problem Definition, Objectives of the Study, Terms of reference for Study, Constraints, and Expected benefits of the new system, etc. in the light of the user requirements. The system proposal is prepared by the System Analyst (who studies the system) and places it before the user management. The management may accept the proposal and the cycle proceeds to the next stage. The management may also reject the proposal or request some modifications in the proposal. In summary, we would say that system study phase passes through the following steps:

v l problem identification and project initiation v l background analysis v l inference or findings (system proposal)

(b) Feasibility Study

In case the system proposal is acceptable to the management, the next phase is to examine the feasibility of the system. The feasibility study is basically the test of the proposed system in the light of its workability, meeting user’s requirements, effective use of resources and of course, the cost effectiveness. These are categorized as technical, operational, economic and schedule feasibility. The main goal of feasibility study is not to solve the problem but to achieve the scope. In the process of feasibility study, the cost and benefits are estimated with greater accuracy to find the Return on Investment (ROI). This also defines the resources needed to complete the detailed investigation. The result is a feasibility report submitted to the management. This may be accepted or accepted with modifications or rejected. The system cycle proceeds only if the management accepts it.

(c) Detailed System Study

The detailed investigation of the system is carried out in accordance with the objectives of the proposed system. This involves detailed study of various operations performed by a system and their relationships within and outside the system. During this process, data are collected on the available files, decision points and transactions handled by the present system. Interviews, on-site observation and questionnaire are the tools used for detailed system study. Using the following steps it becomes easy to draw the exact boundary of the new system under consideration:

· Keeping in view the problems and new requirements

· Workout the pros and cons including new areas of the system

Page 10: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

All the data and the findings must be documented in the form of detailed data flow diagrams (DFDs), data dictionary, logical data structures and miniature specification. The main points to be discussed in this stage are:

v Specification of what the new system is to accomplish based on the user requirements. v Functional hierarchy showing the functions to be performed by the new system and their

relationship with each other v Functional network, which are similar to function hierarchy but they highlight the functions

which are common to more than one procedure. v List of attributes of the entities – these are the data items which need to be held about each

entity (record)

(d) System Analysis

Systems analysis is a process of collecting factual data, understand the processes involved, identifying problems and recommending feasible suggestions for improving the system functioning. This involves studying the business processes, gathering operational data, understand the information flow, finding out bottlenecks and evolving solutions for overcoming the weaknesses of the system so as to achieve the organizational goals. System Analysis also includes subdividing of complex process involving the entire system, identification of data store and manual processes. The major objectives of systems analysis are to find answers for each business process: What is being done How is it being done, who is doing it, When is he doing it, Why is it being done and How can it be improved? It is more of a thinking process and involves the creative skills of the System Analyst. It attempts to give birth to a new efficient system that satisfies the current needs of the user and has scope for future growth within the organizational constraints. The result of this process is a logical system design. Systems analysis is an iterative process that continues until a preferred and acceptable solution emerges.

(e) System Design

Based on the user requirements and the detailed analysis of the existing system, the new system must be designed. This is the phase of system designing. It is the most crucial phase in the developments of a system. The logical system design arrived at as a result of systems analysis is converted into physical system design. Normally, the design proceeds in two stages:

v Preliminary or General Design v Structured or Detailed Design

Preliminary or General Design: In the preliminary or general design, the features of the new system are specified. The costs of implementing these features and the benefits to be derived are estimated. If the project is still considered to be feasible, we move to the detailed design stage.

Page 11: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

Structured or Detailed Design: In the detailed design stage, computer oriented work begins in earnest. At this stage, the design of the system becomes more structured. Structure design is a blue print of a computer system solution to a given problem having the same components and inter-relationships among the same components as the original problem. Input, output, databases, forms, codification schemes and processing specifications are drawn up in detail. In the design stage, the programming language and the hardware and software platform in which the new system will run are also decided. There are several tools and techniques used for describing the system design of the system. These tools and techniques are:

v Flowchart v Data flow diagram (DFD) v Data dictionary v Structured English v Decision table v Decision tree

The system design involves:

1. Defining precisely the required system output

2. Determining the data requirement for producing the output

3. Determining the medium and format of files and databases

4. Devising processing methods and use of software to produce output

5. . Determine the methods of data capture and data input

6. Designing Input forms

7. Designing Codification Schemes

8. Detailed manual procedures

9. Documenting the Design

(f) Coding

The system design needs to be implemented to make it a workable system. This demands the coding of design into computer understandable language, i.e., programming language. This is also called the programming phase in which the programmer converts the program specifications into computer instructions, which we refer to as programs. It is an important stage where the defined procedures are transformed into control specifications by the help of a computer language. The programs coordinate the data movements and control the entire process in a system. It is generally felt that the programs

Page 12: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

must be modular in nature. This helps in fast development, maintenance and future changes, if required.

(g) Testing

Before actually implementing the new system into operation, a test run of the system is done for removing the bugs, if any. It is an important phase of a successful system. After codifying the whole programs of the system, a test plan should be developed and run on a given set of test data. The output of the test run should match the expected results. Sometimes, system testing is considered a part of implementation process. Using the test data following test run are carried out:

v Program test v System test

Program test: When the programs have been coded, compiled and brought to working conditions, they must be individually tested with the prepared test data. Any undesirable happening must be noted and debugged (error corrections)

System Test: After carrying out the program test for each of the programs of the system and errors removed, then system test is done. At this stage the test is done on actual data. The complete system is executed on the actual data. At each stage of the execution, the results or output of the system is analyzed. During the result analysis, it may be found that the outputs are not matching the expected output of the system. In such case, the errors in the particular programs are identified and are fixed and further tested for the expected output.

When it is ensured that the system is running error-free, the users are called with their own actual data so that the system could be shown running as per their requirements.

(h) Implementation

After having the user acceptance of the new system developed, the implementation phase begins. Implementation is the stage of a project during which theory is turned into practice. The major steps involved in this phase are:

v Acquisition and Installation of Hardware and Software v Conversion v User Training v Documentation

The hardware and the relevant software required for running the system must be made fully operational before implementation. The conversion is also one of the most critical and expensive activities in the system development life cycle. The data from the old system needs to be converted to operate in the new format of the new system. The database needs to be setup with security and recovery procedures fully defined.

Page 13: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

During this phase, all the programs of the system are loaded onto the user’s computer. After loading the system, training of the user starts. Main topics of such type of training are:

v How to execute the package v How to enter the data v How to process the data (processing details) v How to take out the reports

After the users are trained about the computerized system, working has to shift from manual to computerized working. The process is called ‘Changeover’. The following strategies are followed for changeover of the system.

(I) Direct Changeover: This is the complete replacement of the old system by the new system. It is a risky approach and requires comprehensive system testing and training.

(ii) Parallel run: In parallel run both the systems, i.e., computerized and manual, are executed simultaneously for certain defined period. The same data is processed by both the systems. This strategy is less risky but more expensive because of the following:

v Manual results can be compared with the results of the computerized system. The operational work is doubled.

v Failure of the computerized system at the early stage does not affect the working of the organization, because the manual system continues to work, as it used to do.

(iii) Pilot run: In this type of run, the new system is run with the data from one or more of the previous periods for the whole or part of the system. The results are compared with the old system results. It is less expensive and risky than parallel run approach. This strategy builds the confidence and the errors are traced easily without affecting the operations. The documentation of the system is also one of the most important activities in the system development life cycle. This ensures the continuity of the system. There are generally two types of documentation prepared for any system. These are:

v User or Operator Documentation v System Documentation

The user documentation is a complete description of the system from the user’s point of view detailing how to use or operate the system. It also includes the major error messages likely to be encountered by the users. The system documentation contains the details of system design, programs, their coding, system flow, data dictionary, process description, etc. This helps to understand the system and permit changes to be made in the existing system to satisfy new user needs.

(I) Maintenance

Maintenance is necessary to eliminate errors in the system during its working life and to tune the system to any variations in its working environments. It has been seen that there are always some

Page 14: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

errors found in the systems that must be noted and corrected. It also means the review of the system from time to time. The review of the system is done for:

v knowing the full capabilities of the system v knowing the required changes or the additional requirements v Studying the performance.

If a major change to a system is needed, a new project may have to be set up to carry out the change. The new project will then proceed through all the above life cycle phases.

3) FEASIBILTY STUDY

Feasibility is defined as the practical extent to which a project can be performed successfully. To evaluate feasibility, a feasibility study is performed, which determines whether the solution considered to accomplish the requirements is practical and workable in the software. Information such as resource availability, cost estimation for software development, benefits of the software to the organization after it is developed and cost to be incurred on its maintenance are considered during the feasibility study. The objective of the feasibility study is to establish the reasons for developing the software that is acceptable to users, adaptable to change and conformable to established standards. Various other objectives of feasibility study are listed below.

v To analyze whether the software will meet organizational requirements v To determine whether the software can be implemented using the current technology and

within the specified budget and schedule v To determine whether the software can be integrated with other existing software.

Types of Feasibility

Various types of feasibility that are commonly considered include technical feasibility, operational feasibility, and economic feasibility.

Page 15: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

Technical feasibility assesses the current resources (such as hardware and software) and technology, which are required to accomplish user requirements in the software within the allocated time and budget. For this, the software development team ascertains whether the current resources and technology can be upgraded or added in the software to accomplish specified user requirements. Technical feasibility also performs the following tasks.

v Analyzes the technical skills and capabilities of the software development team members v Determines whether the relevant technology is stable and established v Ascertains that the technology chosen for software development has a large number of users

so that they can be consulted when problems arise or improvements are required.

Operational feasibility assesses the extent to which the required software performs a series of steps to solve business problems and user requirements. This feasibility is dependent on human resources (software development team) and involves visualizing whether the software will operate after it is developed and be operative once it is installed. Operational feasibility also performs the following tasks.

v Determines whether the problems anticipated in user requirements are of high priority v Determines whether the solution suggested by the software development team is acceptable v Analyzes whether users will adapt to a new software v Determines whether the organization is satisfied by the alternative solutions proposed by the

software development team.

Economic feasibility determines whether the required software is capable of generating financial gains for an organization. It involves the cost incurred on the software development team, estimated cost of hardware and software, cost of performing feasibility study, and so on. For this, it is essential to consider expenses made on purchases (such as hardware purchase) and activities required to carry out software development. In addition, it is necessary to consider the benefits that can be achieved by developing the software. Software is said to be economically feasible if it focuses on the issues listed below.

v Cost incurred on software development to produce long-term gains for an organization v Cost required to conduct full software investigation (such as requirements elicitation and

requirements analysis) v Cost of hardware, software, development team, and training.

Feasibility Study Process

Feasibility study comprises the following steps.

1. Information assessment: Identifies information about whether the system helps in achieving the objectives of the organization. It also verifies that the system can be implemented using

Page 16: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

new technology and within the budget and whether the system can be integrated with the existing system.

2. Information collection: Specifies the sources from where information about software can be obtained. Generally, these sources include users (who will operate the software), organization (where the software will be used), and the software development team (which understands user requirements and knows how to fulfill them in software).

3. Report writing: Uses a feasibility report, which is the conclusion of the feasibility study by the software development team. It includes the recommendations whether the software development should continue. This report may also include information about changes in the software scope, budget, and schedule and suggestions of any requirements in the system.

4. General information: Describes the purpose and scope of feasibility study. It also describes system overview, project references, acronyms and abbreviations, and points of contact to be used. System overview provides description about the name of the organization responsible for the software development, system name or title, system category, operational status, and so on. Project references provide a list of the references used to prepare this document such as documents relating to the project or previously developed documents that are related to the project. Acronyms and abbreviations provide a list of the terms that are used in this document along with their meanings. Points of contact provide a list of points of organizational contact with users for information and coordination. For example, users require assistance to solve problems (such as troubleshooting) and collect information such as contact number, e-mail address, and so on.

5. Management summary: Provides the following information. 6. Environment: Identifies the individuals responsible for software development. It provides

information about input and output requirements, processing requirements of the software and the interaction of the software with other software. It also identifies system security requirements and the system's processing requirements

7. Current functional procedures: Describes the current functional procedures of the existing system, whether automated or manual. It also includes the data-flow of the current system and the number of team members required to operate and maintain the software.

8. Functional objective: Provides information about functions of the system such as new services, increased capacity, and so on.

9. Performance objective: Provides information about performance objectives such as reduced staff and equipment costs, increased processing speeds of software, and improved controls.

10. Assumptions and constraints: Provides information about assumptions and constraints such as operational life of the proposed software, financial constraints, changing hardware, software and operating environment, and availability of information and sources.

11. Methodology: Describes the methods that are applied to evaluate the proposed software in order to reach a feasible alternative. These methods include survey, modeling, benchmarking, etc.

Page 17: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

12. Evaluation criteria: Identifies criteria such as cost, priority, development time, and ease of system use, which are applicable for the development process to determine the most suitable system option.

13. Recommendation: Describes a recommendation for the proposed system. This includes the delays and acceptable risks.

14. Proposed software: Describes the overall concept of the system as well as the procedure to be used to meet user requirements. In addition, it provides information about improvements, time and resource costs, and impacts. Improvements are performed to enhance the functionality and performance of the existing software. Time and resource costs include the costs associated with software development from its requirements to its maintenance and staff training. Impacts describe the possibility of future happenings and include various types of impacts as listed below.

15. Equipment impacts: Determine new equipment requirements and changes to be made in the currently available equipment requirements.

16. Software impacts: Specify any additions or modifications required in the existing software and supporting software to adapt to the proposed software.

17. Organizational impacts: Describe any changes in organization, staff and skills requirement. 18. Operational impacts: Describe effects on operations such as user-operating procedures, data

processing, data entry procedures, and so on. 19. Developmental impacts: Specify developmental impacts such as resources required to

develop databases, resources required to develop and test the software, and specific activities to be performed by users during software development.

20. Security impacts: Describe security factors that may influence the development, design, and continued operation of the proposed software.

21. Alternative systems: Provide description of alternative systems, which are considered in a feasibility study. This also describes the reasons for choosing a particular alternative system to develop the proposed software and the reason for rejecting alternative systems

Decision Trees

OVERVIEW

A decision tree is a flowchart-like structure in which each internal node represents a "test" on an attribute (e.g. whether a coin flip comes up heads or tails), each branch represents the outcome of the test, and each leaf node represents a class label (decision taken after computing all attributes). The paths from root to leaf represent classification rules.

Page 18: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

In decision analysis, a decision tree and the closely related influence diagram are used as a visual and analytical decision support tool, where the expected values (or expected utility) of competing alternatives are calculated. A decision tree consists of three types of nodes:

1. Decision nodes – typically represented by squares 2. Chance nodes – typically represented by circles 3. End nodes – typically represented by triangles

Decision trees are commonly used in operations research and operations management. If, in practice, decisions have to be taken online with no recall under incomplete knowledge, a decision tree should be paralleled by a probability model as a best choice model or online selection model algorithm. Another use of decision trees is as a descriptive means for calculating conditional probabilities. Decision trees, influence diagrams, utility functions, and other decision analysis tools and methods are taught to undergraduate students in schools of business, health economics, and public health, and are examples of operations research or management science methods.

DECISION TREE BUILDING BLOCKS DECISION TREE ELEMENTS

Drawn from left to right, a decision tree has only burst nodes (splitting paths) but no sink nodes (converging paths). Therefore, used manually, they can grow very big and are then often hard to draw fully by hand. Traditionally, decision trees have been created manually — as the aside example shows — although increasingly, specialized software is employed. DECISION RULES

The decision tree can be linearized into decision rules,[1] where the outcome is the contents of the leaf node, and the conditions along the path form a conjunction in the if clause. In general, the rules have the form:

if condition1 and condition2 and condition3 then outcome.

Page 19: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

Decision rules can be generated by constructing association rules with the target variable on the right. They can also denote temporal or causal relations.[2] DECISION TREE USING FLOWCHART SYMBOLS

Commonly a decision tree is drawn using flowchart symbols as it is easier for many to read and understand.

ANALYSIS EXAMPLE

Analysis can take into account the decision maker's (e.g., the company's) preference or utility function, for example:

Page 20: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

The basic interpretation in this situation is that the company prefers B's risk and payoffs under realistic risk preference coefficients (greater than $400K—in that range of risk aversion, the company would need to model a third strategy, "Neither A nor B"). INFLUENCE DIAGRAM

Much of the information in a decision tree can be represented more compactly as an influence diagram, focusing attention on the issues and relationships between events.

The rectangle on the left represents a decision, the ovals represent actions, and the diamond represents results.

Page 21: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

ASSOCIATION RULE INDUCTION

DECISION TREES CAN ALSO BE SEEN AS GENERATIVE MODELS OF INDUCTION RULES

FROM EMPIRICAL DATA. AN OPTIMAL DECISION TREE IS THEN DEFINED AS A TREE THAT

ACCOUNTS FOR MOST OF THE DATA, WHILE MINIMIZING THE NUMBER OF LEVELS (OR

"QUESTIONS").[3] SEVERAL ALGORITHMS TO GENERATE SUCH OPTIMAL TREES HAVE

BEEN DEVISED, SUCH AS ID3/4/5,[4] CLS, ASSISTANT, AND CART.

ADVANTAGES AND DISADVANTAGES

Among decision support tools, decision trees (and influence diagrams) have several advantages. Decision trees:

• Are simple to understand and interpret. People are able to understand decision tree models after a brief explanation.

• Have value even with little hard data. Important insights can be generated based on experts describing a situation (its alternatives, probabilities, and costs) and their preferences for outcomes.

• Allow the addition of new possible scenarios • Help determine worst, best and expected values for different scenarios • Use a white box model. If a given result is provided by a model. • Can be combined with other decision techniques. Disadvantages of decision trees:

• For data including categorical variables with different number of levels, information gain in decision trees are biased in favor of those attributes with more levels.

• Calculations can get very complex particularly if many values are uncertain and/or if many outcomes are linked.

Decision Tables

Decision tables are a precise yet compact way to model complex rule sets and their corresponding actions. Decision tables, like flowcharts, if-then-else, and switch-case statements, associate conditions with actions to perform, but in many cases do so in a more elegant way. In the 1960s and 1970s a range of "decision table based" languages such as File tab were popular for business programming.

Page 22: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

Each decision corresponds to a variable, relation or predicate whose possible values are listed among the condition alternatives. Each action is a procedure or operation to perform, and the entries specify whether (or in what order) the action is to be performed for the set of condition alternatives the entry corresponds to. Many decision tables include in their condition alternatives the don't care symbol, a hyphen. Using don't cares can simplify decision tables, especially when a given condition has little influence on the actions to be performed. In some cases, entire conditions thought to be important initially are found to be irrelevant when none of the conditions influence which actions are performed. Aside from the basic four quadrant structure, decision tables vary widely in the way the condition alternatives and action entries are represented.Some decision tables use simple true/false values to represent the alternatives to a condition (similar to if-then-else), other tables may use numbered alternatives (similar to switch-case), and some tables even use fuzzy logic or probabilistic representations for condition alternatives.[3] In a similar way, action entries can simply represent whether an action is to be performed (check the actions to perform), or in more advanced decision tables, the sequencing of actions to perform (number the actions to perform).

EXAMPLE The limited-entry decision table is the simplest to describe. The condition alternatives are simple Boolean values, and the action entries are check-marks, representing which of the actions in a given column are to be performed.

A technical support company writes a decision table to diagnose printer problems based upon symptoms described to them over the phone from their clients.

The following is a balanced decision table (created by Systems Made Simple).

Printer troubleshooter

Rules

Conditions

Printer prints N N N N Y Y Y Y

A red light is flashing Y Y N N Y Y N N

Printer is recognized by computer N Y N Y N Y N Y

Page 23: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

Actions

Check the power cable X

Check the printer-computer cable X X

Ensure printer software is installed X X X X

Check/replace ink X X X X

Check for paper jam X X

Of course, this is just a simple example (and it does not necessarily correspond to the reality of printer troubleshooting), but even so, it demonstrates how decision tables can scale to several conditions with many possibilities.

Page 24: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

Unit -2

Introduction to RDBMS

A relational DBMS stores information in a set of "tables", each of which has a unique identifier or "primary key". The tables are then related to one another using "foreign keys". A foreign key is simply the primary key in a different table. Diagrammatically, a foreign key is depicted as a line with an arrow at one end.

In the example below, "Customer ID" is the primary key (PK) in one table and the foreign key (FK) in another. The arrow represents a one-to-many relationship between the two tables. The relationship indicates that one customer can have one or more orders. A given order, however, can be initiated by one and only one customer.

By storing data in a RDBMS, undesirable data redundancy can be avoided. This not only makes data management easier, but it also makes for a flexible database that can respond to changing requirements.

Example of a Relational Database

2. Codd’s Rules

Dr Edgar F. Codd, after his extensive research on the Relational Model of database systems, came

up with twelve rules of his own, which according to him, a database must obey in order to be

regarded as a true relational database.

Page 25: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

These rules can be applied on any database system that manages stored data using only its relational

capabilities. This is a foundation rule, which acts as a base for all the other rules.

RULE 1: INFORMATION RULE

The data stored in a database, may it be user data or metadata, must be a value of some table cell.

Everything in a database must be stored in a table format.

RULE 2: GUARANTEED ACCESS RULE

Every single data element (value) is guaranteed to be accessible logically with a combination of

table-name, primary-key (row value), and attribute-name (column value). No other means, such as

pointers, can be used to access data.

RULE 3: SYSTEMATIC TREATMENT OF NULL VALUES

The NULL values in a database must be given a systematic and uniform treatment. This is a very

important rule because a NULL can be interpreted as one the following − data is missing, data is not

known, or data is not applicable.

RULE 4: ACTIVE ONLINE CATALOG

The structure description of the entire database must be stored in an online catalog, known as data

dictionary, which can be accessed by authorized users. Users can use the same query language to

access the catalog which they use to access the database itself.

RULE 5: COMPREHENSIVE DATA SUB-LANGUAGE RULE

A database can only be accessed using a language having linear syntax that supports data definition,

data manipulation, and transaction management operations. This language can be used directly or

by means of some application. If the database allows access to data without any help of this language,

then it is considered as a violation.

Page 26: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

RULE 6: VIEW UPDATING RULE

All the views of a database, which can theoretically be updated, must also be updatable by the

system.

RULE 7: HIGH-LEVEL INSERT, UPDATE, AND DELETE RULE

A database must support high-level insertion, updation, and deletion. This must not be limited to a

single row, that is, it must also support union, intersection and minus operations to yield sets of data

records.

RULE 8: PHYSICAL DATA INDEPENDENCE

The data stored in a database must be independent of the applications that access the database. Any

change in the physical structure of a database must not have any impact on how the data is being

accessed by external applications.

RULE 9: LOGICAL DATA INDEPENDENCE

The logical data in a database must be independent of its user’s view (application). Any change in

logical data must not affect the applications using it. For example, if two tables are merged or one

is split into two different tables, there should be no impact or change on the user application. This is

one of the most difficult rule to apply.

RULE 10: INTEGRITY INDEPENDENCE

A database must be independent of the application that uses it. All its integrity constraints can be

independently modified without the need of any change in the application. This rule makes a

database independent of the front-end application and its interface.

RULE 11: DISTRIBUTION INDEPENDENCE

Page 27: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

The end-user must not be able to see that the data is distributed over various locations. Users should

always get the impression that the data is located at one site only. This rule has been regarded as the

foundation of distributed database systems.

RULE 12: NON-SUBVERSION RULE

If a system has an interface that provides access to low-level records, then the interface must not be

able to subvert the system and bypass security and integrity constraints.

3. Data Integrity

When we are designing a database, there is lot of factors to be concentrated on. We need to make

sure that all the required datas are distributed among right tables and there is no duplication/missing

data. The space utilised for the appropriately for the database. Time taken for each query is minimal

and so on.

Imagine we have a STUDENT table with Student details and the subjects that he has opted for. If

we observe the table below, Joseph has opted for two subjects - Mathematics and Physics. That is

fine. But what is wrong in below table? His address is repeated each time, which is not necessary

and waste of space. This is called redundancy and is not allowed in a database.

Similarly, if we have to insert one more record for Allen, then we have to enter all his details into

the above table. But what is the guarantee that all his details are entered correctly? There could be a

mistake and hence leading to mismatch in his details. But who will later say which entry is correct?

No one! Hence the data in DB is wrong.

Page 28: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

Same issue can happen when we update the data. If we update address one of the record, and leave

other record for Joseph above, again a data mismatch.

And when we delete a data, say for Chris, who is having only one entry, whole of his information is

lost!

Imagine there are two entities - Employee and Department, and they are not properly related by

means of foreign key. What would be the result? We can enter as many department as we want to

an employee for whom department may not exists at all in Department table! So mapping the tables

appropriately is also a very important factor.

Data integrity ensures, all the above mentioned issues are not injected into the database while it is

designed. It guarantees that database is perfect and complete.

Types of Integrity Constraints

There are five types of data integrity constraints

Domain Constraint

Here each columns of a table are verified so that correct data is entered into column. For example,

numeric data is entered into a NUMBER column and not any character. In a DATE column, correct

dates are entered and not any invalid values.

Imagine we have a table where date fields are stored as character and we have to copy this date field

into a new table where this column is defined as DATE. What happens here is most of the data from

Page 29: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

the original table will not be loaded into new table, as there is mismatch in the data stored. i.e.; the

original table will have dates in 22 March 2015 format which new table will not accept as date. In

the foremost case, if there was domain integrity, original table would not have such dates and would

have preserved the integrity of data in the original table itself.

Entity Integrity

This integrity ensures that each record in the table is unique and has primary key which is not NULL.

That means, there is no duplicate record or information of data in a table and each records are

uniquely identified by non null attribute of the table.

In a STUDENT table, each student should be a different from other and there will not be duplicate

records. Also, STUDENT_ID which is a primary key in the table has non-null values for each of the

record.

Column Constraint

This constraint ensures that the values entered into a column are correct by means of business rules.

Say, there is an age column and its value is negative which is not correct. This constraint refines

from entering wrong age. Similar example of such constraint is salary cannot be negative; employee

number will be in a given range etc. These are business rules/requirements that specify what kind of

values could be entered into each column.

Page 30: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

This constraint is different from domain constraint as here it checks for the validity of the data being

entered- like correct age is being entered; Correct Employee Id is entered etc. In the domain

constraint, it checks, whether correct set of data being is entered - like Date is entered into data

column, Number is entered into number column etc.

User-Defined Integrity Constraint

Imagine, while entering a salary of an employee, we need to check if his salary is less than his

manager. Though this is similar to column constraint, we cannot direct insist this constraint on the

column as the system does not know who his manager is. We need to check for his manager's salary

first, if it is more than his employer, then we will insert the data. For this we manually need to write

code. This kind of constraints is called User-Defined Integrity Constraint.

Referential Integrity

As we discussed for Employee and Department tables, if they are not mapped correctly, there would

be a data mismatch. It will allow us to enter a department for an employee which does not exist. It

will allow us to delete a department for which employees are working. What would be the result?

Employees without any department are not correct. Or updating any department number in the

employee table will result in a department which does not exist at all. All these cases will lead to

mismatch and invalid data in the database.

Page 31: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

Hence to ensure above all cases are met, proper relationship has to be defined between the related

tables by means of primary and foreign keys. i.e.; every foreign key in the table should be a primary

key in the related table.

In our example, DEPARTMENT_ID should be a primary key in Department table and it should be

a foreign key in the Employee table. This will stop entering/updating a department which does not

exists. It will not allow us to delete any department from the Department table for which employees

still exists in Employee table.

4. Data Consistency

Data Consistency Explained by Mike Smith, Recovery Specialties 1 2 3 4 Next Data Consistency

issues relevent to Disaster Recovery and Business Continuity issues for the large systems

environment

Data Consistency refers to the usability of data and is often taken for granted in the single site

environment. Data Consistency problems may arise even in a single-site environment during

recovery situations when backup copies of the production data are used in place of the original data.

In order to ensure that your backup data is useable, it is necessary to understand the backup

methodologies that are in place as well as how the primary data is created and accessed. Another

very important consideration is the consistency of the data once the recovery has been completed

and the application is ready to begin processing.

Page 32: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

In order to appreciate the integrity of your data, it is important to understand the dependent write

process. This occurs within individual programs, applications, application systems and databases. A

dependent write is a data update that is not to be written until a previous update has been successfully

completed. In the large systems environments, the logic that determines the sequence in which

systems issue “writes” is controlled by the application processing flow and supported by basic

system functions.

Considering just the local-site z/OS “production” data for a moment, the consistency of this local

data is ensured by a number of protective mechanisms – beginning with ENQ, Reserve/Release,

various modes of database functionality as well as the overall timing of the application writes.

Usually, when data is to be written, control is passed from the application program to system

subroutines to perform the actual write. Once the write has completed, control is returned to the

application and processing continues.

This process provides an inherent synchronization and guarantees that record A has been

successfully written before the write I/O of record B can be issued by the application.

By and large we take these synchronization features for granted and do not give much thought to

how they all work together to protect both the integrity and consistency of the data. It is the integrity

of the data and various systems that allows applications to restart after a power failure or other

unscheduled event.

There are various kinds of data consistency to be considered. These include Point-in-Time (PiT)

Consistency, Transaction Consistency and Application Consistency.

Page 33: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

Point in Time Consistency

Data is said to be Point in Time consistent if all of the interrelated data components (either a group

of data sets or a set of logical volumes) are as they were at any single instant in time. This type of

consistency can be visualized by picturing a data center that has experienced a power failure. Before

the lights come back on and processing resumes, the data is considered time consistent, due to the

fact that the entire processing environment failed at the same time.

Different types of failures may create a situation where Point in Time consistency is not maintained.

For example, consider the failure of a single logical volume containing data from several

applications. If the only recovery option is to restore that volume from a backup taken sometime

earlier, the data contained on the restored volume is not consistent with the other volumes, and

additional recovery steps must be undertaken.

Transaction Consistency

A transaction is a logical unit of work that may include any number of file or database updates.

During normal processing, transaction consistency is present only before any transactions have run,

following the completion of a successful transaction and before the next transaction begins, and

when the application ends normally or the database is closed.

Following a failure of some kind, the data will not be transaction consistent if transactions were in-

flight at the time of the failure. In most cases what occurs is that once the application or database is

restarted, the incomplete transactions are identified and the updates relating to these transactions are

either “backed-out” or processing resumes with the next dependant write.

Page 34: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

Application Consistency

Application Consistency is similar to Transaction consistency, but on a grander scale. Instead of data

consistency within the scope of a single transaction, data must be consistent within the confines of

many different transaction streams from one or more applications.

An application may be made up of many different types of data, such as multiple database

components, various types of files, and data feeds from other applications. Application consistency

is the state in which all related files and databases are in-synch and represent the true status of the

application.

5. Problems in Normalization

Normalization

Normalization is a set of rules/guidelines/technique that is used while designing a database. These rules help to remove all the anomalies and distribute the data among different related tables and query them efficiently and effectively. It removes all the duplication issues and incorrect data issues, helping to have a well designed database. Normalization is divided into following normal forms:

1. First Normal Form (1NF) 2. Second Normal Form (2NF) 3. Third Normal Form (3NF) 4. Boyce-Codd Normal Form (3.5NF) 5. Forth Normal Form (4NF) 6. Fifth Normal Form (5NF)

First Normal Form (1NF)

A table is said to be in First Normal Form (1NF) if and only if each attribute of the relation is atomic. That is,

Page 35: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

• Each row in a table should be identified by primary key (a unique column value or group of unique column values)

• No rows of data should have repeating group of column values.

Let's consider the STUDENT table with his ID, Name address and 2 subjects that he has opted for.

• Look at Chris entry. He has only subject. Hence Subject2 for him is NULL. Here storage space for second entry is simply wasted.

• In the case of Joseph, he has two subjects, Mathematics and Physics, both the columns have values. Imagine if he opts for third subject? There is no column for his third entry. In this case, whole table needs to be altered, which is not good at this stage. Once database is designed, it should be a perfect one. We should not be modifying it as we start adding/updating data.

• One of the requirements of 1NF is, each table should have primary key. This key in the table makes each record unique. In our example we have it already- STUDENT_ID.

• Here, SUBJECT1 and SUBJECT2 are same set of columns, i.e.; it has same kind of information stored - Subject, which is a violation of first rule of 1NF. As it states, there should not be any repeating columns. We have to remove such columns. But think how?

In order to have STUDENT in 1NF, we have to remove multiple SUBJECT columns from STUDENT table. Instead, create only one SUBJECT column, and for each STUDENT enters as many rows as SUBJECT he has. After making this change, the above table will change as follows:

Now STUDENT_ID alone cannot be a primary key, because it does not uniquely determines each record in the table. If we want to records for Joseph, and we query by his ID,100, gives us two records. Hence Student_ID is no more a primary key. When we observe the data in the table, all the four field uniquely determines each record. Hence all four fields together considered as primary key.

Thus, the above table is in 1NF form.

Second Normal Form (2NF)

A relation is said to be in a second normal form if and only if,

Page 36: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

• it's in first normal form

• Every non-key attributes are identified by the use of primary key

• All subset of data, which applies to have multiple rows in a table must be removed and placed in a new table. And this new table and the parent table should be related by the use of foreign key.

In the 1NF STUDENT table above, Joseph and Allen have multiple rows because of their SUBJECTS. Although it is in 1NF form, it wastes storage space by repeating whole of their information - name and address in each row. In addition, Student ID alone is strong enough to be a primary key. If we make Student_ID as primary, all other attributes in the table cannot be uniquely identified. This is because of multiple rows exists for single ID. Hence it does not satisfy second condition of 2NF.

So what we can do here is, apply the third condition of 2NF. Remove Subject from the STUDENT table and create a separate table for it. So the two tables are - STUDENT and SUBJECT. Now the STUDENT table will have only STUDENT information - STUDENT_ID, STUDENT_NAME and ADDRESS. New SUBJECT table will have STUDENT_ID and SUBJECT_NAME.

Now there is no repeating group of columns in STUDENT table and STUDENT_ID is the primary key of STUDENT table. It uniquely identifies the Student name and address which are non key attributes of this table. Hence it satisfies both 1NF and 2NF.

In the new SUBJECT table, Subject names opted by each student. Since same student cannot opt for same subject multiple times in academic year, there will not be any duplicity of data. But Student_ID alone is not unique; hence it cannot be a primary key. Both Student_ID and Subject_Name is unique in this table. Hence both of them together become a primary key. Hence SUBJECT table satisfies 1NF.

There is no non-key attributes in SUBJECT table. Hence we cannot verify second condition of 2NF. According to the third condition of 2NF, we have removed the data which is forming multiple rows and put those details in new table. It also states that there should be relationship between the original table and new table by using foreign key constraint. In the SUBJECT table, STUDENT_ID is derived from STUDENT table. In this table, STUDENT _ID is part of primary key as well as it is a foreign key. Hence we can easily relate both STUDENT and SUBJECT table by using STUDENT_ID. Hence satisfies the third condition of 2NF.

Page 37: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

If we want to know which all subjects Joseph has opted for, we would query as below:

Third Normal Form (3NF)

For a relation to be in third normal form:

• it should meet all the requirements of both 1NF and 2NF

• If there is any columns which are not related to primary key, then remove them and put it in a separate table, relate both the table by means of foreign key i.e.; there should not be any transitive dependency.

Let’s add three more columns - STREET, CITY and ZIP to STUDENT table to explain 3NF. Below is the table satisfies conditions for 2NF - there is primary key, no repeating columns, no duplicate datas.

Here, STREET and CITY have no relation with Student. It's not directly related to student. They fully depend upon zip code. Since Student stays in that area, through zip code, street and city are related to him. This kind of relationship is called transitive dependency. Since its second level of dependency, it is not necessary to store these details in STUDENT table.

Similarly, if there are multiple students staying in same area, STUDENT table is having huge amount of records and there is a change requested for street or city name, then whole STUDENT table needs to be searched and updated. Imagine, we have to update 'Fraser Village Drive' to Fraser Village Dr'. The Update statement would be

UPDATE STUDENT std

SET std.STREET = 'Fraser Village Dr'

WHERE std .STREET = 'Fraser Village Drive';

Above query will search whole student table for 'Fraser Village Drive' and then update it to 'Fraser Village Dr’. But searching a huge table and updating the single or multiple records will be a very time consuming, hence affecting the performance of the database.

Page 38: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

Instead, if we have these details in a separate table ZIPCODE and is related to STUDENT table using zip? However ZIPCODE table will have comparatively less amount of records and we just have to update ZIPCODE table once. It will automatically reflect in the STUDENT table! Hence making the database and query simpler! And table is in 3NF.

UPDATE ZIPCODE z

SET z.STREET = 'Fraser Village Dr'

WHERE z .STREET = 'Fraser Village Drive';

Now if we have to select the whole address of a student, Chris, we join both STUDENT and ZIPCODE table using ZIP and get the whole address.

SELECT std.STUDENT_NAME,

z.STREET,

z.CITY,

z.ZIP

FROM STUDENT std, ZIPCODE z

WHERE std.ZIP = z.ZIP

AND std.STUDENT_NAME = 'Chris';

Boyce-Codd Normal Form (3.5NF)

This normal form is also referred as 3.5 normal forms. This normal form

• Meets all the requirement of 3NF

Page 39: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

• Any table is said to be in BCNF, if its candidate keys do not have any partial dependency on the other attributes. i.e.; in any table with (x, y, z) columns, if (x, y)->z and z->x then it's a violation of BCNF. If (x, y) are composite keys and (x, y)->z, then there should not be any reverse dependency, directly or partially.

In the above 3NF example, STUDENT_ID is the Primary key in STUDENT table and ZIP is the primary key in the ZIPCODE table. There is no other key column in each of the tables which determines the functional dependency. Hence it's in BCNF form. That is, with STUDENT_ID, we can retrieve STUDENT_NAME and ZIP from STUDENT table. Similarly, with ZIP value, we can retrieve STREET and CITY from ZIPCODE table

Let us consider another example - consider each student who has taken major subjects has different advisory lecturers. Each student will have different advisory lecturers for same Subjects. There exists following relationship, which is violation of BCNF.

(STUDENT_ID, MAJOR_SUBJECT) -> ADVISORY_LECTURER

ADVISORY_LECTURER -> MAJOR_SUBJECT

i.e. Major_Subject which is a part of composite candidate key is determined non-key attribute of the same table, which is against the rule.

Below table will have all the anomalies too. If we delete any student from below table, it deletes lecturer's information too. If we add any new lecturer/student to the database, it needs other related information also. Also, if we update subject for any student, his lecturer info also needs to be changed, else it will lead to inconsistency.

Hence we need to decompose the table so that eliminates so that it eliminates such relationship. Now in the new tables below, there are no inter-dependent composite keys (moreover, there is no composite key in both the tables). If we need to add/update/delete any lecturer, we can directly insert record into STUDENT_ADVISOR table, without affecting STUDENT_MAJOR table. If we need to insert/update/delete any subject for a student, then we can directly do it on STUDENT_MAJOR table, without affecting STUDENT_ADVISOR table. When we have both advisor as well as major subject information, then we can directly add/update both the tables. Hence we have eliminated all the anamolies in the database.

Page 40: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

Fourth Normal Form (4NF)

In the fourth normal form,

• It should meet all the requirement of 3NF

• Attribute of one or more rows in the table should not result in more than one rows of the same table leading to multi-valued dependencies

To understand it clearly, consider a table with Subject, Lecturer who teaches each subject and recommended Books for each subject.

If we observe the data in the table above it satisfies 3NF. But LECTURER and BOOKS are two independent entities here. There is no relationship between Lecturer and Books. In the above example, either Alex or Bosco can teach Mathematics. For Mathematics subject , student can refer either 'Maths Book1' or 'Maths Book2'. i.e.;

SUBJECT --> LECTURER

SUBJECT-->BOOKS

This is a multivalued dependency on SUBJECT. If we need to select both lecturer and books recommended for any of the subject, it will show up (lecturer, books) combination, which implies lecturer who recommends which book. This is not correct.

SELECT c.LECTURER, c.BOOKS FROM COURSE c WHERE SUBJECT = 'Mathematics';

To eliminate this dependency, we divide the table into two as below:

Now if we want to know the lecturer names and books recommended for any of the subject, we will fire two independent queries. Hence it removes the multi-valued dependency and confusion around the data. Thus the table is in 4NF.

Page 41: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

--Select the lecturer names

SELECT c.SUBJECT , c.LECTURER FROM COURSE c WHERE c.SUBJECT = 'Mathematics';

--Select the recommended book names

SELECT c.SUBJECT , c.BOOKS FROM COURSE c WHERE c.SUBJECT = 'Mathematics';

Fifth Normal Form (5NF)

A database is said to be in 5NF, if and only if,

• It's in 4NF

• If we can decompose table further to eliminate redundancy and anomaly, and when we re-join the decomposed tables by means of candidate keys, we should not be losing the original data or any new record set should not arise. In simple words, joining two or more decomposed table should not lose records nor create new records.

Consider an example of different Subjects taught by different lecturers and the lecturers taking classes for different semesters.

Note: Please consider that Semester 1 has Mathematics, Physics and Chemistry and Semester 2 has only Mathematics in its academic year!!

In above table, Rose takes both Mathematics and Physics class for Semester 1, but she does not take Physics class for Semester 2. In this case, combination of all these 3 fields is required to identify a valid data. Imagine we want to add a new class - Semester3 but do not know which Subject and who will be taking that subject. We would be simply inserting a new entry with Class as Semester3 and leaving Lecturer and subject as NULL. As we discussed above, it's not a good to have such entries. Moreover, all the three columns together act as a primary key, we cannot leave other two columns blank!

Hence we have to decompose the table in such a way that it satisfies all the rules till 4NF and when join them by using keys, it should yield correct record. Here, we can represent each lecturer's

Page 42: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

Subject area and their classes in a better way. We can divide above table into three - (SUBJECT, LECTURER), (LECTURER, CLASS), (SUBJECT, CLASS)

Now, each of combinations is in three different tables. If we need to identify who is teaching which subject to which semester, we need join the keys of each table and get the result.

For example, who teaches Physics to Semester 1, we would be selecting Physics and Semester1 from table 3 above, join with table1 using Subject to filter out the lecturer names. Then join with table2 using Lecturer to get correct lecturer name. That is we joined key columns of each table to get the correct data. Hence there is no lose or new data - satisfying 5NF condition.

6. Entity Relation(ER) Modeling

The ER model defines the conceptual view of a database. It works around real-world entities and the associations among them. At view level, the ER model is considered a good option for designing databases.

ENTITY

An entity can be a real-world object, either animate or inanimate, that can be easily identifiable. For example, in a school database, students, teachers, classes, and courses offered can be considered as entities. All these entities have some attributes or properties that give them their identity.

An entity set is a collection of similar types of entities. An entity set may contain entities with attribute sharing similar values. For example, a Students set may contain all the students of a school; likewise a Teachers set may contain all the teachers of a school from all faculties. Entity sets need not be disjoint.

ATTRIBUTES

Entities are represented by means of their properties, called attributes. All attributes have values. For example, a student entity may have name, class, and age as attributes.

There exists a domain or range of values that can be assigned to attributes. For example, a student's name cannot be a numeric value. It has to be alphabetic. A student's age cannot be negative, etc.

TYPES OF ATTRIBUTES

Page 43: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

• Simple attribute − Simple attributes are atomic values, which cannot be divided further. For example, a student's phone number is an atomic value of 10 digits.

• Composite attribute − Composite attributes are made of more than one simple attribute. For example, a student's complete name may have first_name and last_name.

• Derived attribute − Derived attributes are the attributes that do not exist in the physical database, but their values are derived from other attributes present in the database. For example, average_salary in a department should not be saved directly in the database, instead it can be derived. For another example, age can be derived from data_of_birth.

• Single-value attribute − Single-value attributes contain single value. For example − Social_Security_Number.

• Multi-value attribute − Multi-value attributes may contain more than one values. For example, a person can have more than one phone number, email_address, etc.

These attribute types can come together in a way like −

• simple single-valued attributes

• simple multi-valued attributes

• composite single-valued attributes

• composite multi-valued attributes

ENTITY-SET AND KEYS

Key is an attribute or collection of attributes that uniquely identifies an entity among entity set.

For example, the roll_number of a student makes him/her identifiable among students.

• Super Key − A set of attributes (one or more) that collectively identifies an entity in an entity set.

• Candidate Key − A minimal super key is called a candidate key. An entity set may have more than one candidate key.

• Primary Key − A primary key is one of the candidate keys chosen by the database designer to uniquely identify the entity set.

RELATIONSHIP

Page 44: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

The association among entities is called a relationship. For example, an employee works_at a department, a student enrolls in a course. Here, Works_at and Enrolls are called relationships.

RELATIONSHIP SET

A set of relationships of similar type is called a relationship set. Like entities, a relationship too can have attributes. These attributes are called descriptive attributes.

DEGREE OF RELATIONSHIP

The number of participating entities in a relationship defines the degree of the relationship.

• Binary = degree 2

• Ternary = degree 3

• n-ary = degree

MAPPING CARDINALITIES

Cardinality defines the number of entities in one entity set, which can be associated with the number of entities of other set via relationship set.

• One-to-one − One entity from entity set A can be associated with at most one entity of entity set B and vice versa.

• One-to-many − One entity from entity set A can be associated with more than one entities of entity set B however an entity from entity set B, can be associated with at most one entity.

Page 45: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

• Many-to-one − More than one entities from entity set A can be associated with at most one entity of entity set B, however an entity from entity set B can be associated with more than one entity from entity set A.

• Many-to-many − One entity from A can be associated with more than one entity from B and vice versa.

Page 46: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

Relational Model

Relational data model is the primary data model, which is used widely around the world for data

storage and processing. This model is simple and it has all the properties and capabilities required

to process data with storage efficiency.

CONCEPTS

Tables − In relational data model, relations are saved in the format of Tables. This format stores the

relation among entities. A table has rows and columns, where rows represents records and columns

represent the attributes.

Tuple − A single row of a table, which contains a single record for that relation is called a tuple.

Relation instance − A finite set of tuples in the relational database system represents relation

instance. Relation instances do not have duplicate tuples.

Relation schema − A relation schema describes the relation name (table name), attributes, and their

names.

Page 47: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

Relation key − Each row has one or more attributes, known as relation key, which can identify the

row in the relation (table) uniquely.

Attribute domain − Every attribute has some pre-defined value scope, known as attribute domain.

CONSTRAINTS

Every relation has some conditions that must hold for it to be a valid relation. These conditions are

called Relational Integrity Constraints. There are three main integrity constraints −

• Key constraints

• Domain constraints

• Referential integrity constraints

KEY CONSTRAINTS

There must be at least one minimal subset of attributes in the relation, which can identify a tuple

uniquely. This minimal subset of attributes is called key for that relation. If there are more than one

such minimal subsets, these are called candidate keys.

Key constraints force that −

• in a relation with a key attribute, no two tuples can have identical values for key attributes.

• a key attribute can not have NULL values.

Key constraints are also referred to as Entity Constraints.

DOMAIN CONSTRAINTS

Page 48: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

Attributes have specific values in real-world scenario. For example, age can only be a positive

integer. The same constraints have been tried to employ on the attributes of a relation. Every attribute

is bound to have a specific range of values. For example, age cannot be less than zero and telephone

numbers cannot contain a digit outside 0-9.

REFERENTIAL INTEGRITY CONSTRAINTS

Referential integrity constraints work on the concept of Foreign Keys. A foreign key is a key

attribute of a relation that can be referred in other relation.

Referential integrity constraint states that if a relation refers to a key attribute of a different or same

relation, then that key element must exist.

Relational Algebra

Relational database systems are expected to be equipped with a query language that can assist its

users to query the database instances. There are two kinds of query languages − relational algebra

and relational calculus.

RELATIONAL ALGEBRA

Relational algebra is a procedural query language, which takes instances of relations as input and

yields instances of relations as output. It uses operators to perform queries. An operator can be

either unary or binary. They accept relations as their input and yield relations as their output.

Relational algebra is performed recursively on a relation and intermediate results are also considered

relations.

The fundamental operations of relational algebra are as follows −

Page 49: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

• Select

• Project

• Union

• Set different

• Cartesian product

• Rename

We will discuss all these operations in the following sections.

SELECT OPERATION (Σ)

It selects tuples that satisfy the given predicate from a relation.

Notation − σp(r)

Where σ stands for selection predicate and r stands for relation. p is prepositional logic formula

which may use connectors like and, or, and not. These terms may use relational operators like −

=, ≠, ≥, < , >, ≤.

For example −

σsubject = "database"(Books)

Output − Selects tuples from books where subject is 'database'.

σsubject = "database" and price = "450"(Books)

Output − Selects tuples from books where subject is 'database' and 'price' is 450.

Page 50: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

σsubject = "database" and price = "450" or year > "2010"(Books)

Output − Selects tuples from books where subject is 'database' and 'price' is 450 or those books

published after 2010.

PROJECT OPERATION (∏)

It projects column(s) that satisfy a given predicate.

Notation − ∏A1, A2, An (r)

Where A1, A2 , An are attribute names of relation r.

Duplicate rows are automatically eliminated, as relation is a set.

For example −

∏subject, author (Books)

Selects and projects columns named as subject and author from the relation Books.

UNION OPERATION (∪)

It performs binary union between two given relations and is defined as −

r ∪ s = { t | t ∈ r or t ∈ s}

Notation − r U s

Where r and s are either database relations or relation result set (temporary relation).

For a union operation to be valid, the following conditions must hold −

• r, and s must have the same number of attributes.

Page 51: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

• Attribute domains must be compatible.

• Duplicate tuples are automatically eliminated.

∏ author (Books) ∪ ∏ author (Articles)

Output − Projects the names of the authors who have either written a book or an article or both.

SET DIFFERENCE (−)

The result of set difference operation is tuples, which are present in one relation but are not in the

second relation.

Notation − r − s

Finds all the tuples that are present in r but not in s.

∏ author (Books) − ∏ author (Articles)

Output − Provides the name of authors who have written books but not articles.

CARTESIAN PRODUCT (Χ)

Combines information of two different relations into one.

Notation − r Χ s

Where r and s are relations and their output will be defined as −

r Χ s = { q t | q ∈ r and t ∈ s}

σauthor = 'tutorialspoint'(Books Χ Articles)

Output − Yields a relation, which shows all the books and articles written by tutorialspoint.

RENAME OPERATION (Ρ)

Page 52: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

The results of relational algebra are also relations but without any name. The rename operation

allows us to rename the output relation. 'rename' operation is denoted with small Greek letter rho ρ.

Notation − ρ x (E)

Where the result of expression E is saved with name of x.

Additional operations are −

• Set intersection

• Assignment

• Natural join

RELATIONAL CALCULUS

In contrast to Relational Algebra, Relational Calculus is a non-procedural query language, that is, it

tells what to do but never explains how to do it.

Relational calculus exists in two forms −

TUPLE RELATIONAL CALCULUS (TRC)

Filtering variable ranges over tuples

Notation − {T | Condition}

Returns all tuples T that satisfies a condition.

For example −

{ T.name | Author(T) AND T.article = 'database' }

Page 53: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

Output − Returns tuples with 'name' from Author who has written article on 'database'.

TRC can be quantified. We can use Existential (∃) and Universal Quantifiers (∀).

For example −

{ R| ∃T ∈ Authors(T.article='database' AND R.name=T.name)}

Output − The above query will yield the same result as the previous one.

DOMAIN RELATIONAL CALCULUS (DRC)

In DRC, the filtering variable uses the domain of attributes instead of entire tuple values (as done in

TRC, mentioned above).

Notation −

{ a1, a2, a3, ..., an | P (a1, a2, a3, ... ,an)}

Where a1, a2 are attributes and P stands for formulae built by inner attributes.

For example −

{< article, page, subject > | ∈ TutorialsPoint ∧ subject = 'database'}

Output − Yields Article, Page, and Subject from the relation TutorialsPoint, where subject is

database.

Just like TRC, DRC can also be written using existential and universal quantifiers. DRC also

involves relational operators.

Page 54: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

The expression power of Tuple Relation Calculus and Domain Relation Calculus is equivalent to

Relational Algebra.

ER Model to Relational Model

ER Model, when conceptualized into diagrams, gives a good overview of entity-relationship, which

is easier to understand. ER diagrams can be mapped to relational schema, that is, it is possible to

create relational schema using ER diagram. We cannot import all the ER constraints into relational

model, but an approximate schema can be generated.

There are several processes and algorithms available to convert ER Diagrams into Relational

Schema. Some of them are automated and some of them are manual. We may focus here on the

mapping diagram contents to relational basics.

ER diagrams mainly comprise of −

• Entity and its attributes

• Relationship, which is association among entities.

MAPPING ENTITY

An entity is a real-world object with some attributes.

MAPPING PROCESS (ALGORITHM)

Page 55: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

• Create table for each entity.

• Entity's attributes should become fields of tables with their respective data types.

• Declare primary key.

MAPPING RELATIONSHIP

A relationship is an association among entities.

MAPPING PROCESS

• Create table for a relationship.

• Add the primary keys of all participating Entities as fields of table with their respective data

types.

• If relationship has any attribute, add each attribute as field of table.

• Declare a primary key composing all the primary keys of participating entities.

• Declare all foreign key constraints.

MAPPING WEAK ENTITY SETS

A weak entity set is one which does not have any primary key associated with it.

Page 56: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

MAPPING PROCESS

• Create table for weak entity set.

• Add all its attributes to table as field.

• Add the primary key of identifying entity set.

• Declare all foreign key constraints.

MAPPING HIERARCHICAL ENTITIES

ER specialization or generalization comes in the form of hierarchical entity sets.

Page 57: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

MAPPING PROCESS

• Create tables for all higher-level entities.

• Create tables for lower-level entities.

• Add primary keys of higher-level entities in the table of lower-level entities.

• In lower-level tables, add all other attributes of lower-level entities.

• Declare primary key of higher-level table and the primary key for lower-level table.

• Declare foreign key constraints.

Page 58: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

Unit-3

Oracle Based Programming Concept

1. What is SQL?

SQL (pronounced "ess-que-el") stands for Structured Query Language. SQL is used to communicate with a database. According to ANSI (American National Standards Institute), it is the standard language for relational database management systems. SQL statements are used to perform tasks such as update data on a database, or retrieve data from a database. Some common relational database management systems that use SQL are: Oracle, Sybase, Microsoft SQL Server, Access, Ingres, etc. Although most database systems use SQL, most of them also have their own additional proprietary extensions that are usually only used on their system. However, the standard SQL commands such as "Select", "Insert",

Page 59: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

"Update", "Delete", "Create", and "Drop" can be used to accomplish almost everything that one needs to do with a database. This tutorial will provide you with the instruction on the basics of each of these commands as well as allow you to put them to practice using the SQL Interpreter.

Structure Query Language(SQL) is a programming language used for storing and managing data in RDBMS. SQL was the first commercial language introduced for E.F Codd's Relational model. Today almost all RDBMS(MySql, Oracle, Infomix, Sybase, MS Access) uses SQL as the standard database language. SQL is used to perform all type of data operations in RDBMS.

SQL Command

SQL defines following data languages to manipulate data of RDBMS.

2. DDL : Data Definition Language

All DDL commands are auto-committed. That means it saves all the changes permanently in the database.

Command Description

create to create new table or database

alter for alteration

truncate delete data from table

drop to drop a table

rename to rename a table

3. DML : Data Manipulation Language

DML commands are not auto-committed. It means changes are not permanent to database, they can be rolled back.

Page 60: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

Command Description

insert to insert a new row

update to update existing row

delete to delete a row

merge merging two rows or two tables

TCL : Transaction Control Language

These commands are to keep a check on other commands and their affect on the database. These commands can annul changes made by other commands by rolling back to original state. It can also make changes permanent.

Command Description

commit to permanently save

rollback to undo change

savepoint to save temporarily

4. DCL : Data Control Language

Data control language provides command to grant and take back authority.

Command Description

Page 61: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

grant grant permission of right

revoke take back permission.

DQL : Data Query Language

Command Description

select retrieve records from one or more table

BASIC SQL STATEMENTS: DDL AND DML

In the first part of this tutorial, you’ve seen some of the SQL statements that you need to start building a database. This page gives you a review of those and adds several more that you haven’t seen yet. • SQL statements are divided into two major categories: data definition language (DDL) and data manipulation language (DML). Both of these categories contain far more statements than we can present here, and each of the statements is far more complex than we show in this introduction. If you want to master this material, we strongly recommend that you find a SQL reference for your own database software as a supplement to these pages.

DATA DEFINITION LANGUAGE

DDL statements are used to build and modify the structure of your tables and other objects in the database. When you execute a DDL statement, it takes effect immediately.

• The create table statement does exactly that: CREATE TABLE <table name> ( <attribute name 1> <data type 1>, ... <attribute name n> <data type n>);

The data types that you will use most frequently are character strings, which might be called VARCHAR or CHAR for variable or fixed length strings; numeric types such as NUMBER or INTEGER, which will usually specify a precision; and DATE or related types. Data type syntax is variable from system to system; the only way to be sure is to consult the documentation for your own software.

• The alter table statement may be used as you have seen to specify primary and foreign key constraints, as well as to make other modifications to the table structure. Key constraints may also be specified in the CREATE TABLE statement.

Page 62: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

ALTER TABLE <table name> ADD CONSTRAINT <constraint name> PRIMARY KEY (<attribute list>);

You get to specify the constraint name. Get used to following a convention of tablename_pk (for example, Customers_pk), so you can remember what you did later. The attribute list contains the one or more attributes that form this PK; if more than one, the names are separated by commas.

• The foreign key constraint is a bit more complicated, since we have to specify both the FK attributes in this (child) table, and the PK attributes that they link to in the parent table.

ALTER TABLE <table name> ADD CONSTRAINT <constraint name> FOREIGN KEY (<attribute list>) REFERENCES <parent table name> (<attribute list>);

Name the constraint in the form childtable_parenttable_fk (for example, Orders_Customers_fk). If there is more than one attribute in the FK, all of them must be included (with commas between) in both the FK attribute list and the REFERENCES (parent table) attribute list. You need a separate foreign key definition for each relationship in which this table is the child.

• If you totally mess things up and want to start over, you can always get rid of any object you’ve created with a drop statement. The syntax is different for tables and constraints.

DROP TABLE <table name>; ALTER TABLE <table name> DROP CONSTRAINT <constraint name>;

This is where consistent constraint naming comes in handy, so you can just remember the PK or FK name rather than remembering the syntax for looking up the names in another table. The DROP TABLE statement gets rid of its own PK constraint, but won’t work until you separately drop any FK constraints (or child tables) that refer to this one. It also gets rid of all data that was contained in the table—and it doesn't even ask you if you really want to do this!

• All of the information about objects in your schema is contained, not surprisingly, in a set of tables that is called the data dictionary. There are hundreds of these tables most database systems, but all of them will allow you to see information about your own tables, in many cases with a graphical interface. How you do this is entirely system-dependent.

DATA MANIPULATION LANGUAGE

DML statements are used to work with the data in tables. When you are connected to most multi-user databases (whether in a client program or by a connection from a Web page script), you are in effect working with a private copy of your tables that can’t be seen by anyone else until you are finished (or tell the system that you are finished). You have already seen the SELECT statement; it is considered to be part of DML even though it just retreives data rather than modifying it. • The insert statement is used, obviously, to add new rows to a table.

INSERT INTO <table name>

Page 63: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

VALUES (<value 1>, ... <value n>); The comma-delimited list of values must match the table structure exactly in the number of attributes and the data type of each attribute. Character type values are always enclosed in single quotes; number values are never in quotes; date values are often (but not always) in the format 'yyyy-mm-dd' (for example, '2006-11-30'). Yes, you will need a separate INSERT statement for every row.

• The update statement is used to change values that are already in a table. UPDATE <table name> SET <attribute> = <expression> WHERE <condition>;

The update expression can be a constant, any computed value, or even the result of a SELECT statement that returns a single row and a single column. If the WHERE clause is omitted, then the specified attribute is set to the same value in every row of the table (which is usually not what you want to do). You can also set multiple attribute values at the same time with a comma-delimited list of attribute=expression pairs.

• The delete statement does just that, for rows in a table.

DELETE FROM <table name> WHERE <condition>;

If the WHERE clause is omitted, then every row of the table is deleted (which again is usually not what you want to do)—and again, you will not get a “do you really want to do this?” message.

• If you are using a large multi-user system, you may need to make your DML changes visible to the rest of the users of the database. Although this might be done automatically when you log out, you could also just type:

COMMIT; • If you’ve messed up your changes in this type of system, and want to restore your private copy of the database to the way it was before you started (this only works if you haven’t already typed COMMIT), just type:

ROLLBACK; Although single-user systems don’t support commit and rollback statements, they are used in large systems to control transactions, which are sequences of changes to the database. Transactions are frequently covered in more advanced courses.

5. SELECT STATEMENT BASICS (http://www.firstsql.com/tutor1.htm)

In the subsequent text, the following 3 example tables are used:

p Table (parts) s Table (suppliers) sp Table (suppliers & parts)

Page 64: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

pno descr color

P1 Widget Blue

P2 Widget Red

P3 Dongle Green

sno name city

S1 Pierre Paris

S2 John London

S3 Mario Rome

sno pno qty

S1 P1 NULL

S2 P1 200

S3 P1 1000

S3 P2 200

The SQL SELECT statement queries data from tables in the database. The statement begins with the SELECT keyword. The basic SELECT statement has 3 clauses:

• SELECT • FROM • WHERE

The SELECT clause specifies the table columns that are retrieved. The FROM clause specifies the tables accessed. The WHERE clause specifies which table rows are used. The WHERE clause is optional; if missing, all table rows are used.

For example, SELECT name FROM s WHERE city='Rome'

This query accesses rows from the table - s. It then filters those rows where the city column contains Rome. Finally, the query retrieves the name column from each filtered row. Using the example s table, this query produces:

name

Mario

A detailed description of the query actions:

• The FROM clause accesses the s table. Contents:

sno name city

S1 Pierre Paris

S2 John London

Page 65: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

S3 Mario Rome

• The WHERE clause filters the rows of the FROM table to use those whose city column contains Rome. This chooses a single row from s:

sno name city

S3 Mario Rome

• The SELECT clause retrieves the name column from the rows filtered by the WHERE clause:

name

Mario

SELECT CLAUSE The SELECT clause is mandatory. It specifies a list of columns to be retrieved from the tables in the FROM clause. It has the following general format:

SELECT [ALL|DISTINCT] select-list select-list is a list of column names separated by commas. The ALL and DISTINCT specifiers are optional. DISTINCT specifies that duplicate rows are discarded. A duplicate row is when each corresponding select-list column has the same value. The default is ALL, which retains duplicate rows.

For example, SELECT descr, color FROM p

The column names in the select list can be qualified by the appropriate table name:

SELECT p.descr, p.color FROM p A column in the select list can be renamed by following the column name with the new name. For example:

SELECT name supplier, city location FROM s This produces:

supplier location

Pierre Paris

John London

Mario Rome

Page 66: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

A special select list consisting of a single '*' requests all columns in all tables in the FROM clause. For example,

SELECT * FROM sp sno pno qty

S1 P1 NULL

S2 P1 200

S3 P1 1000

S3 P2 200

The * delimiter will retrieve just the columns of a single table when qualified by the table name. For example:

SELECT sp.* FROM sp This produces the same result as the previous example.

An unqualified * cannot be combined with other elements in the select list; it must be stand alone. However, a qualified * can be combined with other elements. For example,

SELECT sp.*, city FROM sp, s WHERE sp.sno=s.sno sno pno qty city

S1 P1 NULL Paris

S2 P1 200 London

S3 P1 1000 Rome

S3 P2 200 Rome

Note: this is an example of a query joining 2 tables.

FROM CLAUSE The FROM clause always follows the SELECT clause. It lists the tables accessed by the query. For example,

SELECT * FROM s When the From List contains multiple tables, commas separate the table names. For example,

SELECT sp.*, city FROM sp, s WHERE sp.sno=s.sno

Page 67: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

When the From List has multiple tables, they must be joined together.

Correlation Names Like columns in the select list, tables in the from list can be renamed by following the table name with the new name. For example,

SELECT supplier.name FROM s supplier The new name is known as the correlation (or range) name for the table. Self joins require correlation names.

WHERE CLAUSE The WHERE clause is optional. When specified, it always follows the FROM clause. The WHERE clause filters rows from the FROM clause tables. Omitting the WHERE clause specifies that all rows are used.

Following the WHERE keyword is a logical expression, also known as a predicate. The predicate evaluates to a SQL logical value -- true, false or unknown. The most basic predicate is a comparison:

color = 'Red' This predicate returns:

• true -- if the color column contains the string value -- 'Red', • false -- if the color column contains another string value (not 'Red'), or • unknown -- if the color column contains null.

Generally, a comparison expression compares the contents of a table column to a literal, as above. A comparison expression may also compare two columns to each other. Table joins use this type of comparison.

The = (equals) comparison operator compares two values for equality. Additional comparison operators are:

• > -- greater than • < -- less than • >= -- greater than or equal to • <= -- less than or equal to • <> -- not equal to

For example,

SELECT * FROM sp WHERE qty >= 200 sno pno qty

S2 P1 200

S3 P1 1000

S3 P2 200

Page 68: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

Note: In the sp table, the qty column for one of the rows contains null. The comparison - qty >= 200, evaluates to unknown for this row. In the final result of a query, rows with a WHERE clause evaluating to unknown (or false) are eliminated (filtered out).

Both operands of a comparison should be the same data type, however automatic conversions are performed between numeric, datetime and interval types. The CAST expression provides explicit type conversions. Extended Comparisons In addition to the basic comparisons described above, SQL supports extended comparison operators -- BETWEEN, IN, LIKE and IS NULL.

• BETWEEN Operator

The BETWEEN operator implements a range comparison, that is, it tests whether a value is between two other values. BETWEEN comparisons have the following format:

value-1 [NOT] BETWEEN value-2 AND value-3

This comparison tests if value-1 is greater than or equal to value-2 and less than or equal to value-3. It is equivalent to the following predicate:

value-1 >= value-2 AND value-1 <= value-3

Or, if NOT is included:

NOT (value-1 >= value-2 AND value-1 <= value-3)

For example,

SELECT * FROM sp WHERE qty BETWEEN 50 and 500 sno pno qty

S2 P1 200

S3 P2 200

• IN Operator

The IN operator implements comparison to a list of values, that is, it tests whether a value matches any value in a list of values. IN comparisons have the following general format:

value-1 [NOT] IN ( value-2 [, value-3] ... )

Page 69: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

This comparison tests if value-1 matches value-2 or matches value-3, and so on. It is equivalent to the following logical predicate:

value-1 = value-2 [ OR value-1 = value-3 ] ...

or if NOT is included:

NOT (value-1 = value-2 [ OR value-1 = value-3 ] ...)

For example,

SELECT name FROM s WHERE city IN ('Rome','Paris') name

Pierre

Mario

• LIKE Operator

The LIKE operator implements a pattern match comparison, that is, it matches a string value against a pattern string containing wild-card characters.

The wild-card characters for LIKE are percent -- '%' and underscore -- '_'. Underscore matches any single character. Percent matches zero or more characters.

Examples,

Match Value Pattern Result

'abc' '_b_' True

'ab' '_b_' False

'abc' '%b%' True

'ab' '%b%' True

'abc' 'a_' False

'ab' 'a_' True

'abc' 'a%_' True

Page 70: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

'ab' 'a%_' True

LIKE comparison has the following general format:

value-1 [NOT] LIKE value-2 [ESCAPE value-3]

All values must be string (character). This comparison uses value-2 as a pattern to match value-1. The optional ESCAPE sub-clause specifies an escape character for the pattern, allowing the pattern to use '%' and '_' (and the escape character) for matching. The ESCAPE value must be a single character string. In the pattern, the ESCAPE character precedes any character to be escaped.

For example, to match a string ending with '%', use:

x LIKE '%/%' ESCAPE '/'

A more contrived example that escapes the escape character:

y LIKE '/%//%' ESCAPE '/'

... matches any string beginning with '%/'.

The optional NOT reverses the result so that:

z NOT LIKE 'abc%'

is equivalent to:

NOT z LIKE 'abc%'

• IS NULL Operator

A database null in a table column has a special meaning -- the value of the column is not currently known (missing), however its value may be known at a later time. A database null may represent any value in the future, but the value is not available at this time. Since two null columns may eventually be assigned different values, one null can't be compared to another in the conventional way. The following syntax is illegal in SQL:

WHERE qty = NULL

A special comparison operator -- IS NULL, tests a column for null. It has the following general format:

value-1 IS [NOT] NULL

Page 71: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

This comparison returns true if value-1 contains a null and false otherwise. The optional NOT reverses the result:

value-1 IS NOT NULL

is equivalent to:

NOT value-1 IS NULL

For example,

SELECT * FROM sp WHERE qty IS NULL sno pno qty

S1 P1 NULL

Logical Operators The logical operators are AND, OR, NOT. They take logical expressions as operands and produce a logical result (True, False, Unknown). In logical expressions, parentheses are used for grouping.

• AND Operator

The AND operator combines two logical operands. The operands are comparisons or logical expressions. It has the following general format:

predicate-1 AND predicate-2

AND returns:

o True -- if both operands evaluate to true o False -- if either operand evaluates to false o Unknown -- otherwise (one operand is true and the other is unknown or both are unknown)

The truth table for AND:

AND T F U

T T F U

F F F F

U U F U

For example,

Page 72: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

SELECT * FROM sp WHERE sno='S3' AND qty < 500 sno pno qty

S3 P2 200

• OR Operator

The OR operator combines two logical operands. The operands are comparisons or logical expressions. It has the following general format:

predicate-1 OR predicate-2

OR returns:

o True -- if either operand evaluates to true o False -- if both operands evaluate to false o Unknown -- otherwise (one operand is false and the other is unknown or both are

unknown)

The truth table for OR:

OR T F U

T T T T

F T F U

U T U U

For example,

SELECT * FROM s WHERE sno='S3' OR city = 'London' sno name city

S2 John London

S3 Mario Rome

Page 73: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

AND has a higher precedence than OR, so the following expression:

a OR b AND c

is equivalent to:

a OR (b AND c)

• NOT Operator

The NOT operator inverts the result of a comparison expression or a logical expression. It has the following general format:

NOT predicate-1

The truth table for NOT:

NOT

T F

F T

U U

Example query:

SELECT * FROM sp WHERE NOT sno = 'S3' sno pno qty

S1 P1 NULL

S2 P1 200

ORDER BY CLAUSE The ORDER BY clause is optional. If used, it must be the last clause in the SELECT statement. The ORDER BY clause requests sorting for the results of a query.

Page 74: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

When the ORDER BY clause is missing, the result rows from a query have no defined order (they are unordered). The ORDER BY clause defines the ordering of rows based on columns from the SELECT clause. The ORDER BY clause has the following general format:

ORDER BY column-1 [ASC|DESC] [ column-2 [ASC|DESC] ] ... column-1, column-2, ... are column names specified (or implied) in the select list. If a select column is renamed (given a new name in the select entry), the new name is used in the ORDER BY list. ASC and DESC request ascending or descending sort for a column. ASC is the default.

ORDER BY sorts rows using the ordering columns in left-to-right, major-to-minor order. The rows are sorted first on the first column name in the list. If there are any duplicate values for the first column, the duplicates are sorted on the second column (within the first column sort) in the Order By list, and so on. There is no defined inner ordering for rows that have duplicate values for all Order By columns. Database nulls require special processing in ORDER BY. A null column sorts higher than all regular values; this is reversed for DESC. In sorting, nulls are considered duplicates of each other for ORDER BY. Sorting on hidden information makes no sense in utilizing the results of a query. This is also why SQL only allows select list columns in ORDER BY. For convenience when using expressions in the select list, select items can be specified by number (starting with 1). Names and numbers can be intermixed. Example queries:

SELECT * FROM sp ORDER BY 3 DESC sno pno qty

S1 P1 NULL

S3 P1 1000

S3 P2 200

S2 P1 200

SELECT name, city FROM s ORDER BY name name city

John London

Mario Rome

Pierre Paris

SELECT * FROM sp ORDER BY qty DESC, sno sno pno qty

Page 75: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

S1 P1 NULL

S3 P1 1000

S2 P1 200

S3 P2 200

EXPRESSIONS In the previous subsection on basic Select statements, column values are used in the select list and where predicate. SQL allows a scalar value expression to be used instead. A SQL value expression can be a:

• Literal -- quoted string, numeric value, datetime value • Function Call -- reference to builtin SQL function • System Value -- current date, current user, ... • Special Construct -- CAST, COALESCE, CASE • Numeric or String Operator -- combining sub-expressions

Literals A literal is a typed value that is self-defining. SQL supports 3 types of literals:

• String -- ASCII text framed by single quotes ('). Within a literal, a single quote is represented by 2 single quotes ('').

• Numeric -- numeric digits (at least 1) with an optional decimal point and exponent. The format is

[ddd][[.]ddd][E[+|-]ddd]

Numeric literals with no exponent or decimal point are typed as Integer. Those with a decimal point but no exponent are typed as Decimal. Those with an exponent are typed as Float.

• Datetime -- datetime literals begin with a keyword identifying the type, followed by a string literal: o Date -- DATE 'yyyy-mm-dd' o Time -- TIME 'hh:mm:ss[.fff]' o Timestamp -- TIMESTAMP 'yyyy-mm-dd hh:mm:ss[.fff]' o Interval -- INTERVAL [+|-] string interval-qualifier

The format of the string in the Interval literal depends on the interval qualifier. For year-month intervals, the format is: 'dd[-dd]'. For day-time intervals, the format is '[dd ]dd[:dd[:dd]][.fff]'.

SQL Functions SQL has the following builtin functions:

• SUBSTRING(exp-1 FROM exp-2 [FOR exp-3])

Page 76: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

Extracts a substring from a string - exp-1, beginning at the integer value - exp-2, for the length of the integer value - exp-3. exp-2 is 1 relative. If FOR exp-3 is omitted, the length of the remaining string is used. Returns the substring.

• UPPER(exp-1)

Converts any lowercase characters in a string - exp-1 to uppercase. Returns the converted string.

• LOWER(exp-1)

Converts any uppercase characters in a string - exp-1 to lowercase. Returns the converted string.

• TRIM([LEADING|TRAILING|BOTH] [FROM] exp-1) TRIM([LEADING|TRAILING|BOTH] exp-2 FROM exp-1)

Trims leading, trailing or both characters from a string - exp-1. The trim character is a space, or if exp-2 is specified, it supplies the trim character. If LEADING, TRAILING, BOTH are missing, the default is BOTH. Returns the trimmed string.

• POSITION(exp-1 IN exp-2)

Searches a string - exp-2, for a match on a substring - exp-2. Returns an integer, the 1 relative position of the match or 0 for no match.

• CHAR_LENGTH(exp-1) CHARACTER_LENGTH(exp-1)

Returns the integer number of characters in the string - exp-1.

• OCTET_LENGTH(exp-1)

Returns the integer number of octets (8-bit bytes) needed to represent the string - exp-1.

• EXTRACT(sub-field FROM exp-1)

Returns the numeric sub-field extracted from a datetime value - exp-1. sub-field is YEAR, QUARTER, MONTH, DAY, HOUR, MINUTE, SECOND, TIMEZONE_HOUR or TIMEZONE_MINUTE. TIMEZONE_HOUR and TIMEZONE_MINUTE extract sub-fields from the Timezone portion of exp-1. QUARTER is (MONTH-1)/4+1.

System Values SQL System Values are reserved names used to access builtin values:

• USER -- returns a string with the current SQL authorization identifier. • CURRENT_USER -- same as USER.

Page 77: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

• SESSION_USER -- returns a string with the current SQL session authorization identifier. • SYSTEM_USER -- returns a string with the current operating system user. • CURRENT_DATE -- returns a Date value for the current system date. • CURRENT_TIME -- returns a Time value for the current system time. • CURRENT_TIMESTAMP -- returns a Timestamp value for the current system timestamp.

SQL Special Constructs SQL supports a set of special expression constructs:

• CAST(exp-1 AS data-type)

Converts the value - exp-1, into the specified date-type. Returns the converted value.

• COALESCE(exp-1, exp-2 [, exp-3] ...)

Returns exp-1 if it is not null, otherwise returns exp-2 if it is not null, otherwise returns exp-3, and so on. Returns null if all values are null.

• CASE exp-1 { WHEN exp-2 THEN exp-3 } ... [ELSE exp-4] END CASE { WHEN predicate-1 THEN exp-3 } ... [ELSE exp-4] END

The first form of the CASE construct compares exp-1 to exp-2 in each WHEN clause. If a match is found, CASE returns exp-3 from the corresponding THEN clause. If no matches are found, it returns exp-4 from the ELSE clause or null if the ELSE clause is omitted.

The second form of the CASE construct evaluates predicate-1 in each WHEN clause. If the predicate is true, CASE returns exp-3 from the corresponding THEN clause. If no predicates evaluate to true, it returns exp-4 from the ELSE clause or null if the ELSE clause is omitted.

Expression Operators Expression operators combine 2 subexpressions to calculate a value. There are 2 basic types -- numeric and string.

• String Operators

There is just one string operator - ||, for string concatenation. Both operands of || must be strings. The operator concatenates the second string to the end of the first. For example,

'ab' || 'cd' ==> 'abcd'

• Numeric operators

The numeric operators are common to most languages:

o + -- addition o - -- subtraction o * -- multiplication

Page 78: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

o / -- division

All numeric operators can be used on the standard numeric data types:

o Integer -- TINYINT, SMALLINT, INT, BIGINT o Exact -- NUMERIC, DECIMAL o Approximate -- FLOAT, DOUBLE, REAL

Automatic conversion is provided for numeric operators. If an integer type is combined with an exact type, the integer is converted to exact before the operation. If an exact (or integer) type is combined with an approximate type, it is converted to approximate before the operation.

The + and - operators can also be used as unary operators.

The numeric operators can be applied to datetime values, with some restrictions. The basic rules for datetime expressions are:

o A date, time, timestamp value can be added to an interval; result is a date, time, timestamp value.

o An interval value can be subtracted from a date, time, timestamp value; result is a date, time, timestamp value.

o An interval value can be added to or subtracted from another interval; result is an interval value.

o An interval can be multiplied by or divided by a standard numeric value; result is an interval value.

A special form can be used to subtract a date, time, timestamp value from another date, time, timestamp value to yield an interval value:

(datetime-1 - datetime-2) interval-qualifier

The interval-qualifier specifies the specific interval type for the result.

A second special form allows a ? parameter to be typed as an interval:

? interval-qualifier In expressions, parentheses are used for grouping.

JOINING TABLES The FROM clause allows more than 1 table in its list, however simply listing more than one table will very rarely produce the expected results. The rows from one table must be correlated with the rows of the others. This correlation is known as joining.

An example can best illustrate the rationale behind joins. The following query: SELECT * FROM sp, p

Produces:

Page 79: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

sno pno qty pno descr color

S1 P1 NULL P1 Widget Blue

S1 P1 NULL P2 Widget Red

S1 P1 NULL P3 Dongle Green

S2 P1 200 P1 Widget Blue

S2 P1 200 P2 Widget Red

S2 P1 200 P3 Dongle Green

S3 P1 1000 P1 Widget Blue

S3 P1 1000 P2 Widget Red

S3 P1 1000 P3 Dongle Green

S3 P2 200 P1 Widget Blue

S3 P2 200 P2 Widget Red

S3 P2 200 P3 Dongle Green

Each row in sp is arbitrarily combined with each row in p, giving 12 result rows (4 rows in sp X 3 rows in p.) This is known as a cartesian product.

A more usable query would correlate the rows from sp with rows from p, for instance matching on the common column -- pno:

SELECT * FROM sp, p WHERE sp.pno = p.pno

This produces:

sno pno qty pno descr color

S1 P1 NULL P1 Widget Blue

S2 P1 200 P1 Widget Blue

S3 P1 1000 P1 Widget Blue

Page 80: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

S3 P2 200 P2 Widget Red

Rows for each part in p are combined with rows in sp for the same part by matching on part number (pno). In this query, the WHERE Clause provides the join predicate, matching pno from p with pno from sp.

The join in this example is known as an inner equi-join. equi meaning that the join predicate uses = (equals) to match the join columns. Other types of joins use different comparison operators. For example, a query might use a greater-than join. The term inner means only rows that match are included. Rows in the first table that have no matching rows in the second table are excluded and vice versa (in the above join, the row in p with pno P3 is not included in the result.) An outer join includes unmatched rows in the result. More than 2 tables can participate in a join. This is basically just an extension of a 2 table join. 3 tables -- a, b, c, might be joined in various ways:

• a joins b which joins c • a joins b and the join of a and b joins c • a joins b and a joins c

Plus several other variations. With inner joins, this structure is not explicit. It is implicit in the nature of the join predicates. With outer joins, it is explicit;

This query performs a 3 table join: SELECT name, qty, descr, color FROM s, sp, p WHERE s.sno = sp.sno AND sp.pno = p.pno

It joins s to sp and sp to p, producing:

name qty descr color

Pierre NULL Widget Blue

John 200 Widget Blue

Mario 1000 Widget Blue

Mario 200 Widget Red

Note that the order of tables listed in the FROM clause should have no significance, nor does the order of join predicates in the WHERE clause.

Outer Joins An inner join excludes rows from either table that don't have a matching row in the other table. An outer join provides the ability to include unmatched rows in the query results. The outer join combines the unmatched row in one of the tables with an artificial row for the other table. This artificial row has all columns set to null.

Page 81: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

The outer join is specified in the FROM clause and has the following general format: table-1 { LEFT | RIGHT | FULL } OUTER JOIN table-2 ON predicate-1

predicate-1 is a join predicate for the outer join. It can only reference columns from the joined tables. The LEFT, RIGHT or FULL specifiers give the type of join:

• LEFT -- only unmatched rows from the left side table (table-1) are retained • RIGHT -- only unmatched rows from the right side table (table-2) are retained • FULL -- unmatched rows from both tables (table-1 and table-2) are retained

Outer join example:

SELECT pno, descr, color, sno, qty FROM p LEFT OUTER JOIN sp ON p.pno = sp.pno pno descr color sno qty

P1 Widget Blue S1 NULL

P1 Widget Blue S2 200

P1 Widget Blue S3 1000

P2 Widget Red S3 200

P3 Dongle Green NULL NULL

Self Joins A query can join a table to itself. Self joins have a number of real world uses. For example, a self join can determine which parts have more than one supplier:

SELECT DISTINCT a.pno FROM sp a, sp b WHERE a.pno = b.pno AND a.sno <> b.sno pno

P1

As illustrated in the above example, self joins use correlation names to distinguish columns in the select list and where predicate. In this case, the references to the same table are renamed - a and b.

Self joins are often used in subqueries.

SUBQUERIES Subqueries are an identifying feature of SQL. It is called Structured Query Language because a query can nest inside another query.

Page 82: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

There are 3 basic types of subqueries in SQL:

• Predicate Subqueries -- extended logical constructs in the WHERE (and HAVING) clause. • Scalar Subqueries -- standalone queries that return a single value; they can be used anywhere a

scalar value is used. • Table Subqueries -- queries nested in the FROM clause.

All subqueries must be enclosed in parentheses.

Predicate Subqueries Predicate subqueries are used in the WHERE (and HAVING) clause. Each is a special logical construct. Except for EXISTS, predicate subqueries must retrieve one column (in their select list.)

• IN Subquery

The IN Subquery tests whether a scalar value matches the single query column value in any subquery result row. It has the following general format:

value-1 [NOT] IN (query-1)

Using NOT is equivalent to:

NOT value-1 IN (query-1)

For example, to list parts that have suppliers:

SELECT * FROM p WHERE pno IN (SELECT pno FROM sp) pno descr color

P1 Widget Blue

P2 Widget Red

The Self Join example in the previous subsection can be expressed with an IN Subquery:

SELECT DISTINCT pno FROM sp a WHERE pno IN (SELECT pno FROM sp b WHERE a.sno <> b.sno) pno

P1

Page 83: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

Note that the subquery where clause references a column in the outer query (a.sno). This is known as an outer reference. Subqueries with outer references are sometimes known as correlated subqueries.

• Quantified Subqueries

A quantified subquery allows several types of tests and can use the full set of comparison operators. It has the following general format:

value-1 {=|>|<|>=|<=|<>} {ANY|ALL|SOME} (query-1)

The comparison operator specifies how to compare value-1 to the single query column value from each subquery result row. The ANY, ALL, SOME specifiers give the type of match expected. ANY and SOME must match at least one row in the subquery. ALL must match all rows in the subquery.

For example, to list all parts that have suppliers:

SELECT * FROM p WHERE pno =ANY (SELECT pno FROM sp) pno descr color

P1 Widget Blue

P2 Widget Red

A self join is used to list the supplier with the highest quantity of each part (ignoring null quantities):

SELECT * FROM sp a WHERE qty >ALL (SELECT qty FROM sp b WHERE a.pno = b.pno AND a.sno <> b.sno AND qty IS NOT NULL) sno pno qty

S3 P1 1000

S3 P2 200

• EXISTS Subqueries

Page 84: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

The EXISTS Subquery tests whether a subquery retrieves at least one row, that is, whether a qualifying row exists. It has the following general format

EXISTS(query-1)

Any valid EXISTS subquery must contain an outer reference. It must be a correlated subquery.

Note: the select list in the EXISTS subquery is not actually used in evaluating the EXISTS, so it can contain any valid select list (though * is normally used).

To list parts that have suppliers:

SELECT * FROM p WHERE EXISTS(SELECT * FROM sp WHERE p.pno = sp.pno) pno descr color

P1 Widget Blue

P2 Widget Red

Scalar Subqueries The Scalar Subquery can be used anywhere a value can be used. The subquery must reference just one column in the select list. It must also retrieve no more than one row.

When the subquery returns a single row, the value of the single select list column becomes the value of the Scalar Subquery. When the subquery returns no rows, a database null is used as the result of the subquery. Should the subquery retreive more than one row, it is a run-time error and aborts query execution. A Scalar Subquery can appear as a scalar value in the select list and where predicate of an another query. The following query on the sp table uses a Scalar Subquery in the select list to retrieve the supplier city associated with the supplier number (sno column in sp):

SELECT pno, qty, (SELECT city FROM s WHERE s.sno = sp.sno) FROM sp pno qty city

P1 NULL Paris

P1 200 London

P1 1000 Rome

P2 200 Rome

Page 85: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

The next query on the sp table uses a Scalar Subquery in the where clause to match parts on the color associated with the part number (pno column in sp):

SELECT * FROM sp WHERE 'Blue' = (SELECT color FROM p WHERE p.pno = sp.pno) sno pno qty

S1 P1 NULL

S2 P1 200

S3 P1 1000

Note that both example queries use outer references. This is normal in Scalar Subqueries. Often, Scalar Subqueries are Aggregate Queries.

Table Subqueries Table Subqueries are queries used in the FROM clause, replacing a table name. Basically, the result set of the Table Subquery acts like a base table in the from list. Table Subqueries can have a correlation name in the from list. They can also be in outer joins.

The following two queries produce the same result: SELECT p.*, qty FROM p, sp WHERE p.pno = sp.pno AND sno = 'S3' pno descr color qty

P1 Widget Blue 1000

P2 Widget Red 200

SELECT p.*, qty FROM p, (SELECT pno, qty FROM sp WHERE sno = 'S3') WHERE p.pno = sp.pno pno descr color qty

P1 Widget Blue 1000

P2 Widget Red 200

GROUPING QUERIES A Grouping Query is a special type of query that groups and summarizes rows. It uses the GROUP BY Clause.

Page 86: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

A Grouping Query groups rows based on common values in a set of grouping columns. Rows with the same values for the grouping columns are placed in distinct groups. Each group is treated as a single row in the query result. Even though a group is treated as a single row, the underlying rows can be subject to summary operations known as Set Functions whose results can be included in the query. The optional HAVING Clause supports filtering for group rows in the same manner as the WHERE clause filters FROM rows. For example, grouping the sp table on the pno column produces 2 groups:

sno pno qty

S1 P1 NULL

'P1' Group S2 P1 200

S3 P1 1000

S3 P2 200 'P2' Group

• The P1 group contains 3 sp rows with pno='P1' • The P2 group contains a single sp row with pno='P2'

Nulls get special treatment by GROUP BY. GROUP BY considers a null as distinct from every other null. Each row that has a null in one of its grouping columns forms a separate group.

Grouping the sp table on the qty column produces 3 groups: sno pno qty

S1 P1 NULL NULL Group

S2 P1 200 200 Group

S3 P2 200

S3 P1 1000 1000 Group

The row where qty is null forms a separate group.

GROUP BY Clause GROUP BY is an optional clause in a query. It follows the WHERE clause or the FROM clause if the WHERE clause is missing. A query containing a GROUP BY clause is a Grouping Query. The GROUP BY clause has the following general format:

GROUP BY column-1 [, column-2] ... column-1 and column-2 are the grouping columns. They must be names of columns from tables in the FROM clause; they can't be expressions.

Page 87: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

GROUP BY operates on the rows from the FROM clause as filtered by the WHERE clause. It collects the rows into groups based on common values in the grouping columns. Except nulls, rows with the same set of values for the grouping columns are placed in the same group. If any grouping column for a row contains a null, the row is given its own group. For example,

SELECT pno FROM sp GROUP BY pno pno

P1

P2

In Grouping Queries, the select list can only contain grouping columns, plus literals, outer references and expression involving these elements. Non-grouping columns from the underlying FROM tables cannot be referenced directly. However, non-grouping columns can be used in the select list as arguments to Set Functions. Set Functions summarize columns from the underlying rows of a group.

Set Functions Set Functions are special summarizing functions used with Grouping Queries and Aggregate Queries. They summarize columns from the underlying rows of a group or aggregate.

Using the Group By example from above, grouping the sp table on the pno column: sno pno qty

S1 P1 NULL

'P1' Group S2 P1 200

S3 P1 1000

S3 P2 200 'P2' Group

A Set Function can compute the total quantities for each group:

sno pno qty qty total

S1 P1 NULL

'P1' Group 1200 S2 P1 200

S3 P1 1000

Page 88: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

S3 P2 200 'P2' Group 200

Null columns are ignored in computing the summary. The Set Function -- SUM, computes the arithmetic sum of a numeric column in a set of grouped/aggregate rows. For example,

SELECT pno, SUM(qty) FROM sp GROUP BY pno pno

P1 1200

P2 200

Set Functions have the following general format:

set-function ( [DISTINCT|ALL] column-1 ) set-function is:

• COUNT -- count of rows • SUM -- arithmetic sum of numeric column • AVG -- arithmetic average of numeric column; should be SUM()/COUNT(). • MIN -- minimum value found in column • MAX -- maximum value found in column

The result of the COUNT function is always integer. The result of all other Set Functions is the same data type as the argument.

The Set Functions skip columns with nulls, summarizing non-null values. COUNT counts rows with non-null values, AVG averages non-null values, and so on. COUNT returns 0 when no non-null column values are found; the other functions return null when there are no values to summarize. A Set Function argument can be a column or a scalar expression. The DISTINCT and ALL specifiers are optional. ALL specifies that all non-null values are summarized; it is the default. DISTINCT specifies that distinct column values are summarized; duplicate values are skipped. Note: DISTINCT has no effect on MIN and MAX results. COUNT also has an alternate format:

COUNT(*) ... which counts the underlying rows regardless of column contents.

Set Function examples: SELECT pno, MIN(sno), MAX(qty), AVG(qty), COUNT(DISTINCT sno) FROM sp GROUP BY pno pno

Page 89: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

P1 S1 1000 600 3

P2 S3 200 200 1

SELECT sno, COUNT(*) parts FROM sp GROUP BY sno sno parts

S1 1

S2 1

S3 2

HAVING Clause The HAVING Clause is associated with Grouping Queries and Aggregate Queries. It is optional in both cases. In Grouping Queries, it follows the GROUP BY clause. In Aggregate Queries, HAVING follows the WHERE clause or the FROM clause if the WHERE clause is missing.

The HAVING Clause has the following general format: HAVING predicate

Like the WHERE Clause, HAVING filters the query result rows. WHERE filters the rows from the FROM clause. HAVING filters the grouped rows (from the GROUP BY clause) or the aggregate row (for Aggregate Queries).

predicate is a logical expression referencing grouped columns and set functions. It has the same restrictions as the select list for Grouping Queries and Aggregate Queries. If the Having predicate evaluates to true for a grouped or aggregate row, the row is included in the query result, otherwise, the row is skipped (not included in the query result). For example,

SELECT sno, COUNT(*) parts FROM sp GROUP BY sno HAVING COUNT(*) > 1 sno parts

S3 2

AGGREGATE QUERIES An Aggregate Query can use Set Functions and a HAVING Clause. It is similar to a Grouping Query except there are no grouping columns. The underlying rows from the FROM and WHERE clauses are grouped into a single aggregate row. An Aggregate Query always returns a single row, except when the Having clause is used.

Page 90: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

An Aggregate Query is a query containing Set Functions in the select list but no GROUP BY clause. The Set Functions operate on the columns of the underlying rows of the single aggregate row. Except for outer references, any columns used in the select list must be arguments to Set Functions. An aggregate query may also have a Having clause. The Having clause filters the single aggregate row. If the Having predicate evaluates to true, the query result contains the aggregate row. Otherwise, the query result contains no rows. For example,

SELECT COUNT(DISTINCT pno) number_parts, SUM(qty) total_parts FROM sp number_parts total_parts

2 1400

Subqueries are often Aggregate Queries. For example, parts with suppliers:

SELECT * FROM p WHERE (SELECT COUNT(*) FROM sp WHERE sp.pno=p.pno) > 0 pno descr color

P1 Widget Blue

P2 Widget Red

Parts with multiple suppliers:

SELECT * FROM p WHERE (SELECT COUNT(DISTINCT sno) FROM sp WHERE sp.pno=p.pno) > 1 pno descr color

P1 Widget Blue

UNION QUERIES The SQL UNION operator combines the results of two queries into a composite result. The component queries can be SELECT/FROM queries with optional WHERE/GROUP BY/HAVING clauses. The UNION operator has the following general format:

query-1 UNION [ALL] query-2 query-1 and query-2 are full query specifications. The UNION operator creates a new query result that includes rows from each component query.

By default, UNION eliminates duplicate rows in its composite results. The optional ALL specifier requests that duplicates be retained in the UNION result.

Page 91: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

The component queries of a Union Query can also be Union Queries themselves. Parentheses are used for grouping queries. The select lists from the component queries must be union-compatible. They must match in degree (number of columns). For Entry Level SQL92, the column descriptor (data type and precision, scale) for each corresponding column must match. The rules for Intermediate Level SQL92 are less restrictive. Union-Compatible Queries For Entry Level SQL92, each corresponding column of both queries must have the same column descriptor in order for two queries to be union-compatible. The rules are less restrictive for Intermediate Level SQL92. It supports automatic conversion within type categories. In general, the resulting data type will be the broader type. The corresponding columns need only be in the same data type category:

• Character (String) -- fixed/variable length • Bit String -- fixed/variable length • Exact Numeric (fixed point) -- integer/decimal • Approximate Numeric (floating point) -- float/double • Datetime -- sub-category must be the same,

o Date o Time o Timestamp

• Interval -- sub-category must be the same, o Year-month o Day-time

UNION Examples SELECT * FROM sp UNION SELECT CAST(' ' AS VARCHAR(5)), pno, CAST(0 AS INT) FROM p WHERE pno NOT IN (SELECT pno FROM sp) sno pno qty

S1 P1 NULL

S2 P1 200

S3 P1 1000

S3 P2 200

P3 0

SQL MODIFICATION STATEMENTS

Page 92: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

The SQL Modification Statements make changes to database data in tables and columns. There are 3 modification statements:

• INSERT Statement -- add rows to tables • UPDATE Statement -- modify columns in table rows • DELETE Statement -- remove rows from tables

INSERT STATEMENT The INSERT Statement adds one or more rows to a table. It has two formats:

INSERT INTO table-1 [(column-list)] VALUES (value-list) and,

INSERT INTO table-1 [(column-list)] (query-specification) The first form inserts a single row into table-1 and explicitly specifies the column values for the row. The second form uses the result of query-specification to insert one or more rows into table-1. The result rows from the query are the rows added to the insert table. Note: the query cannot reference table-1.

Both forms have an optional column-list specification. Only the columns listed will be assigned values. Unlisted columns are set to null, so unlisted columns must allow nulls. The values from the VALUES Clause (first form) or the columns from the query-specification rows (second form) are assigned to the corresponding column in column-list in order. If the optional column-list is missing, the default column list is substituted. The default column list contains all columns in table-1 in the order they were declared in CREATE TABLE, or CREATE VIEW. VALUES Clause The VALUES Clause in the INSERT Statement provides a set of values to place in the columns of a new row. It has the following general format:

VALUES ( value-1 [, value-2] ... ) value-1 and value-2 are Literal Values or Scalar Expressions involving literals. They can also specify NULL.

The values list in the VALUES clause must match the explicit or implicit column list for INSERT in degree (number of items). They must also match the data type of corresponding column or be convertible to that data type. INSERT Examples

INSERT INTO p (pno, color) VALUES ('P4', 'Brown') Before After

pno descr color

P1 Widget Blue

P2 Widget Red =>

pno descr color

P1 Widget Blue

P2 Widget Red

Page 93: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

P3 Dongle Green

P3 Dongle Green

P4 NULL Brown

INSERT INTO sp SELECT s.sno, p.pno, 500 FROM s, p WHERE p.color='Green' AND s.city='London' Before After

sno pno qty

S1 P1 NULL

S2 P1 200

S3 P1 1000

S3 P2 200

=>

sno pno qty

S1 P1 NULL

S2 P1 200

S3 P1 1000

S3 P2 200

S2 P3 500

UPDATE STATEMENT The UPDATE statement modifies columns in selected table rows. It has the following general format:

UPDATE table-1 SET set-list [WHERE predicate] The optional WHERE Clause has the same format as in the SELECT Statement. See WHERE Clause. The WHERE clause chooses which table rows to update. If it is missing, all rows are in table-1 are updated.

The set-list contains assignments of new values for selected columns. The SET Clause expressions and WHERE Clause predicate can contain subqueries, but the subqueries cannot reference table-1. This prevents situations where results are dependent on the order of processing. SET Clause The SET Clause in the UPDATE Statement updates (assigns new value to) columns in the selected table rows. It has the following general format:

SET column-1 = value-1 [, column-2 = value-2] ... column-1 and column-2 are columns in the Update table. value-1 and value-2 are expressions that can reference columns from the update table. They also can be the keyword -- NULL, to set the column to null.

Since the assignment expressions can reference columns from the current row, the expressions are evaluated first. After the values of all Set expressions have been computed, they are then assigned to the referenced columns. This avoids results dependent on the order of processing. UPDATE Examples

Page 94: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

UPDATE sp SET qty = qty + 20 Before After

sno pno qty

S1 P1 NULL

S2 P1 200

S3 P1 1000

S3 P2 200

=>

sno pno qty

S1 P1 NULL

S2 P1 220

S3 P1 1020

S3 P2 220

UPDATE s SET name = 'Tony', city = 'Milan' WHERE sno = 'S3' Before After

sno name city

S1 Pierre Paris

S2 John London

S3 Mario Rome

=>

sno name city

S1 Pierre Paris

S2 John London

S3 Tony Milan

DELETE STATEMENT The DELETE Statement removes selected rows from a table. It has the following general format:

DELETE FROM table-1 [WHERE predicate] The optional WHERE Clause has the same format as in the SELECT Statement. See WHERE Clause. The WHERE clause chooses which table rows to delete. If it is missing, all rows are in table-1 are removed.

The WHERE Clause predicate can contain subqueries, but the subqueries cannot reference table-1. This prevents situations where results are dependent on the order of processing. DELETE Examples

DELETE FROM sp WHERE pno = 'P1' Before After

sno pno qty

S1 P1 NULL =>

sno pno qty

S3 P2 200

Page 95: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

S2 P1 200

S3 P1 1000

S3 P2 200

DELETE FROM p WHERE pno NOT IN (SELECT pno FROM sp) Before After

pno descr color

P1 Widget Blue

P2 Widget Red

P3 Dongle Green

=>

pno descr color

P1 Widget Blue

P2 Widget Red

SQL-TRANSACTION STATEMENTS SQL-Transaction Statements control transactions in database access. This subset of SQL is also called the Data Control Language for SQL (SQL DCL).

There are 2 SQL-Transaction Statements:

• COMMIT Statement -- commit (make persistent) all changes for the current transaction • ROLLBACK Statement -- roll back (rescind) all changes for the current transaction

TRANSACTION OVERVIEW A database transaction is a larger unit that frames multiple SQL statements. A transaction ensures that the action of the framed statements is atomic with respect to recovery.

A SQL Modification Statement has limited effect. A given statement can only directly modify the contents of a single table (Referential Integrity effects may cause indirect modification of other tables.) The upshot is that operations which require modification of several tables must involve multiple modification statements. A classic example is a bank operation that transfers funds from one type of account to another, requiring updates to 2 tables. Transactions provide a way to group these multiple statements in one atomic unit. In SQL92, there is no BEGIN TRANSACTION statement. A transaction begins with the execution of a SQL-Data statement when there is no current transaction. All subsequent SQL-Data statements until COMMIT or ROLLBACK become part of the transaction. Execution of a COMMIT Statement or ROLLBACK Statement completes the current transaction. A subsequent SQL-Data statement starts a new transaction.

Page 96: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

In terms of direct effect on the database, it is the SQL Modification Statements that are the main consideration since they change data. The total set of changes to the database by the modification statements in a transaction are treated as an atomic unit through the actions of the transaction. The set of changes either:

• Is made fully persistent in the database through the action of the COMMIT Statement, or • Has no persistent effect whatever on the database, through:

o the action of the ROLLBACK Statement, o abnormal termination of the client requesting the transaction, or o abnormal termination of the transaction by the DBMS. This may be an action by the

system (deadlock resolution) or by an administrative agent, or it may be an abnormal termination of the DBMS itself. In the latter case, the DBMS must roll back any active transactions during recovery.

The DBMS must ensure that the effect of a transaction is not partial. All changes in a transaction must be made persistent, or no changes from the transaction must be made persistent.

Transaction Isolation In most cases, transactions are executed under a client connection to the DBMS. Multiple client connections can initiate transactions at the same time. This is known as concurrent transactions.

In the relational model, each transaction is completely isolated from other active transactions. After initiation, a transaction can only see changes to the database made by transactions committed prior to starting the new transaction. Changes made by concurrent transactions are not seen by SQL DML query and modification statements. This is known as full isolation or Serializable transactions. SQL92 defines Serializable for transactions. However, full serialized transactions can impact performance. For this reason, SQL92 allows additional isolation modes that reduce the isolation between concurrent transactions. SQL92 defines 3 other isolation modes, but support by existing DBMSs is often incomplete and doesn't always match the SQL92 modes. Check the documentation of your DBMS for more details. SQL-Schema Statements in Transactions The 3rd type of SQL Statements - SQL-Schema Statements, may participate in the transaction mechanism. SQL-Schema statements can either be:

• included in a transaction along with SQL-Data statements, • required to be in separate transactions, or • ignored by the transaction mechanism (can't be rolled back).

SQL92 leaves the choice up to the individual DBMS. It is implementation defined behavior.

COMMIT STATEMENT The COMMIT Statement terminates the current transaction and makes all changes under the transaction persistent. It commits the changes to the database. The COMMIT statement has the following general format:

COMMIT [WORK] WORK is an optional keyword that does not change the semantics of COMMIT.

Page 97: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

ROLLBACK STATEMENT The ROLLBACK Statement terminates the current transaction and rescinds all changes made under the transaction. It rolls back the changes to the database. The ROLLBACK statement has the following general format:

ROLLBACK [WORK] WORK is an optional keyword that does not change the semantics of ROLLBACK.

SQL-SCHEMA STATEMENTS SQL-Schema Statements provide maintenance of catalog objects for a schema -- tables, views and privileges. This subset of SQL is also called the Data Definition Language for SQL (SQL DDL).

There are 6 SQL-Schema Statements:

• CREATE TABLE Statement -- create a new base table in the current schema • CREATE VIEW Statement -- create a new view table in the current schema • DROP TABLE Statement -- remove a base table from the current schema • DROP VIEW Statement -- remove a view table from the current schema • GRANT Statement -- grant access privileges for objects in the current schema to other users • REVOKE Statement -- revoke previously granted access privileges for objects in the current

schema from other users

SCHEMA OVERVIEW A relational database contains a catalog that describes the various elements in the system. The catalog divides the database into sub-databases known as schemas. Within each schema are database objects -- tables, views and privileges.

The catalog itself is a set of tables with its own schema name - definition_schema. Tables in the catalog cannot be modified directly. They are modified indirectly with SQL-Schema statements. Tables The database table is the root structure in the relational model and in SQL. A table (called a relation in relational) consists of rows and columns. In relational, rows are called tuples and columns are called attributes. Tables are often displayed in a flat format, with columns arrayed horizontally and rows vertically:

C o l u m n s

R

o

w

Page 98: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

s

Database tables are a logical structure with no implied physical characteristics. Primary among the various logical tables is the base table. A base table is persistent and self contained, that is, all data is part of the table itself with no information dynamically derived from other tables.

A table has a fixed set of columns. The columns in a base table are not accessed positionally but by name, which must be unique among the columns of the table. Each column has a defined data type, and the value for the column in each row must be from the defined data type or null. The columns of a table are accessed and identified by name. A table has 0 or more rows. A row in a base table has a value or null for each column in the table. The rows in a table have no defined ordering and are not accessed positionally. A table row is accessed and identified by the values in its columns. In SQL92, base tables can have duplicate rows (rows where each column has the same value or null). However, the relational model does not recognize tables with duplicate rows as valid base tables (relations). The relational model requires that each base table have a unique identifier, known as the Primary Key. The primary key for a table is a designated set of columns which have a unique value for each table row. For a discussion of Primary Keys, see Entity Integrity under CREATE TABLE below. A base table is defined using the CREATE TABLE Statement. This statement places the table description in the catalog and initializes an internal entity for the actual representation of the base table. Example base table - s:

sno name city

S1 Pierre Paris

S2 John London

S3 Mario Rome

The s table records suppliers. It has 3 defined columns:

• sno -- supplier number, an unique identifier that is the primary key • name -- the name of the supplier • city -- the city where the supplier is located

At the current time, there are 3 rows.

Other types of tables in the system are derived tables. SQL-Data statements use internally derived tables in computing results. A query is in fact a derived table. For instance, the query operator - Union,

Page 99: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

combines two derived tables to produce a third one. Much of the power of SQL comes from the fact that its higher level operations are performed on tables and produce a table as their result. Derived tables are less constrained than base tables. Column names are not required and need not be unique. Derived tables may have duplicate rows. Views are a type of derived table that are cataloged in the database. Views A view is a derived table registered in the catalog. A view is defined using a SQL query. The view is dynamically derived, that is, its contents are materialized for each use. Views are added to the catalog with the CREATE VIEW Statement.

Once defined in the catalog, a view can substitute for a table in SQL-Data statements. A view name can be used instead of a base table name in the FROM clause of a SELECT statement. Views can also be the subject of a modification statement with some restrictions. A SQL Modification Statement can operate on a view if it is an updatable view. An updatable view has the following restrictions on its defining query:

• The query FROM clause can reference a single table (or view) • The single table in the FROM clause must be:

o a base table, o a view that is also an updatable view, or o a nested query that is updatable, that is, it follows the rules for an updatable view query.

• The query must be a basic query, not a: o Grouping Query, o Aggregate Query, or o Union Query.

• The select list cannot contain: o the DISTINCT specifier, o an Expression, or o duplicate column references

Subqueries are acceptable in updatable views but cannot reference the underlying base table for the view's FROM clause.

Privileges SQL92 defines a SQL-agent as an implementation-dependent entity that causes the execution of SQL statements. Prior to execution of SQL statements, the SQL-agent must establish an authorization identifier for database access. An authorization identifier is commonly called a user name.

A DBMS user may access database objects (tables, columns, views) as allowed by the privileges assigned to that specific authorization identifier. Access privileges may be granted by the system (automatic) or by other users. System granted privileges include:

• All privileges on a table to the user that created the table. This includes the privilege to grant privileges on the table to other users.

• SELECT (readonly) privilege on the catalog (the tables in the schema - definition_schema). This is granted to all users.

Page 100: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

User granted privileges cover privileges to access and modify tables and their columns. Privileges can be granted for specific SQL-Data Statements -- SELECT, INSERT, UPDATE, DELETE.

CREATE TABLE STATEMENT The CREATE TABLE Statement creates a new base table. It adds the table description to the catalog. A base table is a logical entity with persistence. The logical description of a base table consists of:

• Schema -- the logical database schema the table resides in • Table Name -- a name unique among tables and views in the Schema • Column List -- an ordered list of column declarations (name, data type) • Constraints -- a list of constraints on the contents of the table

The CREATE TABLE Statement has the following general format:

CREATE TABLE table-name ({column-descr|constraint} [,{column-descr|constraint}]...)

table-name is the new name for the table. column-descr is a column declaration. constraint is a table constraint.

The column declaration can include optional column constraints. The declaration has the following general format:

column-name data-type [column-constraints] column-name is the name of the column and must be unique among the columns of the table. data-type declares the type of the column. Data types are described below. column-constraints is an optional list of column constraints with no separators.

Constraints Constraint specifications add additional restrictions on the contents of the table. They are automatically enforced by the DBMS. The column constraints are:

• NOT NULL -- specifies that the column can't be set to null. If this constraint is not specified, the column is nullable, that is, it can be set to null. Normally, primary key columns are declared as NOT NULL.

• PRIMARY KEY -- specifies that this column is the only column in the primary key. There can be only one primary key declaration in a CREATE TABLE. For primary keys with multiple columns, use the PRIMARY KEY table constraint. See Entity Integrity below for a detailed description of primary keys.

• UNIQUE -- specifies that this column has a unique value or null for all rows of the table. • REFERENCES -- specifies that this column is the only column in a foreign key. For foreign keys

with multiple columns, use the FOREIGN KEY table constraint. See Referential Integrity below for a detailed description of primary keys.

• CHECK -- specifies a user defined constraint on the table. See the table constraint - CHECK, below.

The table constraints are:

• PRIMARY KEY -- specifies the set of columns that comprise the primary key. There can be only one primary key declaration in a CREATE TABLE Statement. See Entity Integrity below for a detailed description of primary keys.

Page 101: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

• UNIQUE -- specifies that a set of columns have unique values (or nulls) for all rows in the table. The UNIQUE specifier is followed by a parenthesized list of column names, separated by commas.

• FOREIGN KEY -- specifies the set of columns in a foreign key. See Referential Integrity below for a detailed description of foreign keys.

• CHECK -- specifies a user defined constraint, known as a check condition. The CHECK specifier is followed by a predicate enclosed in parentheses. For Intermediate Level SQL92, the CHECK predicate can only reference columns from the current table row, with no subqueries. Many DBMSs support subqueries in the check predicate.

The check predicate must evaluate to true before a modification or addition of a row takes place. The check is effectively made on the contents of the table after the modification. For INSERT Statements, the predicate is evaluated as if the INSERT row were added to the table. For UPDATE Statements, the predicate is evaluated as if the row were updated. For DELETE Statements, the predicate is evaluated as if the row were deleted (Note: A check predicate is only useful for DELETE if a subquery is used.)

Data Type This subsection describes data type specifications. The data type categories are:

• Character (String) -- fixed or variable length character strings. The character set is implementation defined but often defaults to ASCII.

• Numeric -- values representing numeric quantities. Numeric values are divided into these two broad categories:

o Exact (also known as fixed-point) -- Exact numeric values have a fixed number of digits to the left of the decimal point and a fixed number of digits to the right (the scale). The total number of digits on both sides of the decimal are the precision. A special subset of exact numeric types with a scale of 0 is called integer.

o Approximate (also known as floating-point) -- Approximate numeric values that have a fixed precision (number of digits) but a floating decimal point.

All numeric types are signed.

• Datetime -- Datetime values include calendar and clock values (Date, Time, Timestamp) and intervals. The datetime types are:

o Date -- calendar date with year, month and day o Time -- clock time with hour, minute, second and fraction of second, plus a timezone

component (adjustment in hours, minutes) o Timestamp -- combination calendar date and clock time with year, month, day, hour,

minute, second and fraction of second, plus a timezone component (adjustment in hours, minutes)

o Interval -- intervals represent time and date intervals. They are signed. An interval value can contain a subset of the interval fields, for example - hour to minute, year, day to second. Interval types are subdivided into:

§ year-month intervals -- may contain years, months or combination years/months value.

§ day-time intervals -- days, hours, minutes, seconds, fractions of second.

Data type declarations have the following general format:

Character (String)

Page 102: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

CHAR [(length)] CHARACTER [(length)] VARCHAR (length) CHARACTER VARYING (length)

length specifies the number of characters for fixed size strings (CHAR, CHARACTER); spaces are supplied for shorter strings. If length is missing for fixed size strings, the default length is 1. For variable size strings (VARCHAR, CHARACTER VARYING), length is the maximum size of the string. Strings exceeding length are truncated on the right.

Numeric SMALLINT INT INTEGER

The integer types have default binary precision -- 15 for SMALLINT and 31 for INT, INTEGER. NUMERIC ( precision [, scale] ) DECIMAL ( precision [, scale] ) Fixed point types have a decimal precision (total number of digits) and scale (which cannot exceed the precision). The default scale is 0. NUMERIC scales must be represented exactly. DECIMAL values can be stored internally with a larger scale (implementation defined). FLOAT [(precision)] REAL DOUBLE The floating point types have a binary precision (maximum significant binary digits). Precision values are implementation dependent for REAL and DOUBLE, although the standard states that the default precision for DOUBLE must be larger than for REAL. FLOAT also uses an implementation defined default for precision (commonly this is the same as for REAL), but the binary precision for FLOAT can be explicit.

Datetime DATE TIME [(scale)] [WITH TIME ZONE] TIMESTAMP [(scale)] [WITH TIME ZONE]

TIME and TIMESTAMP allow an optional seconds fraction (scale). The default scale for TIME is 0, for TIMESTAMP 6. The optional WITH TIME ZONE specifier indicates that the timezone adjustment is stored with the value; if omitted, the current system timezone is assumed. INTERVAL interval-qualifier

Interval Qualifier An interval qualifier defines the specific type of an interval value. The qualifier for an interval type declares the sub-fields that comprise the interval, the precision of the highest (left-most) sub-field and the scale of the SECOND sub-field (if any).

Page 103: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

Intervals are divided into sub-types -- year-month intervals and day-time intervals. Year-month intervals can only contain the sub-fields - year and month. Day-time intervals can contain day, hour, minute, second. The interval qualifier has the following formats:

YEAR [(precision)] [ TO MONTH ] MONTH [(precision)] {DAY|HOUR|MINUTE} [(precision)] [ TO SECOND [(scale)] ] DAY [(precision)] [ TO {HOUR|MINUTE} ] HOUR [(precision)] [ TO MINUTE ] SECOND [ (precision [, scale]) ]

The default precision is 2. The default scale is 6.

Entity Integrity As mentioned earlier, the relational model requires that each base table have a Primary Key. SQL92, on the other hand, allows a table to created without a primary key. The advice here is to create all tables with primary keys.

A primary key is a constraint on the contents of a table. In relational terms, the primary key maintains Entity Integrity for the table. It constrains the table as follows,

• For a given row, the set of values for the primary key columns must be unique from all other rows in the table,

• No primary key column can contain a null, and • A table can have only one primary key (set of primary key columns).

Note: SQL92 does not require the second restriction on nulls in the primary key. However, it is required for a relational system.

Entity Integrity (Primary Keys) is enforced by the DBMS and ensures that every row has a proper unique identifier. The contents of any column in the table with Entity Integrity can be uniquely accessed with 3 pieces of information:

• table identifier • primary key value • column name

This capability is crucial to a relational system. Having a clear, consistent identifier for table rows (and their columns) distinguishes relational systems from all others. It allows the establishment of relationships between tables, also crucial to relational systems. This is discussed below under Referential Integrity.

The primary key constraint in the CREATE STATEMENT has two forms. When the primary key consists of a single column, it can be declared as a column constraint, simply - PRIMARY KEY, attached to the column descriptor. For example:

Page 104: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

sno VARCHAR(5) NOT NULL PRIMARY KEY As a table constraint, it has the following format:

PRIMARY KEY ( column-1 [, column-2] ...) column-1 and column-2 are the names of the columns of the primary key. For example,

PRIMARY KEY (sno, pno) The order of columns in the primary key is not significant, except as the default order for the FOREIGN KEY table constraint.

Referential Integrity Foreign keys provide relationships between tables in the database. In relational, a foreign key in a table is a set of columns that reference the primary key of another table. For each row in the referencing table, the foreign key must match an existing primary key in the referenced table. The enforcement of this constraint is known as Referential Integrity.

Referential Integrity requires that:

• The columns of a foreign key must match in number and type the columns of the primary key in the referenced table.

• The values of the foreign key columns in each row of the referencing table must match the values of the corresponding primary key columns for a row in the referenced table.

The one exception to the second restriction is when the foreign key columns for a row contain nulls. Since primary keys should not contain nulls, a foreign key with nulls cannot match any row in the referenced table. However, a row with a foreign key of all nulls (all foreign key columns contain null) is allowed in the referencing table. It is a null reference.

Like other constraints, the referential integrity constraint restricts the contents of the referencing table, but it also may in effect restrict the contents of the referenced table. When a row in a table is referenced (through its primary key) by a foreign key in a row in another table, operations that affect its primary key columns have side-effects and may restrict the operation. Changing the primary key of or deleting a row which has referencing foreign keys would violate the referential integrity constraints on the referencing table if allowec to proceed. This is handled in two ways,

• The referenced table is restricted from making the change (and violating referential integrity in the referencing table), or

• Rows in the referencing table are modified so the referential integrity constraint is maintained.

These actions are controlled by the referential integrity effects declarations, called referential triggers by SQL92. The referential integrity effect actions defined for SQL are:

• NO ACTION -- the change to the referenced (primary key) table is not performed. This is the default. • CASCADE -- the change to the referenced table is propagated to the referencing (foreign key)

table. • SET NULL -- the foreign key columns in the referencing table are set to null.

Page 105: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

Update and delete have separate action declarations. For CASCADE, update and delete also operate differently:

• For update (the primary key column values have been modified), the corresponding foreign key columns for referencing rows are set to the new values.

• For delete (the primary key row is deleted), the referencing rows are deleted.

A referential integrity constraint in the CREATE STATEMENT has two forms. When the foreign key consists of a single column, it can be declared as a column constraint, like:

column-descr REFERENCES references-specification As a table constraint, it has the following format:

FOREIGN KEY (column-list) REFERENCES references-specification column-list is the referencing table columns that comprise the foreign key. Commas separate column names in the list. Their order must match the explicit or implicit column list in the references-specification.

The references-specification has the following format: table-2 [ ( referenced-columns ) ] [ ON UPDATE { CASCADE | SET NULL | NO ACTION }] [ ON DELETE { CASCADE | SET NULL | NO ACTION }]

The order of the ON UPDATE and ON DELETE clauses may be reversed. These clauses declare the effect action when the referenced primary key is updated or deleted. The default for ON UPDATE and ON DELETE is NO ACTION.

table-2 is the referenced table name (primary key table). The optional referenced-columns list the columns of the referenced primary key. Commas separate column names in the list. The default is the primary key list in declaration order. Contrary to the relational model, SQL92 allows foreign keys to reference any set of columns declared with the UNIQUE constraint in the referenced table (even when the table has a primary key). In this case, the referenced-columns list is required. Example table constraint for referential integrity (for the sp table):

FOREIGN KEY (sno) REFERENCES s(sno) ON DELETE NO ACTION ON UPDATE CASCADE

CREATE TABLE Examples Creating the example tables:

CREATE TABLE s (sno VARCHAR(5) NOT NULL PRIMARY KEY, name VARCHAR(16), city VARCHAR(16) ) CREATE TABLE p (pno VARCHAR(5) NOT NULL PRIMARY KEY, descr VARCHAR(16),

Page 106: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

color VARCHAR(8) ) CREATE TABLE sp (sno VARCHAR(5) NOT NULL REFERENCES s, pno VARCHAR(5) NOT NULL REFERENCES p, qty INT, PRIMARY KEY (sno, pno) )

Create for sp with a constraint that the qty column can't be negative:

CREATE TABLE sp (sno VARCHAR(5) NOT NULL REFERENCES s, pno VARCHAR(5) NOT NULL REFERENCES p, qty INT CHECK (qty IS NULL OR qty >= 0), PRIMARY KEY (sno, pno) )

CREATE VIEW STATEMENT The CREATE VIEW statement creates a new database view. A view is effectively a SQL query stored in the catalog. The CREATE VIEW has the following general format:

CREATE VIEW view-name [ ( column-list ) ] AS query-1 [ WITH [CASCADED|LOCAL] CHECK OPTION ]

view-name is the name for the new view. column-list is an optional list of names for the columns of the view, comma separated. query-1 is any SELECT statement without an ORDER BY clause. The optional WITH CHECK OPTION clause is a constraint on updatable views.

column-list must have the same number of columns as the select list in query-1. If column-list is omitted, all items in the select list of query-1 must be named. In either case, duplicate column names are not allowed for a view. The optional WITH CHECK OPTION clause only applies to updatable views. It affects SQL INSERT and UPDATE statements. If WITH CHECK OPTION is specified, the WHERE predicate for query-1 must evaluate to true for the added row or the changed row. The CASCADED and LOCAL specifiers apply when the underlying table for query-1 is another view. CASCADED requests that WITH CHECK OPTION apply to all underlying views (to any level.) LOCAL requests that the current WITH CHECK OPTION apply only to this view. LOCAL is the default. CREATE VIEW Examples Parts with suppliers:

CREATE VIEW supplied_parts AS SELECT * FROM p WHERE pno IN (SELECT pno FROM sp) WITH CHECK OPTION

Page 107: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

Access example:

SELECT * FROM supplied_parts pno descr color

P1 Widget Red

P2 Widget Blue

Joined view:

CREATE VIEW part_locations (part, quantity, location) AS SELECT pno, qty, city FROM sp, s WHERE sp.sno = s.sno

Access examples:

SELECT * FROM part_locations part quantity location

P1 NULL Paris

P1 200 London

P1 1000 Rome

P2 200 Rome

SELECT part, quantity FROM part_locations WHERE location = 'Rome' part quantity

P1 1000

P2 200

DROP TABLE STATEMENT The DROP TABLE Statement removes a previously created table and its description from the catalog. It has the following general format:

DROP TABLE table-name {CASCADE|RESTRICT} table-name is the name of an existing base table in the current schema. The CASCADE and RESTRICT specifiers define the disposition of other objects dependent on the table. A base table may have two types of dependencies:

Page 108: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

• A view whose query specification references the drop table. • Another base table that references the drop table in a constraint - a CHECK constraint or

REFERENCES constraint.

RESTRICT specifies that the table not be dropped if any dependencies exist. If dependencies are found, an error is returned and the table isn't dropped.

CASCADE specifies that any dependencies are removed before the drop is performed:

• Views that reference the base table are dropped, and the sequence is repeated for their dependencies.

• Constraints in other tables that reference this table are dropped; the constraint is dropped but the table retained.

DROP VIEW STATEMENT The DROP VIEW Statement removes a previously created view and its description from the catalog. It has the following general format:

DROP VIEW view-name {CASCADE|RESTRICT} view-name is the name of an existing view in the current schema. The CASCADE and RESTRICT specifiers define the disposition of other objects dependent on the view. A view may have two types of dependencies:

• A view whose query specification references the drop view. • A base table that references the drop view in a constraint - a CHECK constraint.

RESTRICT specifies that the view not be dropped if any dependencies exist. If dependencies are found, an error is returned and the view isn't dropped.

CASCADE specifies that any dependencies are removed before the drop is performed:

• Views that reference the drop view are dropped, and the sequence is repeated for their dependencies.

• Constraints in base tables that reference this view are dropped; the constraint is dropped but the table retained.

GRANT STATEMENT The GRANT Statement grants access privileges for database objects to other users. It has the following general format:

GRANT privilege-list ON [TABLE] object-list TO user-list privilege-list is either ALL PRIVILEGES or a comma-separated list of properties: SELECT, INSERT, UPDATE, DELETE. object-list is a comma-separated list of table and view names. user-list is either PUBLIC or a comma-separated list of user names.

The GRANT statement grants each privilege in privilege-list for each object (table) in object-list to each user in user-list. In general, the access privileges apply to all columns in the table or view, but it is possible to specify a column list with the UPDATE privilege specifier:

Page 109: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

UPDATE [ ( column-1 [, column-2] ... ) ] If the optional column list is specified, UPDATE privileges are granted for those columns only.

The user-list may specify PUBLIC. This is a general grant, applying to all users (and future users) in the catalog. Privileges granted are revoked with the REVOKE Statement. The optional specificier WITH GRANT OPTION may follow user-list in the GRANT statement. WITH GRANT OPTION specifies that, in addition to access privileges, the privilege to grant those privileges to other users is granted. GRANT Statement Examples

GRANT SELECT ON s,sp TO PUBLIC GRANT SELECT,INSERT,UPDATE(color) ON p TO art,nan GRANT SELECT ON supplied_parts TO sam WITH GRANT OPTION

REVOKE STATEMENT The REVOKE Statement revokes access privileges for database objects previously granted to other users. It has the following general format:

REVOKE privilege-list ON [TABLE] object-list FROM user-list The REVOKE Statement revokes each privilege in privilege-list for each object (table) in object-list from each user in user-list. All privileges must have been previously granted.

The user-list may specify PUBLIC. This must apply to a previous GRANT TO PUBLIC. REVOKE Statement Examples

REVOKE SELECT ON s,sp FROM PUBLIC REVOKE SELECT,INSERT,UPDATE(color) ON p FROM art,nan REVOKE SELECT ON supplied_parts FROM sam

PL/SQL

PL/SQL CONTROL STRUCTURES Overview of PL/SQL Control Structures

Conditional Control: IF and CASE Statements

Iterative Control: LOOP and EXIT Statements

Sequential Control: GOTO and NULL Statements

OVERVIEW OF PL/SQL CONTROL STRUCTURES

Page 110: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

According to the structure theorem, any computer program can be written using the basic control structures shown in Figure 4-1. They can be combined in any way necessary to deal with a given problem.

Figure 4-1 Control Structures

Text description of the illustration pls81008_control_structures.gif

The selection structure tests a condition, then executes one sequence of statements instead of another, depending on whether the condition is true or false. A condition is any variable or expression that returns a Boolean value (TRUE or FALSE). The iteration structure executes a sequence of statements repeatedly as long as a condition holds true. The sequence structure simply executes a sequence of statements in the order in which they occur.

CONDITIONAL CONTROL: IF AND CASE STATEMENTS

Often, it is necessary to take alternative actions depending on circumstances. The IF statement lets you execute a sequence of statements conditionally. That is, whether the sequence is executed or not depends on the value of a condition. There are three forms of IF statements: IF-THEN, IF-THEN-ELSE, and IF-THEN-ELSIF. The CASE statement is a compact way to evaluate a single condition and choose between many alternative actions.

IF-THEN STATEMENT

The simplest form of IF statement associates a condition with a sequence of statements enclosed by the keywords THEN and END IF (not ENDIF), as follows:

IF condition THEN sequence_of_statements END IF;

The sequence of statements is executed only if the condition is true. If the condition is false or null, the IF statement does nothing. In either case, control passes to the next statement. An example follows:

Page 111: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

IF sales > quota THEN compute_bonus(empid); UPDATE payroll SET pay = pay + bonus WHERE empno = emp_id; END IF;

You might want to place brief IF statements on a single line, as in

IF x > y THEN high := x; END IF;

IF-THEN-ELSE STATEMENT

The second form of IF statement adds the keyword ELSE followed by an alternative sequence of statements, as follows:

IF condition THEN sequence_of_statements1 ELSE sequence_of_statements2 END IF;

The sequence of statements in the ELSE clause is executed only if the condition is false or null. Thus, the ELSE clause ensures that a sequence of statements is executed. In the following example, the first UPDATE statement is executed when the condition is true, but the second UPDATE statement is executed when the condition is false or null:

IF trans_type = 'CR' THEN UPDATE accounts SET balance = balance + credit WHERE ... ELSE UPDATE accounts SET balance = balance - debit WHERE ... END IF;

The THEN and ELSE clauses can include IF statements. That is, IF statements can be nested, as the following example shows:

IF trans_type = 'CR' THEN UPDATE accounts SET balance = balance + credit WHERE ... ELSE IF new_balance >= minimum_balance THEN UPDATE accounts SET balance = balance - debit WHERE ... ELSE RAISE insufficient_funds; END IF; END IF;

Page 112: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

IF-THEN-ELSIF STATEMENT

Sometimes you want to select an action from several mutually exclusive alternatives. The third form of IF statement uses the keyword ELSIF (not ELSEIF) to introduce additional conditions, as follows:

IF condition1 THEN sequence_of_statements1 ELSIF condition2 THEN sequence_of_statements2 ELSE sequence_of_statements3 END IF;

If the first condition is false or null, the ELSIF clause tests another condition. An IF statement can have any number of ELSIF clauses; the final ELSE clause is optional. Conditions are evaluated one by one from top to bottom. If any condition is true, its associated sequence of statements is executed and control passes to the next statement. If all conditions are false or null, the sequence in the ELSE clause is executed. Consider the following example:

BEGIN ... IF sales > 50000 THEN bonus := 1500; ELSIF sales > 35000 THEN bonus := 500; ELSE bonus := 100; END IF; INSERT INTO payroll VALUES (emp_id, bonus, ...); END;

If the value of sales is larger than 50000, the first and second conditions are true. Nevertheless, bonus is assigned the proper value of 1500 because the second condition is never tested. When the first condition is true, its associated statement is executed and control passes to the INSERT statement.

CASE STATEMENT

Like the IF statement, the CASE statement selects one sequence of statements to execute. However, to select the sequence, the CASE statement uses a selector rather than multiple Boolean expressions. (Recall from Chapter 2 that a selector is an expression whose value is used to select one of several

Page 113: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

alternatives.) To compare the IF and CASE statements, consider the following code that outputs descriptions of school grades:

IF grade = 'A' THEN dbms_output.put_line('Excellent'); ELSIF grade = 'B' THEN dbms_output.put_line('Very Good'); ELSIF grade = 'C' THEN dbms_output.put_line('Good'); ELSIF grade = 'D' THEN dbms_output. put_line('Fair'); ELSIF grade = 'F' THEN dbms_output.put_line('Poor'); ELSE dbms_output.put_line('No such grade'); END IF;

Notice the five Boolean expressions. In each instance, we test whether the same variable, grade, is equal to one of five values: 'A', 'B', 'C', 'D', or 'F'. Let us rewrite the preceding code using the CASE statement, as follows:

CASE grade WHEN 'A' THEN dbms_output.put_line('Excellent'); WHEN 'B' THEN dbms_output.put_line('Very Good'); WHEN 'C' THEN dbms_output.put_line('Good'); WHEN 'D' THEN dbms_output.put_line('Fair'); WHEN 'F' THEN dbms_output.put_line('Poor'); ELSE dbms_output.put_line('No such grade'); END CASE;

The CASE statement is more readable and more efficient. So, when possible, rewrite lengthy IF-THEN-ELSIF statements as CASE statements.

The CASE statement begins with the keyword CASE. The keyword is followed by a selector, which is the variable grade in the last example. The selector expression can be arbitrarily complex. For example, it can contain function calls. Usually, however, it consists of a single variable. The selector expression is evaluated only once. The value it yields can have any PL/SQL datatype other than BLOB, BFILE, an object type, a PL/SQL record, an index-by-table, a varray, or a nested table.

The selector is followed by one or more WHEN clauses, which are checked sequentially. The value of the selector determines which clause is executed. If the value of the selector equals the value of a WHEN-clause expression, that WHEN clause is executed. For instance, in the last example,

Page 114: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

if grade equals 'C', the program outputs 'Good'. Execution never falls through; if any WHEN clause is executed, control passes to the next statement.

The ELSE clause works similarly to the ELSE clause in an IF statement. In the last example, if the grade is not one of the choices covered by a WHEN clause, the ELSE clause is selected, and the phrase 'No such grade' is output. The ELSE clause is optional. However, if you omit the ELSE clause, PL/SQL adds the following implicit ELSE clause:

ELSE RAISE CASE_NOT_FOUND;

If the CASE statement selects the implicit ELSE clause, PL/SQL raises the predefined exception CASE_NOT_FOUND. So, there is always a default action, even when you omit the ELSE clause.

The keywords END CASE terminate the CASE statement. These two keywords must be separated by a space. The CASE statement has the following form:

[<<label_name>>] CASE selector WHEN expression1 THEN sequence_of_statements1; WHEN expression2 THEN sequence_of_statements2; ... WHEN expressionN THEN sequence_of_statementsN; [ELSE sequence_of_statementsN+1;] END CASE [label_name];

Like PL/SQL blocks, CASE statements can be labeled. The label, an undeclared identifier enclosed by double angle brackets, must appear at the beginning of the CASE statement. Optionally, the label name can also appear at the end of the CASE statement.

Exceptions raised during the execution of a CASE statement are handled in the usual way. That is, normal execution stops and control transfers to the exception-handling part of your PL/SQL block or subprogram.

An alternative to the CASEstatement is the CASE expression, where each WHEN clause is an expression. For details, see "CASE Expressions".

Searched CASE Statement

PL/SQL also provides a searched CASE statement, which has the form:

[<<label_name>>] CASE

Page 115: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

WHEN search_condition1 THEN sequence_of_statements1; WHEN search_condition2 THEN sequence_of_statements2; ... WHEN search_conditionN THEN sequence_of_statementsN; [ELSE sequence_of_statementsN+1;] END CASE [label_name];

The searched CASE statement has no selector. Also, its WHEN clauses contain search conditions that yield a Boolean value, not expressions that can yield a value of any type. An example follows:

CASE WHEN grade = 'A' THEN dbms_output.put_line('Excellent'); WHEN grade = 'B' THEN dbms_output.put_line('Very Good'); WHEN grade = 'C' THEN dbms_output.put_line('Good'); WHEN grade = 'D' THEN dbms_output.put_line('Fair'); WHEN grade = 'F' THEN dbms_output.put_line('Poor'); ELSE dbms_output.put_line('No such grade'); END CASE;

The search conditions are evaluated sequentially. The Boolean value of each search condition determines which WHEN clause is executed. If a search condition yields TRUE, its WHEN clause is executed. If any WHEN clause is executed, control passes to the next statement, so subsequent search conditions are not evaluated.

If none of the search conditions yields TRUE, the ELSE clause is executed. The ELSE clause is optional. However, if you omit the ELSE clause, PL/SQL adds the following implicit ELSE clause:

ELSE RAISE CASE_NOT_FOUND;

Exceptions raised during the execution of a searched CASE statement are handled in the usual way. That is, normal execution stops and control transfers to the exception-handling part of your PL/SQL block or subprogram.

GUIDELINES FOR PL/SQL CONDITIONAL STATEMENTS

Avoid clumsy IF statements like those in the following example:

IF new_balance < minimum_balance THEN overdrawn := TRUE; ELSE overdrawn := FALSE; END IF; ...

Page 116: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

IF overdrawn = TRUE THEN RAISE insufficient_funds; END IF;

This code disregards two useful facts. First, the value of a Boolean expression can be assigned directly to a Boolean variable. So, you can replace the first IF statement with a simple assignment, as follows:

overdrawn := new_balance < minimum_balance;

Second, a Boolean variable is itself either true or false. So, you can simplify the condition in the second IF statement, as follows:

IF overdrawn THEN ...

When possible, use the ELSIF clause instead of nested IF statements. That way, your code will be easier to read and understand. Compare the following IF statements:

IF condition1 THEN | IF condition1 THEN statement1; | statement1; ELSE | ELSIF condition2 THEN IF condition2 THEN | statement2; statement2; | ELSIF condition3 THEN ELSE | statement3; IF condition3 THEN | END IF; statement3; | END IF; | END IF; | END IF; |

These statements are logically equivalent, but the first statement obscures the flow of logic, whereas the second statement reveals it.

If you are comparing a single expression to multiple values, you can simplify the logic by using a single CASE statement instead of an IF with several ELSIF clauses.

ITERATIVE CONTROL: LOOP AND EXIT STATEMENTS

LOOP statements let you execute a sequence of statements multiple times. There are three forms of LOOP statements: LOOP, WHILE-LOOP, and FOR-LOOP.

LOOP

Page 117: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

The simplest form of LOOP statement is the basic (or infinite) loop, which encloses a sequence of statements between the keywords LOOP and END LOOP, as follows:

LOOP sequence_of_statements END LOOP;

With each iteration of the loop, the sequence of statements is executed, then control resumes at the top of the loop. If further processing is undesirable or impossible, you can use an EXIT statement to complete the loop. You can place one or more EXIT statements anywhere inside a loop, but nowhere outside a loop. There are two forms of EXIT statements: EXIT and EXIT-WHEN.

EXIT

The EXIT statement forces a loop to complete unconditionally. When an EXIT statement is encountered, the loop completes immediately and control passes to the next statement. An example follows:

LOOP ... IF credit_rating < 3 THEN ... EXIT; -- exit loop immediately END IF; END LOOP; -- control resumes here

The next example shows that you cannot use the EXIT statement to complete a PL/SQL block:

BEGIN ... IF credit_rating < 3 THEN ... EXIT; -- not allowed END IF; END;

Remember, the EXIT statement must be placed inside a loop. To complete a PL/SQL block before its normal end is reached, you can use the RETURN statement. For more information, see "Using the RETURN Statement".

EXIT-WHEN

Page 118: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

The EXIT-WHEN statement lets a loop complete conditionally. When the EXIT statement is encountered, the condition in the WHEN clause is evaluated. If the condition is true, the loop completes and control passes to the next statement after the loop. An example follows:

LOOP FETCH c1 INTO ... EXIT WHEN c1%NOTFOUND; -- exit loop if condition is true ... END LOOP; CLOSE c1;

Until the condition is true, the loop cannot complete. So, a statement inside the loop must change the value of the condition. In the last example, if the FETCH statement returns a row, the condition is false. When the FETCH statement fails to return a row, the condition is true, the loop completes, and control passes to the CLOSE statement.

The EXIT-WHEN statement replaces a simple IF statement. For example, compare the following statements:

IF count > 100 THEN | EXIT WHEN count > 100; EXIT; | END IF; |

These statements are logically equivalent, but the EXIT-WHEN statement is easier to read and understand.

Loop Labels

Like PL/SQL blocks, loops can be labeled. The label, an undeclared identifier enclosed by double angle brackets, must appear at the beginning of the LOOP statement, as follows:

<<label_name>> LOOP sequence_of_statements END LOOP;

Optionally, the label name can also appear at the end of the LOOP statement, as the following example shows:

<<my_loop>> LOOP ... END LOOP my_loop;

Page 119: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

When you nest labeled loops, use ending label names to improve readability.

With either form of EXIT statement, you can complete not only the current loop, but any enclosing loop. Simply label the enclosing loop that you want to complete. Then, use the label in an EXIT statement, as follows:

<<outer>> LOOP ... LOOP ... EXIT outer WHEN ... -- exit both loops END LOOP; ... END LOOP outer;

Every enclosing loop up to and including the labeled loop is exited.

WHILE-LOOP

The WHILE-LOOP statement associates a condition with a sequence of statements enclosed by the keywords LOOP and END LOOP, as follows:

WHILE condition LOOP sequence_of_statements END LOOP;

Before each iteration of the loop, the condition is evaluated. If the condition is true, the sequence of statements is executed, then control resumes at the top of the loop. If the condition is false or null, the loop is bypassed and control passes to the next statement. An example follows:

WHILE total <= 25000 LOOP ... SELECT sal INTO salary FROM emp WHERE ... total := total + salary; END LOOP;

The number of iterations depends on the condition and is unknown until the loop completes. The condition is tested at the top of the loop, so the sequence might execute zero times. In the last example, if the initial value of total is larger than 25000, the condition is false and the loop is bypassed.

Page 120: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

Some languages have a LOOP UNTIL or REPEAT UNTIL structure, which tests the condition at the bottom of the loop instead of at the top. Therefore, the sequence of statements is executed at least once. PL/SQL has no such structure, but you can easily build one, as follows:

LOOP sequence_of_statements EXIT WHEN boolean_expression; END LOOP;

To ensure that a WHILE loop executes at least once, use an initialized Boolean variable in the condition, as follows:

done := FALSE; WHILE NOT done LOOP sequence_of_statements done := boolean_expression; END LOOP;

A statement inside the loop must assign a new value to the Boolean variable. Otherwise, you have an infinite loop. For example, the following LOOP statements are logically equivalent:

WHILE TRUE LOOP | LOOP ... | ... END LOOP; | END LOOP;

FOR-LOOP

Whereas the number of iterations through a WHILE loop is unknown until the loop completes, the number of iterations through a FOR loop is known before the loop is entered. FOR loops iterate over a specified range of integers. The range is part of an iteration scheme, which is enclosed by the keywords FOR and LOOP. A double dot (..) serves as the range operator. The syntax follows:

FOR counter IN [REVERSE] lower_bound..higher_bound LOOP sequence_of_statements END LOOP;

The range is evaluated when the FOR loop is first entered and is never re-evaluated.

As the next example shows, the sequence of statements is executed once for each integer in the range. After each iteration, the loop counter is incremented.

FOR i IN 1..3 LOOP -- assign the values 1,2,3 to i sequence_of_statements -- executes three times

Page 121: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

END LOOP;

The following example shows that if the lower bound equals the higher bound, the sequence of statements is executed once:

FOR i IN 3..3 LOOP -- assign the value 3 to i sequence_of_statements -- executes one time END LOOP;

By default, iteration proceeds upward from the lower bound to the higher bound. However, as the example below shows, if you use the keyword REVERSE, iteration proceeds downward from the higher bound to the lower bound. After each iteration, the loop counter is decremented. Nevertheless, you write the range bounds in ascending (not descending) order.

FOR i IN REVERSE 1..3 LOOP -- assign the values 3,2,1 to i sequence_of_statements -- executes three times END LOOP;

Inside a FOR loop, the loop counter can be referenced like a constant but cannot be assigned values, as the following example shows:

FOR ctr IN 1..10 LOOP IF NOT finished THEN INSERT INTO ... VALUES (ctr, ...); -- legal factor := ctr * 2; -- legal ELSE ctr := 10; -- not allowed END IF; END LOOP; Iteration Schemes

The bounds of a loop range can be literals, variables, or expressions but must evaluate to numbers. Otherwise, PL/SQL raises the predefined exception VALUE_ERROR. The lower bound need not be 1, as the examples below show. However, the loop counter increment (or decrement) must be 1.

j IN -5..5 k IN REVERSE first..last step IN 0..TRUNC(high/low) * 2

Internally, PL/SQL assigns the values of the bounds to temporary PLS_INTEGER variables, and, if necessary, rounds the values to the nearest integer. The magnitude range of a PLS_INTEGER is -

Page 122: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

2**31 .. 2**31. So, if a bound evaluates to a number outside that range, you get a numeric overflow error when PL/SQL attempts the assignment, as the following example shows:

DECLARE hi NUMBER := 2**32; BEGIN FOR j IN 1..hi LOOP -- causes a 'numeric overflow' error ... END LOOP; END;

Some languages provide a STEP clause, which lets you specify a different increment (5 instead of 1 for example). PL/SQL has no such structure, but you can easily build one. Inside the FOR loop, simply multiply each reference to the loop counter by the new increment. In the following example, you assign today's date to elements 5, 10, and 15 of an index-by table:

DECLARE TYPE DateList IS TABLE OF DATE INDEX BY BINARY_INTEGER; dates DateList; k CONSTANT INTEGER := 5; -- set new increment BEGIN FOR j IN 1..3 LOOP dates(j*k) := SYSDATE; -- multiply loop counter by increment END LOOP; ... END; Dynamic Ranges

PL/SQL lets you determine the loop range dynamically at run time, as the following example shows:

SELECT COUNT(empno) INTO emp_count FROM emp; FOR i IN 1..emp_count LOOP ... END LOOP;

The value of emp_count is unknown at compile time; the SELECT statement returns the value at run time.

What happens if the lower bound of a loop range evaluates to a larger integer than the upper bound? As the next example shows, the sequence of statements within the loop is not executed and control passes to the next statement:

-- limit becomes 1

Page 123: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

FOR i IN 2..limit LOOP sequence_of_statements -- executes zero times END LOOP; -- control passes here Scope Rules

The loop counter is defined only within the loop. You cannot reference it outside the loop. After the loop is exited, the loop counter is undefined, as the following example shows:

FOR ctr IN 1..10 LOOP ... END LOOP; sum := ctr - 1; -- not allowed

You need not explicitly declare the loop counter because it is implicitly declared as a local variable of type INTEGER. The next example shows that the local declaration hides any global declaration:

DECLARE ctr INTEGER; BEGIN ... FOR ctr IN 1..25 LOOP ... IF ctr > 10 THEN ... -- refers to loop counter END LOOP; END;

To reference the global variable in this example, you must use a label and dot notation, as follows:

<<main>> DECLARE ctr INTEGER; ... BEGIN ... FOR ctr IN 1..25 LOOP ... IF main.ctr > 10 THEN -- refers to global variable ... END IF; END LOOP; END main;

Page 124: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

The same scope rules apply to nested FOR loops. Consider the example below. Both loop counters have the same name. So, to reference the outer loop counter from the inner loop, you must use a label and dot notation, as follows:

<<outer>> FOR step IN 1..25 LOOP FOR step IN 1..10 LOOP ... IF outer.step > 15 THEN ... END LOOP; END LOOP outer; Using the EXIT Statement

The EXIT statement lets a FOR loop complete prematurely. For example, the following loop normally executes ten times, but as soon as the FETCH statement fails to return a row, the loop completes no matter how many times it has executed:

FOR j IN 1..10 LOOP FETCH c1 INTO emp_rec; EXIT WHEN c1%NOTFOUND; ... END LOOP;

Suppose you must exit from a nested FOR loop prematurely. You can complete not only the current loop, but any enclosing loop. Simply label the enclosing loop that you want to complete. Then, use the label in an EXIT statement to specify which FOR loop to exit, as follows:

<<outer>> FOR i IN 1..5 LOOP ... FOR j IN 1..10 LOOP FETCH c1 INTO emp_rec; EXIT outer WHEN c1%NOTFOUND; -- exit both FOR loops ... END LOOP; END LOOP outer; -- control passes here

SEQUENTIAL CONTROL: GOTO AND NULL STATEMENTS

Unlike the IF and LOOP statements, the GOTO and NULL statements are not crucial to PL/SQL programming. The structure of PL/SQL is such that the GOTO statement is seldom needed. Occasionally, it can simplify logic enough to warrant its use. The NULL statement can improve readability by making the meaning and action of conditional statements clear.

Page 125: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

Overuse of GOTO statements can result in complex, unstructured code (sometimes called spaghetti code) that is hard to understand and maintain. So, use GOTO statements sparingly. For example, to branch from a deeply nested structure to an error-handling routine, raise an exception rather than use a GOTO statement.

GOTO STATEMENT

The GOTO statement branches to a label unconditionally. The label must be unique within its scope and must precede an executable statement or a PL/SQL block. When executed, the GOTO statement transfers control to the labeled statement or block. In the following example, you go to an executable statement farther down in a sequence of statements:

BEGIN ... GOTO insert_row; ... <<insert_row>> INSERT INTO emp VALUES ... END;

In the next example, you go to a PL/SQL block farther up in a sequence of statements:

BEGIN ... <<update_row>> BEGIN UPDATE emp SET ... ... END; ... GOTO update_row; ... END;

The label end_loop in the following example is not allowed because it does not precede an executable statement:

DECLARE done BOOLEAN; BEGIN ... FOR i IN 1..50 LOOP IF done THEN GOTO end_loop;

Page 126: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

END IF; ... <<end_loop>> -- not allowed END LOOP; -- not an executable statement END;

To debug the last example, just add the NULL statement, as follows:

FOR i IN 1..50 LOOP IF done THEN GOTO end_loop; END IF; ... <<end_loop>> NULL; -- an executable statement END LOOP;

As the following example shows, a GOTO statement can branch to an enclosing block from the current block:

DECLARE my_ename CHAR(10); BEGIN <<get_name>> SELECT ename INTO my_ename FROM emp WHERE ... BEGIN ... GOTO get_name; -- branch to enclosing block END; END;

The GOTO statement branches to the first enclosing block in which the referenced label appears.

Restrictions

Some possible destinations of a GOTO statement are not allowed. Specifically, a GOTO statement cannot branch into an IF statement, CASE statement, LOOP statement, or sub-block. For example, the following GOTO statement is not allowed:

BEGIN ... GOTO update_row; -- can't branch into IF statement ...

Page 127: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

IF valid THEN ... <<update_row>> UPDATE emp SET ... END IF; END;

As the example below shows, a GOTO statement cannot branch from one IF statement clause to another. Likewise, a GOTO statement cannot branch from one CASE statement WHEN clause to another.

BEGIN ... IF valid THEN ... GOTO update_row; -- can't branch into ELSE clause ELSE ... <<update_row>> UPDATE emp SET ... END IF; END;

The next example shows that a GOTO statement cannot branch from an enclosing block into a sub-block:

BEGIN ... IF status = 'OBSOLETE' THEN GOTO delete_part; -- can't branch into sub-block END IF; ... BEGIN ... <<delete_part>> DELETE FROM parts WHERE ... END; END;

Also, a GOTO statement cannot branch out of a subprogram, as the following example shows:

DECLARE ...

Page 128: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

PROCEDURE compute_bonus (emp_id NUMBER) IS BEGIN ... GOTO update_row; -- can't branch out of subprogram END; BEGIN ... <<update_row>> UPDATE emp SET ... END;

Finally, a GOTO statement cannot branch from an exception handler into the current block. For example, the following GOTO statement is not allowed:

DECLARE ... pe_ratio REAL; BEGIN ... SELECT price / NVL(earnings, 0) INTO pe_ratio FROM ... <<insert_row>> INSERT INTO stats VALUES (pe_ratio, ...); EXCEPTION WHEN ZERO_DIVIDE THEN pe_ratio := 0; GOTO insert_row; -- can't branch into current block END;

However, a GOTO statement can branch from an exception handler into an enclosing block.

NULL STATEMENT

The NULL statement does nothing other than pass control to the next statement. In a conditional construct, the NULL statement tells readers that a possibility has been considered, but no action is necessary. In the following example, the NULL statement shows that no action is taken for unnamed exceptions:

EXCEPTION WHEN ZERO_DIVIDE THEN ROLLBACK; WHEN VALUE_ERROR THEN INSERT INTO errors VALUES ... COMMIT; WHEN OTHERS THEN

Page 129: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

NULL; END;

In IF statements or other places that require at least one executable statement, the NULL statement to satisfy the syntax. In the following example, the NULL statement emphasizes that only top-rated employees get bonuses:

IF rating > 90 THEN compute_bonus(emp_id); ELSE NULL; END IF;

Also, the NULL statement is a handy way to create stubs when designing applications from the top down. A stub is dummy subprogram that lets you defer the definition of a procedure or function until you test and debug the main program. In the following example, the NULL statement meets the requirement that at least one statement must appear in the executable part of a subprogram:

PROCEDURE debit_account (acct_id INTEGER, amount REAL) IS BEGIN NULL; END debit_account;

PL/SQL

PL/SQL is a procedural language designed specifically to embrace SQL statements within its syntax. PL/SQL program units are compiled by the Oracle Database server and stored inside the database. And at run-time, both PL/SQL and SQL run within the same server process, bringing

Page 130: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

optimal efficiency. PL/SQL automatically inherits the robustness, security, and portability of the Oracle Database.

WHY USE PL/SQL? An application that uses Oracle Database is worthless unless only correct and complete data is persisted. The time-honored way to ensure this is to expose the database only via an interface that hides the implementation details -- the tables and the SQL statements that operate on these. This approach is generally called the thick database paradigm, because PL/SQL subprograms inside the database issue the SQL statements from code that implements the surrounding business logic; and because the data can be changed and viewed only through a PL/SQL interface. Bryn Llewellyn, Distinguished Product Manager for PL/SQL and Edition-based Redefinition, explains the thick database approach in detail in his "Why use PL/SQL?" whitepaper.

6. Cursor

A cursor is a pointer to this context area. PL/SQL controls the context area through a cursor. A cursor holds the rows (one or more) returned by a SQL statement. The set of rows the cursor holds is referred to as the active set.

You can name a cursor so that it could be referred to in a program to fetch and process the rows returned by the SQL statement, one at a time. There are two types of cursors −

• Implicit cursors

• Explicit cursors

IMPLICIT CURSORS

Implicit cursors are automatically created by Oracle whenever an SQL statement is executed, when there is no explicit cursor for the statement. Programmers cannot control the implicit cursors and the information in it.

Whenever a DML statement (INSERT, UPDATE and DELETE) is issued, an implicit cursor is associated with this statement. For INSERT operations, the cursor holds the data that needs to be inserted. For UPDATE and DELETE operations, the cursor identifies the rows that would be affected.

In PL/SQL, you can refer to the most recent implicit cursor as the SQL cursor, which always has attributes such as %FOUND, %ISOPEN, %NOTFOUND, and %ROWCOUNT. The SQL cursor has additional attributes, %BULK_ROWCOUNT and %BULK_EXCEPTIONS, designed

Page 131: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

for use with the FORALL statement. The following table provides the description of the most used attributes −

S.No Attribute & Description

1

%FOUND

Returns TRUE if an INSERT, UPDATE, or DELETE statement affected one or more rows or a SELECT INTO statement returned one or more rows. Otherwise, it returns FALSE.

2

%NOTFOUND

The logical opposite of %FOUND. It returns TRUE if an INSERT, UPDATE, or DELETE statement affected no rows, or a SELECT INTO statement returned no rows. Otherwise, it returns FALSE.

3

%ISOPEN

Always returns FALSE for implicit cursors, because Oracle closes the SQL cursor automatically after executing its associated SQL statement.

4

%ROWCOUNT

Returns the number of rows affected by an INSERT, UPDATE, or DELETE statement, or returned by a SELECT INTO statement.

Any SQL cursor attribute will be accessed as sql%attribute_name as shown below in the example.

EXAMPLE

We will be using the CUSTOMERS table we had created and used in the previous chapters.

Select * from customers; +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+

Page 132: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

| 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | +----+----------+-----+-----------+----------+

The following program will update the table and increase the salary of each customer by 500 and use the SQL%ROWCOUNT attribute to determine the number of rows affected −

DECLARE

total_rows number(2);

BEGIN

UPDATE customers

SET salary = salary + 500;

IF sql%notfound THEN

dbms_output.put_line('no customers selected');

ELSIF sql%found THEN

total_rows := sql%rowcount;

dbms_output.put_line( total_rows || ' customers selected ');

END IF;

END;

/

When the above code is executed at the SQL prompt, it produces the following result −

6 customers selected PL/SQL procedure successfully completed.

If you check the records in customers table, you will find that the rows have been updated −

Select * from customers; +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2500.00 |

Page 133: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

| 2 | Khilan | 25 | Delhi | 2000.00 | | 3 | kaushik | 23 | Kota | 2500.00 | | 4 | Chaitali | 25 | Mumbai | 7000.00 | | 5 | Hardik | 27 | Bhopal | 9000.00 | | 6 | Komal | 22 | MP | 5000.00 | +----+----------+-----+-----------+----------+

EXPLICIT CURSORS

Explicit cursors are programmer-defined cursors for gaining more control over the context area. An explicit cursor should be defined in the declaration section of the PL/SQL Block. It is created on a SELECT Statement which returns more than one row.

The syntax for creating an explicit cursor is −

CURSOR cursor_name IS select_statement;

Working with an explicit cursor includes the following steps −

• Declaring the cursor for initializing the memory

• Opening the cursor for allocating the memory

• Fetching the cursor for retrieving the data

• Closing the cursor to release the allocated memory

DECLARING THE CURSOR

Declaring the cursor defines the cursor with a name and the associated SELECT statement. For example −

CURSOR c_customers IS

SELECT id, name, address FROM customers;

OPENING THE CURSOR

Opening the cursor allocates the memory for the cursor and makes it ready for fetching the rows returned by the SQL statement into it. For example, we will open the above defined cursor as follows −

OPEN c_customers;

FETCHING THE CURSOR

Fetching the cursor involves accessing one row at a time. For example, we will fetch rows from the above-opened cursor as follows −

Page 134: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

FETCH c_customers INTO c_id, c_name, c_addr;

CLOSING THE CURSOR

Closing the cursor means releasing the allocated memory. For example, we will close the above-opened cursor as follows −

CLOSE c_customers;

EXAMPLE

Following is a complete example to illustrate the concepts of explicit cursors &minua;

DECLARE

c_id customers.id%type;

c_name customerS.No.ame%type;

c_addr customers.address%type;

CURSOR c_customers is

SELECT id, name, address FROM customers;

BEGIN

OPEN c_customers;

LOOP

FETCH c_customers into c_id, c_name, c_addr;

EXIT WHEN c_customers%notfound;

dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_addr);

END LOOP;

CLOSE c_customers;

END;

/

When the above code is executed at the SQL prompt, it produces the following result −

1 Ramesh Ahmedabad 2 Khilan Delhi 3 kaushik Kota 4 Chaitali Mumbai 5 Hardik Bhopal

Page 135: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

6 Komal MP PL/SQL procedure successfully completed.

7. Procedures

A subprogram is a program unit/module that performs a particular task. These subprograms are combined to form larger programs. This is basically called the 'Modular design'. A subprogram can be invoked by another subprogram or program which is called the calling program.

A subprogram can be created −

• At the schema level

• Inside a package

• Inside a PL/SQL block

At the schema level, subprogram is a standalone subprogram. It is created with the CREATE PROCEDURE or the CREATE FUNCTION statement. It is stored in the database and can be deleted with the DROP PROCEDURE or DROP FUNCTION statement.

A subprogram created inside a package is a packaged subprogram. It is stored in the database and can be deleted only when the package is deleted with the DROP PACKAGE statement. We will discuss packages in the chapter 'PL/SQL - Packages'.

PL/SQL subprograms are named PL/SQL blocks that can be invoked with a set of parameters. PL/SQL provides two kinds of subprograms −

• Functions − These subprograms return a single value; mainly used to compute and return a value.

• Procedures − These subprograms do not return a value directly; mainly used to perform an action.

This chapter is going to cover important aspects of a PL/SQL procedure. We will discuss PL/SQL function in the next chapter.

Page 136: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

PARTS OF A PL/SQL SUBPROGRAM

Each PL/SQL subprogram has a name, and may also have a parameter list. Like anonymous PL/SQL blocks, the named blocks will also have the following three parts −

S.No Parts & Description

1

Declarative Part

It is an optional part. However, the declarative part for a subprogram does not start with the DECLARE keyword. It contains declarations of types, cursors, constants, variables, exceptions, and nested subprograms. These items are local to the subprogram and cease to exist when the subprogram completes execution.

2 Executable Part

This is a mandatory part and contains statements that perform the designated action.

3 Exception-handling

This is again an optional part. It contains the code that handles run-time errors.

CREATING A PROCEDURE

A procedure is created with the CREATE OR REPLACE PROCEDURE statement. The simplified syntax for the CREATE OR REPLACE PROCEDURE statement is as follows −

CREATE [OR REPLACE] PROCEDURE procedure_name

[(parameter_name [IN | OUT | IN OUT] type [, ...])]

{IS | AS}

BEGIN

< procedure_body >

END procedure_name;

Where,

• procedure-name specifies the name of the procedure.

Page 137: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

• [OR REPLACE] option allows the modification of an existing procedure.

• The optional parameter list contains name, mode and types of the parameters. IN represents the value that will be passed from outside and OUT represents the parameter that will be used to return a value outside of the procedure.

• procedure-body contains the executable part.

• The AS keyword is used instead of the IS keyword for creating a standalone procedure.

EXAMPLE

The following example creates a simple procedure that displays the string 'Hello World!' on the screen when executed.

CREATE OR REPLACE PROCEDURE greetings

AS

BEGIN

dbms_output.put_line('Hello World!');

END;

/

When the above code is executed using the SQL prompt, it will produce the following result −

Procedure created.

EXECUTING A STANDALONE PROCEDURE

A standalone procedure can be called in two ways −

• Using the EXECUTE keyword

• Calling the name of the procedure from a PL/SQL block

The above procedure named 'greetings' can be called with the EXECUTE keyword as −

EXECUTE greetings;

The above call will display −

Hello World

Page 138: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

PL/SQL procedure successfully completed.

The procedure can also be called from another PL/SQL block −

BEGIN

greetings;

END;

/

The above call will display −

Hello World PL/SQL procedure successfully completed.

DELETING A STANDALONE PROCEDURE

A standalone procedure is deleted with the DROP PROCEDURE statement. Syntax for deleting a procedure is −

DROP PROCEDURE procedure-name;

You can drop the greetings procedure by using the following statement −

DROP PROCEDURE greetings;

PARAMETER MODES IN PL/SQL SUBPROGRAMS

The following table lists out the parameter modes in PL/SQL subprograms −

S.No Parameter Mode & Description

1

IN

An IN parameter lets you pass a value to the subprogram. It is a read-only parameter. Inside the subprogram, an IN parameter acts like a constant. It cannot be assigned a value. You can pass a constant, literal, initialized variable, or expression as an IN parameter. You can also initialize it to a default value; however, in that case, it is omitted from the subprogram call. It is the default mode of parameter passing. Parameters are passed by reference.

Page 139: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

2

OUT

An OUT parameter returns a value to the calling program. Inside the subprogram, an OUT parameter acts like a variable. You can change its value and reference the value after assigning it. The actual parameter must be variable and it is passed by value.

3

IN OUT

An IN OUT parameter passes an initial value to a subprogram and returns an updated value to the caller. It can be assigned a value and the value can be read.

The actual parameter corresponding to an IN OUT formal parameter must be a variable, not a constant or an expression. Formal parameter must be assigned a value. Actual parameter is passed by value.

IN & OUT MODE EXAMPLE 1

This program finds the minimum of two values. Here, the procedure takes two numbers using the IN mode and returns their minimum using the OUT parameters.

DECLARE

a number;

b number;

c number;

PROCEDURE findMin(x IN number, y IN number, z OUT number) IS

BEGIN

IF x < y THEN

z:= x;

ELSE

z:= y;

END IF;

END;

BEGIN

Page 140: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

a:= 23;

b:= 45;

findMin(a, b, c);

dbms_output.put_line(' Minimum of (23, 45) : ' || c);

END;

/

When the above code is executed at the SQL prompt, it produces the following result −

Minimum of (23, 45) : 23 PL/SQL procedure successfully completed.

IN & OUT MODE EXAMPLE 2

This procedure computes the square of value of a passed value. This example shows how we can use the same parameter to accept a value and then return another result.

DECLARE

a number;

PROCEDURE squareNum(x IN OUT number) IS

BEGIN

x := x * x;

END;

BEGIN

a:= 23;

squareNum(a);

dbms_output.put_line(' Square of (23): ' || a);

END;

/

When the above code is executed at the SQL prompt, it produces the following result −

Square of (23): 529 PL/SQL procedure successfully completed.

Page 141: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

METHODS FOR PASSING PARAMETERS

Actual parameters can be passed in three ways −

• Positional notation

• Named notation

• Mixed notation

POSITIONAL NOTATION

In positional notation, you can call the procedure as −

findMin(a, b, c, d);

In positional notation, the first actual parameter is substituted for the first formal parameter; the second actual parameter is substituted for the second formal parameter, and so on. So, a is substituted for x, b is substituted for y, c is substituted for z and d is substituted for m.

NAMED NOTATION

In named notation, the actual parameter is associated with the formal parameter using the arrow symbol ( => ). The procedure call will be like the following −

findMin(x => a, y => b, z => c, m => d);

MIXED NOTATION

In mixed notation, you can mix both notations in procedure call; however, the positional notation should precede the named notation.

The following call is legal −

findMin(a, b, c, m => d);

However, this is not legal:

findMin(x => a, b, c, d);

8. Functions

Page 142: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

A function is same as a procedure except that it returns a value. Therefore, all the discussions of the previous chapter are true for functions too.

CREATING A FUNCTION

A standalone function is created using the CREATE FUNCTION statement. The simplified syntax for the CREATE OR REPLACE PROCEDURE statement is as follows −

CREATE [OR REPLACE] FUNCTION function_name [(parameter_name [IN | OUT | IN OUT] type [, ...])] RETURN return_datatype {IS | AS} BEGIN < function_body > END [function_name];

Where,

• function-name specifies the name of the function.

• [OR REPLACE] option allows the modification of an existing function.

• The optional parameter list contains name, mode and types of the parameters. IN represents the value that will be passed from outside and OUT represents the parameter that will be used to return a value outside of the procedure.

• The function must contain a return statement.

• The RETURN clause specifies the data type you are going to return from the function.

• function-body contains the executable part.

• The AS keyword is used instead of the IS keyword for creating a standalone function.

EXAMPLE

The following example illustrates how to create and call a standalone function. This function returns the total number of CUSTOMERS in the customers table.

We will use the CUSTOMERS table, which we had created in the PL/SQL Variables chapter −

Select * from customers; +----+----------+-----+-----------+----------+

Page 143: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

| ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | +----+----------+-----+-----------+----------+ CREATE OR REPLACE FUNCTION totalCustomers

RETURN number IS

total number(2) := 0;

BEGIN

SELECT count(*) into total

FROM customers;

RETURN total;

END;

/

When the above code is executed using the SQL prompt, it will produce the following result −

Function created.

CALLING A FUNCTION

While creating a function, you give a definition of what the function has to do. To use a function, you will have to call that function to perform the defined task. When a program calls a function, the program control is transferred to the called function.

A called function performs the defined task and when its return statement is executed or when the last end statement is reached, it returns the program control back to the main program.

To call a function, you simply need to pass the required parameters along with the function name and if the function returns a value, then you can store the returned value. Following program calls the function totalCustomers from an anonymous block −

DECLARE

c number(2);

Page 144: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

BEGIN

c := totalCustomers();

dbms_output.put_line('Total no. of Customers: ' || c);

END;

/

When the above code is executed at the SQL prompt, it produces the following result −

Total no. of Customers: 6 PL/SQL procedure successfully completed.

EXAMPLE

The following example demonstrates Declaring, Defining, and Invoking a Simple PL/SQL Function that computes and returns the maximum of two values.

DECLARE

a number;

b number;

c number;

FUNCTION findMax(x IN number, y IN number)

RETURN number

IS

z number;

BEGIN

IF x > y THEN

z:= x;

ELSE

Z:= y;

END IF;

RETURN z;

END;

BEGIN

Page 145: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

a:= 23;

b:= 45;

c := findMax(a, b);

dbms_output.put_line(' Maximum of (23,45): ' || c);

END;

/

When the above code is executed at the SQL prompt, it produces the following result −

Maximum of (23,45): 45 PL/SQL procedure successfully completed.

PL/SQL RECURSIVE FUNCTIONS

We have seen that a program or subprogram may call another subprogram. When a subprogram calls itself, it is referred to as a recursive call and the process is known as recursion.

To illustrate the concept, let us calculate the factorial of a number. Factorial of a number n is defined as −

n! = n*(n-1)! = n*(n-1)*(n-2)! ... = n*(n-1)*(n-2)*(n-3)... 1

The following program calculates the factorial of a given number by calling itself recursively −

DECLARE

num number;

factorial number;

FUNCTION fact(x number)

RETURN number

IS

f number;

BEGIN

IF x=0 THEN

Page 146: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

f := 1;

ELSE

f := x * fact(x-1);

END IF;

RETURN f;

END;

BEGIN

num:= 6;

factorial := fact(num);

dbms_output.put_line(' Factorial '|| num || ' is ' || factorial);

END;

/

When the above code is executed at the SQL prompt, it produces the following result −

Factorial 6 is 720 PL/SQL procedure successfully completed.

9. Triggers

Triggers are stored programs, which are automatically executed or fired when some events occur. Triggers are, in fact, written to be executed in response to any of the following events −

• A database manipulation (DML) statement (DELETE, INSERT, or UPDATE)

• A database definition (DDL) statement (CREATE, ALTER, or DROP).

• A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or SHUTDOWN).

Page 147: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

Triggers can be defined on the table, view, schema, or database with which the event is associated.

BENEFITS OF TRIGGERS

Triggers can be written for the following purposes −

• Generating some derived column values automatically

• Enforcing referential integrity

• Event logging and storing information on table access

• Auditing

• Synchronous replication of tables

• Imposing security authorizations

• Preventing invalid transactions

CREATING TRIGGERS

The syntax for creating a trigger is −

CREATE [OR REPLACE ] TRIGGER trigger_name

{BEFORE | AFTER | INSTEAD OF }

{INSERT [OR] | UPDATE [OR] | DELETE}

[OF col_name]

ON table_name

[REFERENCING OLD AS o NEW AS n]

[FOR EACH ROW]

WHEN (condition)

DECLARE

Declaration-statements

BEGIN

Executable-statements

EXCEPTION

Exception-handling-statements

END;

Where,

Page 148: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

• CREATE [OR REPLACE] TRIGGER trigger_name − Creates or replaces an existing trigger with the trigger_name.

• {BEFORE | AFTER | INSTEAD OF} − This specifies when the trigger will be executed. The INSTEAD OF clause is used for creating trigger on a view.

• {INSERT [OR] | UPDATE [OR] | DELETE} − This specifies the DML operation.

• [OF col_name] − This specifies the column name that will be updated.

• [ON table_name] − This specifies the name of the table associated with the trigger.

• [REFERENCING OLD AS o NEW AS n] − This allows you to refer new and old values for various DML statements, such as INSERT, UPDATE, and DELETE.

• [FOR EACH ROW] − This specifies a row-level trigger, i.e., the trigger will be executed for each row being affected. Otherwise the trigger will execute just once when the SQL statement is executed, which is called a table level trigger.

• WHEN (condition) − This provides a condition for rows for which the trigger would fire. This clause is valid only for row-level triggers.

EXAMPLE

To start with, we will be using the CUSTOMERS table we had created and used in the previous chapters −

Select * from customers; +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | +----+----------+-----+-----------+----------+

The following program creates a row-level trigger for the customers table that would fire for INSERT or UPDATE or DELETE operations performed on the CUSTOMERS table. This trigger will display the salary difference between the old values and new values −

Page 149: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

CREATE OR REPLACE TRIGGER display_salary_changes

BEFORE DELETE OR INSERT OR UPDATE ON customers

FOR EACH ROW

WHEN (NEW.ID > 0)

DECLARE

sal_diff number;

BEGIN

sal_diff := :NEW.salary - :OLD.salary;

dbms_output.put_line('Old salary: ' || :OLD.salary);

dbms_output.put_line('New salary: ' || :NEW.salary);

dbms_output.put_line('Salary difference: ' || sal_diff);

END;

/

When the above code is executed at the SQL prompt, it produces the following result −

Trigger created.

The following points need to be considered here −

• OLD and NEW references are not available for table-level triggers, rather you can use them for record-level triggers.

• If you want to query the table in the same trigger, then you should use the AFTER keyword, because triggers can query the table or change it again only after the initial changes are applied and the table is back in a consistent state.

• The above trigger has been written in such a way that it will fire before any DELETE or INSERT or UPDATE operation on the table, but you can write your trigger on a single or multiple operations, for example BEFORE DELETE, which will fire whenever a record will be deleted using the DELETE operation on the table.

TRIGGERING A TRIGGER

Let us perform some DML operations on the CUSTOMERS table. Here is one INSERT statement, which will create a new record in the table −

Page 150: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)

VALUES (7, 'Kriti', 22, 'HP', 7500.00 );

When a record is created in the CUSTOMERS table, the above create trigger, display_salary_changes will be fired and it will display the following result −

Old salary: New salary: 7500 Salary difference:

Because this is a new record, old salary is not available and the above result comes as null. Let us now perform one more DML operation on the CUSTOMERS table. The UPDATE statement will update an existing record in the table −

UPDATE customers

SET salary = salary + 500

WHERE id = 2;

When a record is updated in the CUSTOMERS table, the above create trigger, display_salary_changes will be fired and it will display the following result −

Old salary: 1500 New salary: 2000 Salary difference: 500

10. Packages

Packages are schema objects that groups logically related PL/SQL types, variables, and subprograms.

A package will have two mandatory parts −

• Package specification

• Package body or definition

PACKAGE SPECIFICATION

The specification is the interface to the package. It just DECLARES the types, variables, constants, exceptions, cursors, and subprograms that can be referenced from outside the package. In other

Page 151: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

words, it contains all information about the content of the package, but excludes the code for the subprograms.

All objects placed in the specification are called public objects. Any subprogram not in the package specification but coded in the package body is called a private object.

The following code snippet shows a package specification having a single procedure. You can have many global variables defined and multiple procedures or functions inside a package.

CREATE PACKAGE cust_sal AS

PROCEDURE find_sal(c_id customers.id%type);

END cust_sal;

/

When the above code is executed at the SQL prompt, it produces the following result −

Package created.

PACKAGE BODY

The package body has the codes for various methods declared in the package specification and other private declarations, which are hidden from the code outside the package.

The CREATE PACKAGE BODY Statement is used for creating the package body. The following code snippet shows the package body declaration for the cust_sal package created above. I assumed that we already have CUSTOMERS table created in our database as mentioned in the PL/SQL - Variableschapter.

CREATE OR REPLACE PACKAGE BODY cust_sal AS

PROCEDURE find_sal(c_id customers.id%TYPE) IS

c_sal customers.salary%TYPE;

BEGIN

SELECT salary INTO c_sal

FROM customers

WHERE id = c_id;

dbms_output.put_line('Salary: '|| c_sal);

Page 152: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

END find_sal;

END cust_sal;

/

When the above code is executed at the SQL prompt, it produces the following result −

Package body created.

USING THE PACKAGE ELEMENTS

The package elements (variables, procedures or functions) are accessed with the following syntax −

package_name.element_name;

Consider, we already have created the above package in our database schema, the following program uses the find_sal method of the cust_sal package −

DECLARE

code customers.id%type := &cc_id;

BEGIN

cust_sal.find_sal(code);

END;

/

When the above code is executed at the SQL prompt, it prompts to enter the customer ID and when you enter an ID, it displays the corresponding salary as follows −

Enter value for cc_id: 1 Salary: 3000 PL/SQL procedure successfully completed.

EXAMPLE

The following program provides a more complete package. We will use the CUSTOMERS table stored in our database with the following records −

Select * from customers; +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+

Page 153: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

| 1 | Ramesh | 32 | Ahmedabad | 3000.00 | | 2 | Khilan | 25 | Delhi | 3000.00 | | 3 | kaushik | 23 | Kota | 3000.00 | | 4 | Chaitali | 25 | Mumbai | 7500.00 | | 5 | Hardik | 27 | Bhopal | 9500.00 | | 6 | Komal | 22 | MP | 5500.00 | +----+----------+-----+-----------+----------+

THE PACKAGE SPECIFICATION

CREATE OR REPLACE PACKAGE c_package AS

-- Adds a customer

PROCEDURE addCustomer(c_id customers.id%type,

c_name customerS.No.ame%type,

c_age customers.age%type,

c_addr customers.address%type,

c_sal customers.salary%type);

-- Removes a customer

PROCEDURE delCustomer(c_id customers.id%TYPE);

--Lists all customers

PROCEDURE listCustomer;

END c_package;

/

When the above code is executed at the SQL prompt, it creates the above package and displays the following result −

Package created.

CREATING THE PACKAGE BODY

CREATE OR REPLACE PACKAGE BODY c_package AS

PROCEDURE addCustomer(c_id customers.id%type,

c_name customerS.No.ame%type,

c_age customers.age%type,

Page 154: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

c_addr customers.address%type,

c_sal customers.salary%type)

IS

BEGIN

INSERT INTO customers (id,name,age,address,salary)

VALUES(c_id, c_name, c_age, c_addr, c_sal);

END addCustomer;

PROCEDURE delCustomer(c_id customers.id%type) IS

BEGIN

DELETE FROM customers

WHERE id = c_id;

END delCustomer;

PROCEDURE listCustomer IS

CURSOR c_customers is

SELECT name FROM customers;

TYPE c_list is TABLE OF customerS.No.ame%type;

name_list c_list := c_list();

counter integer :=0;

BEGIN

FOR n IN c_customers LOOP

counter := counter +1;

name_list.extend;

name_list(counter) := n.name;

dbms_output.put_line('Customer(' ||counter|| ')'||name_list(counter));

END LOOP;

END listCustomer;

END c_package;

Page 155: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

/

The above example makes use of the nested table. We will discuss the concept of nested table in the next chapter.

When the above code is executed at the SQL prompt, it produces the following result −

Package body created.

USING THE PACKAGE

The following program uses the methods declared and defined in the package c_package.

DECLARE

code customers.id%type:= 8;

BEGIN

c_package.addcustomer(7, 'Rajnish', 25, 'Chennai', 3500);

c_package.addcustomer(8, 'Subham', 32, 'Delhi', 7500);

c_package.listcustomer;

c_package.delcustomer(code);

c_package.listcustomer;

END;

/

When the above code is executed at the SQL prompt, it produces the following result −

Customer(1): Ramesh Customer(2): Khilan Customer(3): kaushik Customer(4): Chaitali Customer(5): Hardik Customer(6): Komal Customer(7): Rajnish Customer(8): Subham Customer(1): Ramesh Customer(2): Khilan Customer(3): kaushik Customer(4): Chaitali Customer(5): Hardik Customer(6): Komal

Page 156: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

Customer(7): Rajnish PL/SQL procedure successfully completed

UNIT IV

GRAPHICAL USER INTERFACE & LANGUAGE REFERENCE

1. Introduction to the Visual Basic Language and Environment Preview In this first class, we will do a quick overview of how to build an application inVisual Basic. You’ll learn a new vocabulary, a new approach to programming,and ways to move around in the Visual Basic environment. You will leave havingwritten your first Visual Basic program. Course Objectives Understand the benefits of using Microsoft Visual Basic 6.0 for Windowsas an application tool understand the Visual Basic event-driven programming concepts,terminology, and available tools learn the fundamentals of designing, implementing, and distributing aVisual Basic application Learn to use the Visual Basic toolbox Learn to modify object properties Learn object methods Use the menu design window Understand proper debugging and error-handling procedures Gain a basic understanding of database access and management usingdata bound controls Obtain an introduction to ActiveX controls and the Windows ApplicationProgramming Interface (API) What is Visual Basic?

Page 157: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

Visual Basic is a tool that allows you to develop Windows (Graphic UserInterface - GUI) applications. The applications have a familiar appearance to theuser. Visual Basic is event-driven, meaning code remains idle until called upon torespond to some event (button pressing, menu selection,). Visual Basic isgoverned by an event processor. Nothing happens until an event is detected. Once an event is detected, the code corresponding to that event (eventprocedure) is executed. Program control is then returned to the event processor.

Some Features of Visual Basic Full set of objects - you 'draw' the application Lots of icons and pictures for your use Response to mouse and keyboard actions Clipboard and printer access Full array of mathematical, string handling and graphics functions Can handle fixed and dynamic variable and control arrays Sequential and random access files support Useful debugger and error-handling facilities Powerful database access tools ActiveX support Package & Deployment Wizard makes distributing your applications simple · The original Visual Basic for DOS and Visual Basic For Windows wereintroduced in 1991. · Visual Basic 3.0 (a vast improvement over previous versions) was released in1993. · Visual Basic 4.0 released in late 1995 (added 32 bit application support). · Visual Basic 5.0 released in late 1996. New environment, supported creation ofActiveX controls, deleted 16 bit application support. · And, now Visual Basic 6.0 - some identified new features of Visual Basic 6.0: Faster compiler New ActiveX data control object Allows database integration with wide variety of applications New data report designer New Package & Deployment Wizard Additional internet capabilities Structure of a Visual Basic Application

Page 158: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

Application (Project) is made up of: Forms - Windows that you create for user interface Controls - Graphical features drawn on forms to allow user interaction(text boxes, labels, scroll bars, command buttons, etc.) (Forms andControls are objects.) Properties - Every characteristic of a form or control is specified by aproperty. Example properties include names, captions, size, color,position, and contents. Visual Basic applies default properties. You canchange properties at design time or run time. Methods - Built-in procedure that can be invoked to impart some action toa particular object. Event Procedures - Code related to some object. This is the code that isexecuted when a certain event occurs. General Procedures - Code not related to objects. This code must beinvoked by the application. Modules - Collection of general procedures, variable declarations, andconstant definitions used by application. Steps in Developing Application There are three primary steps involved in building a Visual Basic application: 1. Draw the user interface 2. Assign properties to controls 3. Attach code to controls Drawing the User Interface and Setting Properties · Visual Basic operates in three modes. Design mode - used to build application Run mode - used to run the application Break mode - application halted and debugger is available We focus here on the design mode.

Page 159: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

· Six windows appear when you start Visual Basic. The Main Window consists of the title bar, menu bar, and toolbar. Thetitle bar indicates the project name, the current Visual Basic operatingmode, and the current form. The menu bar has drop-down menus fromwhich you control the operation of the Visual Basic environment. Thetoolbar has buttons that provide shortcuts to some of the menu options.The main window also shows the location of the current form relative tothe upper left corner of the screen (measured in twips) and the widthand length of the current form.

The Form Window is central to developing Visual Basic applications. It is where you draw your application.

The Toolbox is the selection menu for controls used in yourapplication.

Page 160: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

The Properties Window is used to establish initial property values forobjects. The drop-down box at the top of the window lists all objects inthe current form. Two views are available: Alphabetic andCategorized. Under this box are the available properties for thecurrently selected object.

Page 161: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

The Form Layout Window shows where (upon program execution) Your form will be displayed relative to your monitor’s screen:

The Project Window displays a list of all forms and modules making upyour application. You can also obtain a view of the Form or Codewindows (window containing the actual basic coding) from the Projectwindow.

Page 162: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

· As mentioned, the user interface is ‘drawn’ in the form window. There are twoways to place controls on a form: 1. Double-click the tool in the toolbox and it is created with a default size onthe form. You can then move it or resize it. 2. Click the tool in the toolbox, then move the mouse pointer to the formwindow. The cursor changes to a crosshair. Place the crosshair at theupper left corner of where you want the control to be, press the left mousebutton and hold it down while dragging the cursor toward the lower rightcorner. When you release the mouse button, the control is drawn. · Tomove a control you have drawn, click the object in the form window and drag itto the new location. Release the mouse button. · Toresize a control, click the object so that it is select and sizing handles appear. Use these handles to resize the object.

Stopwatch Application - Drawing Controls 1. Start a new project. The idea of this project is to start a timer, then stop the timerand compute the elapsed time (in seconds). 2. Place three command buttons and six labels on the form. Move and size thecontrols and form so it looks something like this:

Page 163: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

Setting Properties of Objects at Design Time · Each form and control has properties assigned to it by default when you start upa new project. There are two ways to display the properties of an object. The firstway is to click on the object (form or control) in the formwindow. Then, click onthe Properties Window or the Properties Window button in the tool bar. Thesecond way is to first click on the Properties Window. Then, select the objectfrom the Object box in the Properties Window. Shown is the Properties Windowfor the stopwatch application:

Page 164: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

The drop-down box at the top of the PropertiesWindow is the Object box. It displays the nameof each object in the application as well as itstype. This display shows the Form object. TheProperties list is directly below this box. In thislist, you can scroll through the list of propertiesfor the selected object. You may select aproperty by clicking on it. Properties can bechanged by typing a new value or choosing froma list of predefined settings (available as a dropdown list). Properties can be viewed in twoways: Alphabetic and Categorized. A very important property for each object is itsname. The name is used by Visual Basic torefer to a particular object in code. · A convention has been established for naming Visual Basic objects. Thisconvention is to use a three letter prefix (depending on the object) followed by aname you assign. A few of the prefixes are (we’ll see more as we progress in theclass):

· Object names can be up to 40 characters long, must start with a letter, mustcontain only letters, numbers, and the underscore (_) character. Names are usedin setting properties at run time and also in establishing procedure names forobject events. Setting Properties at Run Time · You can also set or modify properties while your application is running. To do this,you must write some code. The code format is: ObjectName.Property = New Value Such a format is referred to as dot notation. For example, to change theBack Colorproperty of a form name frmStart, we'd type: frmStart.BackColor = BLUE · The names you assign to objects are used by Visual Basic to set up a frameworkof event-driven procedures for you to add code to. The format for each of thesesubroutines (all object procedures in Visual Basic are subroutines) is: Sub ObjectName_Event (Optional Arguments) .. End Sub

Page 165: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

· Visual Basic provides the Sub line with its arguments (if any) and the End Substatement. You provide any needed code.

Page 166: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

In the Caption properties of the three command buttons, notice theampersand (&). The ampersand precedes a button's access key. That is, inaddition to clicking on a button to invoke its event, you can also press itsaccess key (no need for a mouse). The access key is pressed in conjunctionwith the Alt key. Hence, to invoke 'Begin Timing', you can either click thebutton or press Alt+B. Note in the button captions on the form, the accesskeys appear with an underscore (_). 2. Your form should now look something like this:

Page 167: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

Variables · We’re now ready to attach code to our application. As objects are added to theform, Visual Basic automatically builds a framework of all event procedures. Wesimply add code to the event procedures we want our application to respond to.But before we do this, we need to discuss variables. · Variables are used by Visual Basic to hold information needed by yourapplication. Rules used in naming variables: No more than 40 characters They may include letters, numbers, and underscore (_) The first character must be a letter You cannot use a reserved word (word needed by Visual Basic)

Visual Basic Data Types Data Type Suffix Boolean None Integer % Long (Integer) & Single (Floating) ! Double (Floating) # Currency @ Date None Object None String $ Variant Variable Declaration · There are three ways for a variable to be typed (declared): 1. Default 2. Implicit 3. Explicit · If variables are not implicitly or explicitly typed, they are assigned the variant typeby default. The variant data type is a special type used by Visual Basic that cancontain numeric, string, or date data. · To implicitly type a variable, use the corresponding suffix shown above in thedata type table. For example, TextValue$ = "This is a string" Creates a string variable, while Amount% = 300 Creates an integer variable. · There are many advantages to explicitly typing variables. Primarily, we insure allcomputations are properly done, mistyped variable names are easily spotted, andVisual Basic will take care of insuring consistency in upper and lower

Page 168: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

case letter used in variable names. Because of these advantages, and because it is goodprogramming practice, we will explicitly type all variables. · Toexplicitly type a variable, you must first determine its scope. There are fourlevels of scope: Procedure level Procedure level, static Form and module level Global level · Within a procedure, variables are declared using the Dim statement: Dim MyInt as Integer Dim MyDouble as Double Dim MyString, Your String as String Procedure level variables declared in this manner do not retain their value once aprocedure terminates. · To make a procedure level variable retain its value upon exiting the procedure;replace the Dim keyword with Static: Static MyInt as Integer Static MyDouble as Double · Form (module) level variables retain their value and are available to allprocedures within that form (module). Form (module) level variables are declaredin the declarations part of the general object in the form's (module's) codewindow. The Dim keyword is used: Dim MyInt as Integer Dim MyDate as Date · Global level variables retain their value and are available to all procedures withinan application. Module level variables are declared in the declarations part ofthe general object of a module's code window. (It is advisable to keep all globalvariables in one module.) Use the Global keyword: Global MyInt as Integer Global MyDate as Date · What happens if you declare a variable with the same name in two or moreplaces? More local variables shadow (are accessed in preference to) less localvariables. For example, if a variable MyInt is defined as Global in a module anddeclared local in a routine MyRoutine, while in MyRoutine, the local value of MyIntis accessed. Outside MyRoutine, the global value of MyInt is accessed.

Page 169: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

UNIT V PROGRAMMING IN VISUAL BASIC The Visual Basic Language Review and Preview · Last week, we found there were three primary steps involved in developing anapplication using Visual Basic: 1. Draw the user interface 2. Assign properties to controls 3. Attach code to events This week, we are primarily concerned with Step 3, attaching code. We willbecome more familiar with moving around in the Code window and learn some ofthe elements of the Basic language. A Brief History of Basic · Language developed in early 1960's at Dartmouth College: B (eginner's) A (All-Purpose) S (Symbolic) I (Instruction) C (Code) · Answer to complicated programming languages (FORTRAN, Algol, Cobol ...).First timeshare language. · In the mid-1970's, two college students write first Basic for a microcomputer(Altair) - cost $350 on cassette tape. You may have heard of them: Bill Gatesand Paul Allen! · Every Basic since then essentially based on that early version. Examples include:GW-Basic, QBasic, and QuickBasic. · Visual Basic was introduced in 1991. Visual Basic Statements and Expressions · The simplest statement is the assignment statement. It consists of a variablename, followed by the assignment operator (=), followed by some sort ofexpression. · Statements normally take up a single line with no terminator. Statements can bestacked by using a colon (:) to separate them. Example: Start Time = Now:End Time = Start Time + 10

Page 170: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

(Be careful stacking statements, especially with If/End If structures. You may notget the response you desire.) · If a statement is very long, it may be continued to the next line using thecontinuation character, an underscore (_). Example: Months = Log (Final * IntRate / Deposit + 1) _ / Log (1 + IntRate) · Comment statements begin with the keyword Rem or a single quote ('). Forexample: Rem this is a remark ‘This is also a remark x = 2 * y ' another way to write a remark or comment You, as a programmer, should decide how much to comment your code. Consider such factors as reuse, your audience, and the legacy of your code. Visual Basic Operators · The simplest operators carry out arithmetic operations. These operators in theirorder of precedence are: Operator Operation ^ Exponentiation * / Multiplication and division \ Integer division (truncates) Mod Modulus + - Addition and subtraction · Parenthesesaround expressions can change precedence. · Toconcatentate two strings, use the &symbol or the + symbol: lblTime.Caption = "The current time is" &Format (Now, “hh:mm”) txtSample.Text = "Hook this “ + “to this” · There are six comparison operators in Visual Basic: Operator Comparison > Greater than < Less than >= Greater than or equal to <= Less than or equal to = Equal to · The result of a comparison operation is a Boolean value (True or False). · We will use three logical operators Operator Operation Not Logical not And Logical and

Page 171: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

Or Logical or · The Not operator simply negates an operand. · The andoperator returns a True if both operands are True. Else, it returns aFalse. · The oroperator returns a True if either of its operands is True, else it returns aFalse. · Logical operators follow arithmetic operators in precedence. Visual Basic Functions · Visual Basic offers a rich assortment of built-in functions. The on-line help utilitywill give you information on any or all of these functions and their use. Someexamples are: Function Value Returned Abs Absolute value of a number Asc ASCII or ANSI code of a character Chr Character corresponding to a given ASCII or ANSI code Cos Cosine of an angle Date Current date as a text string Format Date or number converted to a text string Left Selected left side of a text string Len Number of characters in a text string Mid Selected portion of a text string Now Current time and date Right Selected right end of a text string Rnd Random number Sin Sine of an angle Sqr Square root of a number Str Number converted to a text string Time Current time as a text string Timer Number of seconds elapsed since midnight Val Numeric value of a given text string Visual Basic Symbolic Constants · Many times in Visual Basic, functions and objects require data arguments thataffect their operation and return values you want to read and interpret. Thesearguments and values are constant numerical data and difficult to interpret basedon just the numerical value. To make these constants more understandable,Visual Basic assigns names to the most widely used values - these are calledsymbolic constants. Appendix I lists many of these constants. · As an example, to set the background color of a form named frmExample toblue, we could type: frmExample.BackColor = 0xFF0000 or, we could use the symbolic constant for the blue color (vbBlue): frmExample.BackColor = vbBlue · It is strongly suggested that the symbolic constants be used instead of the numericvalues, when possible. You should agree that vbBlue means more than the value0xFF0000 when selecting the background color in the above example. You donot need to do anything to define the symbolic constants - they are built into VisualBasic.

Page 172: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

Visual Basic Branching - If Statements · Branchingstatements are used to cause certain actions within a program if acertain condition is met. · The simplest is the If/Then statement: If Balance - Check < 0 Then Print "You are overdrawn" Here, if and only if Balance - Check is less than zero, the statement “You areoverdrawn” is printed. · You can also have If/Then/End If blocks to allow multiple statements: If Balance - Check < 0 Then Print "You are overdrawn" Print "Authorities have been notified" End If In this case, if Balance - Check is less than zero, two lines of information areprinted. · Or, If/Then/Else/End If blocks: If Balance - Check < 0 Then Print "You are overdrawn" Print "Authorities have been notified" Else Balance = Balance - Check End If Here, the same two lines are printed if you are overdrawn (Balance - Check < 0),but, if you are not overdrawn (Else), your new Balance is computed. · Or, we can add the ElseIf statement: If Balance - Check < 0 Then Print "You are overdrawn" Print "Authorities have been notified" else If Balance - Check = 0 Then Print "Whew! You barely made it" Balance = 0 Else Balance = Balance - Check End If ] Now, one more condition is added. If your Balance equals the Check amount(else IfBalance - Check = 0), a different message appears. · In using branching statements, make sure you consider all viable possibilities inthe If/Else/End If structure. Also, be aware that each If and Else If in a block istested sequentially. The first time an If test is met, the code associated with thatcondition is executed and the If block is exited. If a later condition is also True, itwill never be considered. Key Trapping · Note in the previous example, there is nothing to prevent the user from typing inmeaningless characters (for example, letters) into the text boxes expectingnumerical data. Whenever getting input from a user, we want to limit the availablekeys they can press. The process of intercepting unacceptable keystrokes iskey trapping.

Page 173: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

· Key trapping is done in the KeyPress procedure of an object. Such a procedurehas the form (for a text box named txtText): Sub txtText_KeyPress (KeyAscii as Integer) End Sub What happens in this procedure is that every time a key is pressed in thecorresponding text box, the ASCII code for the pressed key is passed to thisprocedure in the argument list (i.e. KeyAscii). If KeyAscii is an acceptable value, we would do nothing. However, if KeyAscii is not acceptable, we would setKeyAscii equal to zero and exit the procedure. Doing this has the same result ofnot pressing a key at all. ASCII values for all keys are available via the on-line help in Visual Basic. And some keys are also defined by symbolic constants.Where possible, we will use symbolic constants; else, we will use the ASCIIvalues. · As an example, say we have a text box (named txtExample) and we only want tobe able to enter upper case letters (ASCII codes 65 through 90, or,correspondingly, symbolic constants vbKeyA through vbKeyZ). The key pressprocedure would look like (the Beep causes an audible tone if an incorrect key ispressed): Sub txtExample_KeyPress(KeyAscii as Integer) If KeyAscii >= vbKeyA And KeyAscii <= vbKeyZ Then Exit Sub Else KeyAscii = 0 Beep End If End Sub · In key trapping, it's advisable to always allow the backspace key (ASCII code 8;symbolic constant vbKeyBack) to pass through the key press event. Else, youwill not be able to edit the text box properly. Select Case - Another Way to Branch · In addition to If/Then/Else type statements, the Select Case format can be usedwhen there are multiple selection possibilities. · Say we've written this code using the If statement: If Age = 5 Then Category = "Five Year Old" ElseIf Age >= 13 and Age <= 19 Then Category = "Teenager" ElseIf (Age >= 20 and Age <= 35) Or Age = 50 Or (Age >= 60 and Age <= 65) Then Category = "Special Adult" ElseIf Age > 65 Then Category = "Senior Citizen" Else Category = "Everyone Else" End If The corresponding code with Select Case would be: Select Case Age Case 5 Category = "Five Year Old" Case 13 To 19

Page 174: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

Category = "Teenager" Case 20 to 35, 50, 60 To 65 Category = "Special Adult" Case Is > 65 Category = "Senior Citizen" Case Else Category = "Everyone Else" End Select Notice there are several formats for the Case statement. Consult on-line help fordiscussions of these formats. The GoTo Statement Another branching statement, and perhaps the most hated statement inprogramming, is the GoTo statement. However, we will need this to do Run-Timeerror trapping. The format is GoTo Label, where Label is a labeled line.Labeled lines are formed by typing the Label followed by a colon. When the code reaches the GoTo statement, program control transfers to the linelabeled Line10. Visual Basic Looping Looping is done with the Do/Loop format. Loops are used for operations are tobe repeated some number of times. The loop repeats until some specifiedcondition at the beginning or end of the loop is met. Do While/Loop Example: Counter = 1 Do While Counter <= 1000 Debug. Print Counter Counter = Counter + 1 Loop This loop repeats as long as (While) the variable Counter is less than or equal to1000. Note a Do While/Loop structure will not execute even once if the Whilecondition is violated (False) the first time through. Also note the Debug. Printstatement. What this does is print the value Counter in the Visual Basic Debugwindow. We'll learn more about this window later in the course. · Make sure you can always get out of a loop! Infinite loops are never nice. If youget into one, try Ctrl+Break. That sometimes works - other times the only way outis rebooting your machine! · The statement Exit Do will get you out of a loop and transfer program control tothe statement following the Loop statement. Visual Basic Counting · Counting is accomplished using the For/Next loop. In this example, the variable I initializes at 1 and, with each iteration of theFor/Next loop, is incremented by 2 (Step). This looping continues until I becomesgreater than or equal to its final value (50). If Step is not included, the default valueis 1. Negative values of Step are allowed. · You may exit a For/Next loop using an Exit For statement. This will transferprogram control to the statement following the Next statement. If the Interest value is missing, we have to solve an Mth-order polynomial usingsomething called Newton-Raphson iteration - a good example of using a Do loop.

Page 175: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

Finding the Interest value is straightforward. What we do is guess at what theinterest is, compute a better guess (using Newton-Raphson iteration), and repeatthe process (loop) until the old guess and the new guess are close to each other. You can see each step in the code. 5. Test and save your application. Go home and relax. Flash Card Addition Problems Write an application that generates random addition problems. Provide some kind offeedback and scoring system as the problems are answered. My Solution:

Properties: Form frmAdd: Border Style = 1 - Fixed Single Caption = Flash Card Addition Command Button cmdNext: Caption = &Next Problem Enabled = False CommandButton cmdExit: Caption = E&xit TextBox txtAnswer:

Page 176: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

FontName = Arial FontSize = 48 MaxLength = 2 Label lblMessage: Alignment = 2 - Center Back Color = &H00FFFF00& (Cyan) Border Style = 1 - Fixed Single Font Name = MS sans Serif Font Bold = True Font Size = 24 Font Italic = True Label lblScore: Alignment = 2 - Center Back Color = &H0000FFFF& (Yellow) border Style = 1 - Fixed Single Caption = 0 Font Name = Times New Roman Font Bold = True Font Size = 36 Label Label1: Alignment = 2 - Center Caption = Score: Font Name = MS Sans Serif Font Size = 18 Label Label4: Alignment = 2 - Center Caption = = Font Name = Arial Font Size = 48 Label lblNum2: Alignment = 2 - Center FontName = Arial FontSize = 48 Label Label2: Alignment = 2 - Center Caption = + Font Name = Arial Font Size = 48 Label lblNum1: Alignment = 2 - Center FontName = Arial FontSize = 48

Page 177: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

Exploring the Visual Basic Toolbox Review and Preview · In this class, we begin a journey where we look at each tool in the Visual Basictoolbox. We will revisit some tools we already know and learn a lot of new tools. First, though, we look at an important Visual Basic functions. The Message Box · One of the best functions in Visual Basic is the message box. The message boxdisplays a message, optional icon, and selected set of command buttons. Theuser responds by clicking a button. · The statement form of the message box returns no value (it simply displays thebox): MsgBox Message, Type, Title Where Message Text message to be displayed Type Type of message box (discussed in a bit) Title Text in title bar of message box You have no control over where the message box appears on the screen. · The function form of the message box returns an integer value (corresponding tothe button clicked by the user). Example of use (Response is returned value): Dim Response as Integer Response = MsgBox (Message, Type, Title) · The Type argument is formed by summing four values corresponding to thebuttons to display, any icon to show, which button is the default response, and themodality of the message box. · The first component of the Type value specifies the buttons to display: Value Meaning Symbolic Constant 0 OK button only vbOKOnly 1 OK/Cancel buttons vbOKCancel 2 Abort/Retry/Ignore buttons vbAbortRetryIgnore 3 Yes/No/Cancel buttons vbYesNoCancel 4 Yes/No buttons vbYesNo 5 Retry/Cancel buttons vbRetryCancel · The second component of Type specifies the icon to display in the messagebox: Value Meaning Symbolic Constant 0 No icon (None) 16 Critical icon vbCritical

Page 178: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

32 Question mark vbQuestion 48 Exclamation point vbExclamation 64 Information icon vbInformation · The third component of Type specifies which button is default (i.e. pressingEnter is the same as clicking the default button): Value Meaning Symbolic Constant 0 First button default vbDefaultButton1 256 Second button default vbDefaultButton2 512 Third button default vbDefaultButton3 · The fourth and final component of Type specifies the modality: Value Meaning Symbolic Constant 0 Application modal vbApplicationModal 4096 System modal vbSystemModal If the box is Application Modal, the user must respond to the box beforecontinuing work in the current application. If the box is System Modal, allapplications are suspended until the user responds to the message box. · Note for each option in Type, there are numeric values listed and symbolicconstants. Recall, it is strongly suggested that the symbolic constants be usedinstead of the numeric values. You should agree that vbOKOnly means morethan the number 0 when selecting the button type. · Message Box Example: MsgBox “This is an example of a message box”, vbOKCancel + vbInformation,“Message Box Example”

· You’ve seen message boxes if you've ever used a Windows application. Think ofall the examples you've seen. For example, message boxes are used to ask youif you wish to save a file before exiting and to warn you if a disk drive is not ready. Object Methods · In previous work, we have seen that each object has properties and eventsassociated with it. A third concept associated with objects is the method. Amethod is a procedure or function that imparts some action to an object. · As we move through the toolbox, when appropriate, we'll discuss object methods.Methods are always enacted at run-time in code. The format for invoking amethod is: ObjectName.Method {optional arguments} Note this is another use of the dot notation. The Form Object

Page 179: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

· TheForm is where the user interface is drawn. It is central to the development ofVisual Basic applications. · Form Properties: Appearance Selects 3-D or flat appearance. Back Color Sets the form background color. border Style sets the form border to be fixed or sizeable. Caption Sets the form window title. Enabled If True, allows the form to respond to mouse andkeyboard events; if False, disables form. Font Sets font type, style, size. ForeColor Sets color of text or graphics. Picture Places a bitmap picture in the form. Visible If False, hides the form. · Form Events: Activate Form_Activate event is triggered when form becomesthe active window. Click Form_Click event is triggered when user clicks onform. DblClick Form_DblClick event is triggered when user doubleclickson form. Load Form Load event occurs when form is loaded. Thisis a good place to initialize variables and set any

runtimeproperties. · Form Methods: Cls Clears all graphics and text from form. Does not clearany objects. Print Prints text string on the form. Examples frmExample.Cls ' clears the form frmExample.Print "This will print on the form" Command Buttons · We’ve seen the command button before. It is probably the most widely usedcontrol. It is used to begin, interrupt, or end a particular process. · Command Button Properties: Appearance Selects 3-D or flat appearance. Cancel Allows selection of button with Esc key (only onebutton on a form can have this property

True). Caption String to be displayed on button. Default Allows selection of button with Enter key (only onebutton on a form can have this property

True). Font Sets font type, style, size. · Command Button Events: Click Event triggered when button is selected either byclicking on it or by pressing the access key.

Label Boxes

Page 180: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

· Alabel box is a control you use to display text that a user can't edit directly.We've seen, though, in previous examples, that the text of a label box can bechanged at run-time in response to events. · Label Properties: Alignment Aligns caption within border. Appearance Selects 3-D or flat appearance. Auto Size If true, the label is resized to fit the text specified bythe caption property. If False, the label

will remain thesize defined at design time and the text may beclipped. Border Style Determines type of border. Caption String to be displayed in box. Font Sets font type, style, size. Text Boxes · Atext box is used to display information entered at design time, by a user at runtime,or assigned within code. The displayed text may be edited. · Text Box Properties: Appearance Selects 3-D or flat appearance. border Style Determines type of border. Font Sets font type, style, size. MaxLength Limits the length of displayed text (0 value indicatesunlimited length). Multiline Specifies whether text box displays single line ormultiple lines. Password Char Hides text with a single character. ScrollBars Specifies type of displayed scroll bar(s). SelLength Length of selected text (run-time only). SelStart Starting position of selected text (run-time only). SelText Selected text (run-time only). Tag Stores a string expression. Text Displayed text. Text Box Events: Change Triggered every time the Text property changes. LostFocus Triggered when the user leaves the text box. This is agood place to examine the contents of a text box

afterediting. KeyPress Triggered whenever a key is pressed. Used for keytrapping, as seen in last class. Text Box Methods: Set Focus Places the cursor in a specified text box. Example txtExample.SetFocus ' moves cursor to box named txtExample Arrays · Up to now, we've only worked with regular variables, each having its own uniquename. Visual Basic has powerful facilities for handling multi-dimensionalvariables, or arrays. For now, we'll only use single, fixed-dimension arrays.

Page 181: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

· Arrays are declared in a manner identical to that used for regular variables. Forexample, to declare an integer array named 'Items', with dimension 9, at theprocedure level, we use: Dim Items (9) as Integer If we want the array variables to retain their value upon leaving a procedure, weuse the keyword Static: Static Items (9) as Integer At the form or module level, in the general declarations area of the Codewindow, use: Dim Items (9) as Integer And, at the module level, for a global declaration, use: Global Items (9) as Integer · The index on an array variable begins at 0 and ends at the dimensioned value.For example, the Items array in the above examples has ten elements, rangingfrom Items (0) to Items(9). You use array variables just like any other variable – justremember to include its name and its index. For example, to set Item (5) equal to7, you simply write: Item (5) = 7 Control Arrays · With some controls, it is very useful to define control arrays - it depends on theapplication. For example, option buttons are almost always grouped in controlarrays. · Control arrays are a convenient way to handle groups of controls that perform asimilar function. All of the events available to the single control are still available tothe array of controls, the only difference being an argument indicating the index ofthe selected array element is passed to the event. Hence, instead of writingindividual procedures for each control (i.e. not using control arrays), you only haveto write one procedure for each array. · Another advantage to control arrays is that you can add or delete array elementsat run-time. You cannot do that with controls (objects) not in arrays. Refer to theLoad and Unload statements in on-line help for the proper way to add and deletecontrol array elements at run-time. · Two ways to create a control array: 1. Create an individual control and set desired properties. Copy the controlusing the editor, and then paste it on the form. Visual Basic will pop-up a dialogbox that will ask you if you wish to create a control array. Respond yes and thearray is created. 2. Create all the controls you wish to have in the array. Assign the desired controlarray name to the first control. Then, try to name the second control with thesame name. Visual Basic will prompt you, asking if you want to create acontrol array. Answer yes. Once the array is created, rename all remainingcontrols with that name. · Once a control array has been created and named, elements of the array arereferred to by their name and index. For example, to set the Caption property ofelement 6 of a label box array named lblExample, we would use: LblExample (6).Caption = “This is an example” We'll use control arrays in the next example. Frames · We’ve seen that both option buttons and check boxes work as a group. Framesprovide a way of grouping related controls on a form. And, in the case of optionbuttons, frames affect how such buttons operate.

Page 182: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

· To group controls in a frame, you first draw the frame. Then, the associatedcontrols must be drawn in the frame. This allows you to move the frame andcontrols together. And, once a control is drawn within a frame, it can be copiedand pasted to create a control array within that frame. To do this, first click on theobject you want to copy. Copy the object. Then, click on the frame. Paste theobject. You will be asked if you want to create a control array. Answer Yes. · · Drawing the controls outside the frame and dragging them in, copying them into aframe, or drawing the frame around existing controls will not result in a propergrouping. It is perfectly acceptable to draw frames within other frames. · As mentioned, frames affect how option buttons work. Option buttons within aframe work as a group, independently of option buttons in other frames. Optionbuttons on the form, and not in frames, work as another independent group. Thatis, the form is itself a frame by default. We'll see this in the next example. · It is important to note that an independent group of option buttons is defined byphysical location within frames, not according to naming convention. That is, acontrol array of option buttons does not work as an independent group justbecause it is a control array. It would only work as a group if it were the only groupof option buttons within a frame or on the form. So, remember physical location,and physical location only, dictates independent operation of option buttongroups. · Frame Properties: Caption Title information at top of frame. Font Sets font type, style, size. Creating a Stand-Alone Visual Basic Application Review and Preview · We’ve finished looking at most of the Visual Basic tools and been introduced tomost of the Basic language features. Thus far, to run any of the applicationsstudied, we needed Visual Basic. In this class, we learn the steps of developing astand-alone application that can be run on any Windows-based machine. We’llalso look at some new components that help make up applications. Designing an Application · Before beginning the actual process of building your application by drawing theVisual Basic interface, setting the object properties, and attaching the Basiccode, many things should be considered to make your application useful. · A first consideration should be to determine what processes and functions youwant your application to perform. What are the inputs and outputs? Develop a framework or flow chart of all your application's processes. · Decide what tools you need. Do the built-in Visual Basic toolsand functions meetyour needs? Do you need to develop some tools or functions of your own? · Design your user interface. What do you want your form to look like? Considerappearance and ease of use. Make the interface consistent with other Windowsapplications. Familiarity is good in program design. · Write your code. Make your code readable and traceable - future code modifierswill thank you. Consider developing reusable code - modules with utility outsideyour current development. This will save you time in future developments. · Make your code 'user-friendly.' Try to anticipate all possible ways a user canmess up in using your application. It's fairly easy to write an application that worksproperly when the user does everything correctly. It's difficult to write anapplication that can handle all the possible wrong things a user can do and still notbomb out.

Page 183: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

· Debug your code completely before distributing it. There's nothing worse thanhaving a user call you to point out flaws in your application. A good way to find allthe bugs is to let several people try the code - a mini beta-testing program. Using General Sub Procedures in Applications · So far in this class, the only procedures we have studied are the event-drivenprocedures associated with the various tools. Most applications have tasks notrelated to objects that require some code to perform these tasks. Such tasks areusually coded in a general Sub procedure (essentially the same as a subroutinein other languages). · Using general Sub procedures can help divide a complex application into moremanageable units of code. This helps meet the above stated goals of readabilityand reusability. · Defining a Sub Procedure: The form for a general Sub procedure named GenlSubProc is: Sub GenlSubProc(Arguments) 'Definition header End Sub The definition header names the Sub procedure and defines any argumentspassed to the procedure. Arguments are a comma-delimited list of variablespassed to and/or from the procedure. If there are arguments, they must bedeclared and typed in the definition header in this form: Var1 As Type1, Var2 As Type2... · Sub Procedure Example: Here is a Sub procedure (USMexConvert) that accepts as inputs an amount inUS dollars (US Dollars) and an exchange rate (UStoPeso). It then outputs anamount in Mexican pesos (MexPesos). Sub USMexConvert (USDollars As Single, UStoPeso As Single, MexPesos As Single) MexPesos = UsDollars * UsToPeso End Sub · Calling a Sub Procedure: There are two ways to call or invoke a Sub procedure. You can also use these tocall event-driven procedures. Locating General Sub Procedures: General Sub procedures can be located in one of two places in your application:attached to a form or attached to a module. Place the procedure in the form if ithas a purpose specifically related to the form. Place it in a module if it is ageneral purpose procedure that might be used by another form or module oranother application. Whether placing the procedure in a form or module, the methods of creating theprocedure are the same. Select or open the form or module's code window.Make sure the window's Object list says (General) and the Procedure list says(Declarations). You can now create the procedure by selecting Add Procedurefrom Visual Basic's Tools menu. A window appears allowing you to select TypeSub and enter a name for your procedure. Another way to create a Sub is to go tothe last line of the General Declarations section, type Sub followed by a spaceand the name of your procedure. Then, hit Enter. With either method forestablishing a Sub, Visual Basic will form a template for your procedure. Fill inthe Argument list and write your Basic code. In selecting the Insert Proceduremenu item, note another option for your procedure is Scope. You have the choiceof Public or Private. The scope word appears before the Sub word in thedefinition heading. If a module procedure is Public, it can be called from any otherprocedure in any other module. If a module procedure is Private, it can only becalled from the module it is defined in. Note, scope only applies to procedures

Page 184: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

inmodules. By default, all event procedures and general procedures in a form arePrivate - they can only be called from within the form. You must decide the scopeof your procedures. · Passing Arguments to Sub Procedures: A quick word on passing arguments to procedures. By default, they are passedby reference. This means if an argument is changed within the procedure, it willremain changed once the procedure is exited. C programmers have experienced the concept of passing by value, where aparameter changed in a procedure will retain the value it had prior to calling theroutine. Visual Basic also allows calling by value. To do this, place the wordBy Valin front of each such variable in the Argument list. Creating a Code Module · If you're going to put code in a module, you'll need to know how to create and savea module. A good way to think about modules is to consider them forms withoutany objects, just code. · To create a module, click on the New Module button on the toolbar, or select theModule option from the Insert menu. The module will appear. Note any modulesappear in the Project Window, along with your form(s). You use the ProjectWindow to move among forms and modules. · Once the module is active, establish all of your procedures as outlined above. Toname the module, click on the properties window while the module is active. NoteName is the only property associated with a module. Saving a module is just likesaving a form - use the Save File and Save File As options. Using General Function Procedures in Applications · Related to Sub procedures are Function procedures. A Function procedure, orsimply Function, performs a specific task within a Visual Basic program andreturns a value. We've seen some built-in functions such as the MsgBox and theFormat function. · Defining a Function: The form for a general Function named GenlFcn is: Function GenlFcn (Arguments) As Type 'Definition header GenlFcn = ... End Function The definition header names the Function and specifies its Type (the type of thereturned value) and defines any input Arguments passed to the function. Notethat somewhere in the function, a value for GenlFcn must be computed for returnto the calling procedure. Function Example: Here is a Function named CylVol that computes the volume of a cylinder ofknown height (Height) and radius (Radius). Function CylVol (Height as Single, Radius as Single) As Single Dim Area as Single Const PI = 3.1415926 Area = PI * Radius ^ 2 CylVol = Area * Height End Sub Calling a Function:

Page 185: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

To call or use a Function, you equate a variable (of proper type) to the Function,with its arguments. That is, if the Function GenlFunc is of Type Integer, then usethe code segment: Dim RValue as Integer R-value = GenlFunc (Arguments) Example To call the volume computation function, we could use: Dim Volume as Single .. Volume = CylVol (Height, Radius) · Locating Function Procedures: Like Sub procedures, Functions can be located in forms or modules. They arecreated using exactly the same process described for Sub procedures, the onlydifference being you use the keyword Function. And, like Sub procedures, Functions (in modules) can be public or private. Adding Menus to an Application As mentioned earlier, it is important that the interface of your application befamiliar to a seasoned, or not-so-seasoned, Windows user. One such familiarapplication component is the Menu bar. Menus are used to provide a user withchoices that control the application. Menus are easily incorporated into VisualBasic programs using the Menu Editor. A good way to think about elements of a menu structure is to consider them as ahierarchical list of command buttons that only appear when pulled down from themenu bar. When you click on a menu item, some action is taken. Like commandbuttons, menu items are named, have captions, and have properties. The Menu Editor allows us to define the menu structure, adding access keys andshortcut keys, if desired. We then add code to the Click events we need torespond to. The Menu Editor is selected from the Tools menu bar or by clickingthe Menu Editor on the toolbar. This selection can only be made when the formneeding the menu is active. Upon selecting the editor, and entering the examplemenu structure, the editor window looks like this:

Page 186: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

TheCaption box is where you type the text that appears in the menu bar. Access is defined in the standard way using the ampersand (&). Separator bars (ahorizontal line used to separate menu items) are defined by using a Caption of asingle hyphen (-). When assigning captions and access keys, try to use conformto any established Windows standards. TheName box is where you enter a control name for each menu item. This isanalogous to the Name property of command buttons and is the name used to setproperties and establish the Click event procedure for each menu item. Eachmenu item must have a name, even separator bars! The prefix menuis used toname menu items. Sub-menu item names usually refer back to main menuheadings. For example, if the menu item New is under the main heading Filemenu, use the name mnuFileNew. TheIndex box is used for indexing any menu items defined as control arrays. TheShortcut dropdown box is used to assign shortcut keystrokes to any item ina menu structure. The shortcut keystroke will appear to the right of the caption for the menu item. An example of such a keystroke is using Ctrl+X to cut text. · TheHelpContextID and Negotiate Positionboxes relate to using on-line helpand object linking embedding, and are beyond the scope of this discussion. · Each menu item has four properties associated with it. These properties can beset at design time using the Menu Editor or at run-time using the standard dotnotation. These properties are: Checked Used to indicate whether a toggle option is turned onor off. If true, a check mark appears next to

themenu item. Enabled If true, menu item can be selected. If False, menuitem is grayed and cannot be selected.

Page 187: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

Visible Controls whether the menu item appears in thestructure. Window List Used with Multiple Document Interface (MDI) – notdiscussed here. · At the bottom of the Menu Editor Form is a list box displaying the hierarchical list ofmenu items? Sub-menu items are indented to their level in the hierarchy. The rightand left arrows adjust the levels of menu items, while the up and down arrows move items within the same level. The Next, Insert, and Delete buttons are usedto move the selection down one line, insert a line above the current selection, ordelete the current selection, respectively. · Let’s look at the process of entering the example menu structure. To do this, we‘stack’ the three menus on top of each other, that isentering items as a long list. Foreach item in this list, we provide a Caption (with access key, if any), a Name(indicative of where it is in the structure), a shortcut key (if any), and provideproper indentation to indication hierarchical location (use the left and right arrowsto move in and out). · After entering this structure, the complete list box at the bottom of the Menu Editorwould look like this (notice access keys are indicated with ampersands andshortcut keys are listed at the right, and, the assigned names are shown at the left- these don’t really appear in the Menu Editor list box; they are shown to illustrateone possible naming convention): · At first, using the Menu Editor may seem a little clunky. After you’ve done acouple of menu structures, however, its use becomes obvious. A neat thing is:after setting up your menu, you can look at it in the Visual Basic design mode andsee if it looks like it should. In the next example, you’ll get practice setting up asimilar menu structure. Using Pop-Up Menus · Pop-up menus can show up anywhere on a form, usually being activated by asingle or double-click of one of the two mouse buttons. Most Windowsapplications, and Windows itself, use pop-up menus. For example, using the righthand mouse button on almost any object in Windows 95 will display a pop-upmenu. In fact, with the introduction of such pop-up menus with Windows 95, theneed for adding such menus to Visual Basic applications has been reduced. · Adding pop-up menus to your Visual Basic application is a two-step process.First, you need to create the menu using the Menu Editor (or, you can use anyexisting menu structure with at least one sub-menu). If creating a unique pop-upmenu (one that normally does not appear on the menu bar), it’sVisible property isset to be False at design time. Once created, the menu is displayed on a formusing the PopupMenu method. · ThePopup Menu method syntax is: ObjectName.PopupMenu MenuName, Flags, X, Y The ObjectName can be omitted if working with the current form. The argumentsare: MenuName Full-name of the pop-up menu to display. Flags Specifies location and behavior of menu (optional). X, Y (X, Y) coordinates of menu in twips (optional; if either valueis omitted, the current mouse coordinate is used). · TheFlags setting is the sum of two constants. The first constant specifieslocation: Value Meaning Symbolic Constant 0 Left side of menu is at X coordinate vbPopupMenuLeftAlign 4 Menu is centered at X coordinate vbPopupMenuCenterAlign 8 Right side of menu is at X coordinate vbPopupMenuRightAlign

Page 188: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

· You need to decide where to put the code that displays the pop-up menu that isthe PopupMenu method. Usually, a pop-up menu is displayed in response to aClick event or MouseDown event. The standard (starting with Windows 95)seems to be leaning toward displaying a pop-up menu in response to a rightmouse button click. · Just like other menus, each item on your pop-up menu will need code for thecorresponding Click event. Many times, though, the code is simply a call to anexisting menu item’s Click event. Assigning Icons to Forms · Notice that whenever you run an application, a small icon appears in the upper lefthand corner of the form. This icon is also used to represent the form when it isminimized at run-time. The icon seen is the default Visual Basic icon for forms.Using the Icon property of a form, you can change this displayed icon. · The idea is to assign a unique icon to indicate the form’s function. To assign anicon, click on the Icon property in the Property Window for the form. Click on theellipsis (...) and a window that allows selection of icon files will appear. · The icon file you load must have the .ico filename extension and format. Whenyou first assign an icon to a form (at design time), it will not appear on the form. Itwill only appear after you have run the application once. Designing Your Own Icon with IconEdit · Visual Basic offers a wealth of icon files from which you could choose an icon toassign to your form(s). But, it’s also fun to design your own icon to add thatpersonal touch. · PCMagazineoffers a free utility called IconEdit that allows you to design andsave icons. Included with these notes is this program and other files (directoryIconEdit). To install these files on your machine, copy the folder to your hard drive. · To run Icon Edit, click Start on the Windows 95 task bar, and then click Run. Find theIconEdit.exe program (use Browse mode). You can also establish a shortcut tostart IconEdit from your desktop, if desired. The following Editor window willappear:

Page 189: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

· The basic idea of IconEdit is to draw an icon in the 32 x 32 grid displayed. Youcan draw single points, lines, open rectangles and ovals, and filled rectangles andovals. Various colors are available. Once completed, the icon file can be savedfor attaching to a form. · Another fun thing to do with IconEdit is to load in Visual Basic icon files and seehow much artistic talent really goes into creating an icon. · We won’t go into a lot of detail on using the IconEdit program here - I just want youto know it exists and can be used to create and save icon files. Its use is fairlyintuitive. Consult the on-line help of the program for details. And, there is a .txtfile included that is very helpful. Creating Visual Basic Executable Files · Up to now, to run any of the applications created, we needed Visual Basic. Thegoal of creating an application is to let others (without Visual Basic) use it. This isaccomplished by creating an executable version of the application. · Before creating an executable, you should make sure your program is free ofbugs and operating as desired. Save all forms, modules, and project files. Anylater changes to the application will require re-creating the executable file. · The executable file will have the extension .exe. To create an exe file for yourapplication, select Make [Project name] exe from Visual Basic’s File menu.This will display the Make EXE File dialog box, where you name the exe file. Toopen the Options box, click that button. The EXE Options dialog box will appear:

· We’ll only concern ourselves with two pieces of information in this box: Title andIcon. The Title is the name you want to give your application. It does not have tobe the same as the Project name. The Icon is selected from icons assigned toform(s) in your application. The selected icon is used to identify the applicationeverywhere it is needed in Windows 95. · Once you have selected these options, return to the Make EXE File dialog box,and select a directory (best to use the same directory your application files are in) andname for your executable file. Click OK and the exe file is created.

Page 190: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

· Use Windows Explorer to confirm creation of the file. And, while there, doubleclickthe executable file name and the program will run! Using the Visual Basic Package & Deployment Wizard · We were able to run the Note Editor Executable file because Visual Basic isinstalled on our system. If you gave someone a copy of your exe file and they triedto run it, it wouldn’t work (unless they have Visual Basic installed also). Thereason it wouldn’t run is that the executable file also needs some ancillary files(primarily, so-called dynamic link libraries) to run properly. These libraries providemost of the code associated with keeping things on a form working properly. · So to allow others to run your application, you need to give them the executablefile (exe) and at least two dynamic link libraries. Unfortunately, these dynamic linklibraries take up over 1 Meg of disk space, so it’s hard to move those around on afloppy disk. · Visual Basic solves this ‘distribution problem’ by providing a very powerful toolcalled the Visual Basic Package & Deployment Wizard. This wizard isinstalled along with Visual Basic. · The Package & Deployment Wizard prepares your application for distribution. Ithelps you determine which files to distribute, creates a Setup program (written inVisual Basic) that works like all other Windows Setup programs (setup.exe),compresses all required files to save disk space, and writes the compressed filesto the distribution media of choice, usually floppy disk(s). · To start the Package & Deployment Wizard, click the Start button in Windows,then find the Visual Basic program folder - click on Visual Basic Tools, thenchoose Package & DeploymentWizard The setup follows several steps. Thedirections provided with each step pertain to the simple applications we developin class. For more complicated examples, you need to modify the directions,especially regarding what files you need to distribute with your application. Step 1. Initial Information. Enter the path and file name for your project file(.vbp). Click the ellipsis (...) to browse vbp files. If an executable (.exe) file doesnot exist, one will be created. Click the ‘Package’ button to continue. If you havepreviously saved a setup package for the selected project, it will load the packagefile created during that session.

Page 191: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

Step 2. Package Type. Choose the Standard Setup Package (we want astandard setup program). Click Next to continue. Step 3. Package Folder. Select a directory where you want the applicationdistribution package to be saved. Click Next to continue. Click Back to return tothe previous step. Step 4. Included Files. The Package & Deployment Wizard will list all files itbelieves are required for your application to function properly. If your applicationrequires any files not found by the wizard (for example, external data files you havecreated), you would add them to the setup list here (click Add). To continue, clicknext. Click Back to return to the previous step. Step 5. Cab Options. Distribution files are called cab files (have a cabextension). You can choose a Single cab file written to your hard drive (if you useCD ROM distribution), or Multiple cab files (to allow distribution on floppy disks). Ifyou choose, Multiple, you also specify the capacity of the disks you will use towrite your distribution file(s). Make your choice. Click Next to Continue. ClickBack to return to the previous step. Step 6. Installation Title. Enter a title you want your application to have. ClickNext to Continue. Click Back to return to previous step. Step 7. Start Menu Items. This step determines where your installedapplication will be located on the user’s Start menu. We will use the defaultchoice. Click Next to Continue. Click Back to return to previous step. Step 8. Install Locations. The wizard gives you an opportunity to change thelocations of installed files. Click Next to Continue. Click Back to return toprevious step. Step 9. Shared Files. Some files in your application may be shared by otherapplications. Shared files will not be removed if the application is uninstalled.Decide if you have shared files. Click Next to Continue. Click Back to return toprevious step. Step 10. Finished! Provide a name for saving the script for this wizard session(a file that saves answers to all the questions you just answered). Click Finish toContinue. Click Back to return to previous step. The wizard will create and writethe cab files and tell you where they are saved. Click Close. You will be returnedto the Package & Deployment Wizard opening window. Click Close. Step 11. Write Distribution Media. This is not a step in the wizard, but one youmust take. The cab files (distribution files) the wizard wrote must now be copiedto your distribution media. If you wrote a single cab file (for CD ROM), copy thatfile, the setup.exe file (the setup application), and the setup.lst file to your CDROM). If you wrote multiple files (for floppy disks), copy the setup.exe, setup’s,and first cab file (1 at end of file name) to floppy number 1. Copy the second cabfile (2 at end of file name) to floppy number 2. Copy all subsequent cab files to asmany floppies as needed. Properly label all floppies. · To install the application using the distribution CD ROM or floppy disk(s), a usersimply puts CD ROM or floppy number 1 in a drive. Then, through the WindowsExplorer, run the setup.exe program. The user will be taken through theinstallation procedure step-by-step. The procedure is nearly identical to theinstallation process for all Microsoft products. · The Package & Deployment Wizard is a very powerful tool. We’ve only looked atusing it for simple applications. As your programming skills begin to includedatabase access and other advanced topics, you will need to become familiarwith other files that should be distributed with your applications. Error-Handling, Debugging and File Input/output Review and Preview

Page 192: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

In this class, we expand on our Visual Basic knowledge from past classes andexamine a few new topics. We first look at handling errors in programs, usingboth run-time error trapping and debugging techniques. We then study input andoutput to disks using sequential files and random access files. Error Types No matter how hard we try, errors do creep into our programs. These errors canbe grouped into three categories; 1. Syntax errors 2. Run-time errors 3. Logic errors Syntax errors occur when you mistype a command or leave out an expectedphrase or argument. Visual Basic detects these errors as they occur and evenprovides help in correcting them. You cannot run a Visual Basic program until allsyntax errors have been corrected. Run-time errors are usually beyond your program's control. Examples include: when a variable takes on an unexpected value (divide by zero), when a drive dooris left open, or when a file is not found. Visual Basic allows you to trap such errorsand make attempts to correct them. Logic errors are the most difficult to find. With logic errors, the program willusually run, but will produce incorrect or unexpected results. The Visual Basicdebugger is an aid in detecting logic errors. Design your application carefully. More design time means less debuggingtime. Use comments where applicable to help you remember what you were tryingto do. Use consistent and meaningful naming conventions for your variables, objects,and procedures. Run-Time Error Trapping and Handling Run-time errors are trappable. That is, Visual Basic recognizes an error hasoccurred and enables you to trap it and take corrective action. If an error occursand is not trapped, your program will usually end in a rather unceremonious Manner. Error trapping is enabled with the On Error statement: On Error GoTo errlabel Yes, this uses the dreaded Go Tostatement! Any time a run-time error occursfollowing this line, program control is transferred to the line labeled errlabel.Recall a labeled line is simply a line with the label followed by a colon (:). The best way to explain how to use error trapping is to look at an outline of anexample procedure with error trapping. Sub Sub Example() . . [Declare variables ...] . On Error Go ToHandle Errors . . [Procedure code] . Exit Sub HandleErrors: .

Page 193: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

. [Error handling code]

. End Sub Once you have set up the variable declarations, constant definitions, and anyother procedure preliminaries, the On Error statement is executed to enable errortrapping. Your normal procedure code follows this statement. The error handlingcode goes at the end of the procedure, following the Handle Errorsstatementlabel. This is the code that is executed if an error is encountered anywhere in theSub procedure. Note you must exit (with Exit Sub) from the code before reachingthe Handle Errors line to avoid inadvertent execution of the error handling code. Since the error handling code is in the same procedure where an error occurs, allvariables in that procedure are available for possible corrective action. If at sometime in your procedure, you want to turn off error trapping that is done with thefollowing statement: On Error Go To 0 Once a run-time error occurs, we would like to know what the error is and attemptto fix it. This is done in the error handling code. Visual Basic offers help in identifying run-time errors. The Err object returns, in itsNumber property (Err. Number), the number associated with the current errorcondition. (The Err function has other useful properties that we won’t cover here -consult on-line help for further information.) The Error () function takes this errornumber as its argument and returns a string description of the error. Consult onlinehelp for Visual Basic run-time error numbers and their descriptions. Once an error has been trapped and some action taken, control must be returnedto your application. That control is returned via the Resume statement. There arethree options: Resume Lets you retry the operation that caused the error.That is, control is returned to the line where the

erroroccurred. This could be dangerous in that, if the errorhas not been corrected (via code or by the user), aninfinite loop between the error handler and theprocedure code may result.

Resume Next Program control is returned to the line immediatelyfollowing the line where the error occurred. Resume label Program control is returned to the line labeled label. Be careful with the Resume statement. When executing the error handling portionof the code and the end of the procedure is encountered before a Resume, anerror occurs. Likewise, if a Resume is encountered outside of the error handlingportion of the code, an error occurs. General Error Handling Procedure Development of an adequate error handling procedure is applicationdependent. You need to know what type of errors you are looking for and whatcorrective actions must be taken if these errors are encountered. For example, if a 'divide by zero' is found, you need to decide whether to skip the operation or dosomething to reset the offending denominator. What we develop here is a generic framework for an error handling procedure. Itsimply informs the user that an error has occurred, provides a description of theerror, and allows the user to Abort, Retry, or Ignore. This framework is a goodstarting point for designing custom error handling for your applications. The generic code (begins with label Handle Errors) is: Handle Errors: Select Case MsgBox (Error (Err.Number), vbCritical + vbAbortRetryIgnore, "Error Number" + Str (Err.Number)) Case vbAbort

Page 194: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

Resume ExitLine Case vbRetry Resume Case vbIgnore Resume Next End Select ExitLine: Exit Sub Let’s look at what goes on here. First, this routine is only executed when an erroroccurs. A message box is displayed, using the Visual Basic provided errordescription [Error(Err.Number)] as the message, uses a critical icon along withthe Abort, Retry, and Ignore buttons, and uses the error number [Err.Number]as the title. This message box returns a response indicating which button wasselected by the user. If Abort is selected, we simply exit the procedure. (This isdone using a Resume to the line labeled ExitLine. Recall all error trapping mustbe terminated with a Resume statement of some kind.) If Retry is selected, theoffending program line is retried (in a real application, you or the user would haveto change something here to correct the condition causing the error). If Ignore is selected, program operation continues with the line following the error causing Line. To use this generic code in an existing procedure, you need to do three things: 1. Copy and paste the error handling code into the end of your procedure. 2. Place an Exit Sub line immediately preceding the Handle Errorslabeled line. 3. Place the line, On Error Go ToHandle Errors, at the beginning of yourprocedure. For example, if your procedure is the Sub Exampleseen earlier, the modifiedcode will look like this: Sub Sub Example() . . [Declare variables ...] . On Error GoTo Handle Errors [Procedure code] . Exit Sub HandleErrors: Select Case MsgBox (Error (Err.Number), vbCritical + vbAbortRetryIgnore, "Error Number" + Str (Err.Number)) Case vbAbort Resume ExitLine Case vbRetry Resume Case vbIgnore Resume Next End Select ExitLine: Exit Sub End Sub Again, this is a very basic error-handling routine. You must determine its utility in yourapplications and make any modifications necessary. Specifically, you need code toclear error conditions before using the Retry option. One last thing. Once you've written an error handling routine, you need to test it tomake sure it works properly. But, creating run-time errors is sometimes difficultand perhaps dangerous. Visual Basic comes to the rescue! The Visual

Page 195: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

BasicErr objects has a method (Raise) associated with it that simulates the occurrenceof a run-time error. To cause an error with value Number, use: Err. Raise Number We can use this function to completely test the operation of any error handler wewrite. Don’t forget to remove the Raise statement once testing is completed,though! And, to really get fancy, you can also use Raise to generate your own‘application-defined’ errors. There are errors specific to your application that youwant to trap. To clear an error condition (any error, not just ones generated with the Raisemethod), use the method Clear: Err. Clear Debugging Visual Basic Programs We now consider the search for, and elimination of, logic errors. These areerrors that don’t prevent an application from running, but cause incorrect orunexpected results. Visual Basic provides an excellent set of debugging tools to aid in this search. Debugging a code is an art, not a science. There are no prescribed processesthat you can follow to eliminate all logic errors in your program. The usualapproach is to eliminate them as they are discovered. What we’ll do here is present the debugging tools available in the Visual Basicenvironment (several of which appear as buttons on the toolbar) and describetheir use with an example. You, as the program designer, should select thedebugging approach and tools you feel most comfortable with. The interface between your application and the debugging tools is via threedifferent debug windows: the Immediate Window, the Locals Window, and theWatch Window. These windows can be accessed from the View menu (theImmediate Window can be accessed by pressing Ctrl+G). Or, they can beselected from the Debug Toolbar (accessed using the Toolbars option underthe View menu):

All debugging using the debug windows is done when your application is in breakmode. You can enter break mode by setting breakpoints, pressing Ctrl+Break,or the program will go into break mode if it encounters an untapped error or aStop statement. Once in break mode, the debug windows and other tools can be used to: Determine values of variables Set breakpoints Set watch variables and expressions Manually control the application Determine which procedures have been called Change the values of variables and properties Using the Debugging Tools

Page 196: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

There are several debugging tools available for use in Visual Basic. Access tothese tools is provided with both menu options and buttons on the Debug toolbar.These tools include breakpoints, watch points, calls, step into, step over, and stepout. The simplest tool is the use of direct prints to the immediate window. Printing to the Immediate Window: You can print directly to the immediate window while an application is running.Sometimes, this is all the debugging you may need. A few carefully placed printstatements can sometimes clear up all logic errors, especially in smallapplications. To print to the immediate window, use the Print method: Debug. Print [List of variables separated by commas or semi-colons] Debug. Print Example: 1. Place the following statement in the Command1_Click procedureafter the line calling the general procedure Fcn: Debug. Print X; Y and run the application. 2. Examine the immediate window. Note how, at each iteration of theloop, the program prints the value of X and Y. You could use thisinformation to make sure X is incrementing correctly and that Y valueslook acceptable. 3. Remove the Debug. Print statement. Breakpoints: In the above examples, the program ran to completion before we could look at thedebug window. In many applications, we want to stop the application while it isrunning, examine variables and then continue running. This can be done withbreakpoints. A breakpoint is a line in the code where you want to stop (temporarily) theexecution of the program, that is force the program into break mode. To set abreakpoint, put the cursor in the line of code you want to break on. Then, press<F9>or click the Breakpoint button on the toolbar or select Toggle Breakpointfrom the Debug menu. The line will be highlighted. When you run your program, Visual Basic will stop when it reaches lines withbreakpoints and allow you to use the immediate window to check variables andexpressions. To continue program operation after a breakpoint, press <F5>, clickthe Run button on the toolbar, or choose Start from the Run menu. You can also change variable values using the immediate window. Simply type avalid Basic expression. This can sometimes be dangerous, though, as it maychange program operation completely. Breakpoint Example: 1. Set a breakpoint on the X = X + 1 line in the sample program. Run theprogram. 2. When the program stops, display the immediate window and type thefollowing line: Print X;Y

Page 197: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

3. The values of these two variables will appear in the debug window. Youcan use a question mark (?) as shorthand for the command Print, ifyou’d like. Restart the application. Print the new variable values. 4. Try other breakpoints if you have time. Once done, all breakpoints canbe cleared by Ctrl+Shift+<F9>or by choosing Clear All Breakpointsfrom the Debug menu. Individual breakpoints can be toggled using<F9>or the Breakpoint button on the toolbar. Viewing Variables in the Locals Window: The locals window shows the value of any variables within the scope of thecurrent procedure. As execution switches from procedure to procedure, thecontents of this window changes to reflect only the variables applicable to thecurrent procedure. Repeat the above example and notice the values of X and Yalso appear in the locals window. Watch Expressions: The Add Watch option on the Debug menu allows you to establish watchexpressions for your application. Watch expressions can be variable values orlogical expressions you want to view or test. Values of watch expressions are displayed in the watch window. In break mode, you can use the Quick Watch button on the toolbar to add watchexpressions you need. Simply put the cursor on the variable or expression youwant to add to the watch list and click the Quick Watch button. Watch expressions can be edited using the Edit Watch option on the Debugmenu. Watch Expression Example: 1. Set a breakpoint at the X = X + 1 line in the example. 2. Set a watch expression for the variable X. Run the application.Notice X appears in the watch window. Every time you re-start theapplication, the value of X changes. 3. At some point in the debug procedure, add a quick watch on Y.Notice it is now in the watch window. 4. Clear the breakpoint. Add a watch on the expression: X = Y. SetWatch Type to ‘Break When Value Is True.’ Run the application. Notice it goes into break mode and displays the watch windowwhenever X = Y. Delete this last watch expression. Selecting the Call Stack button from the toolbar (or pressing Ctrl+L or selectingCall Stack from the View menu) will display all active procedures, that is thosethat have not been exited. Call Stack helps you unravel situations with nested procedure calls to give yousome idea of where you are in the application. Call Stack Example: 1. Set a breakpoint on the Fcn = Cint () line in the general functionprocedure. Run the application. It will break at this line. 2. Press the Call Stack button. It will indicate you are currently in the Fcnprocedure which was called from the Command1_Click procedure.Clear the breakpoint. While at a breakpoint, you may execute your program one line at a time bypressing <F8>, choosing the Step Into option in the Debug menu, or by clickingthe Step Into button on the toolbar. This process is single stepping. It allows you to watch how variables change (inthe locals window) or how your form changes, one step at a time.

Page 198: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

You may step through several lines at a time by using Run to Cursor option.With this option, click on a line below your current point of execution. Then pressCtrl+<F8>(or choose Run to Cursor in the Debug menu). The program will runthrough every line up to the cursor location, and then stop. Step into Example: 1. Set a breakpoint on the Do line in the example. Run the application. 2. When the program breaks, use the Step Into button to single stepthrough the program. 3. At some point, put the cursor on the Loop While line. Try the Run toCursor option (press Ctrl+<F8>). Procedure Stepping (Step Over): While single stepping your program, if you come to a procedure call you knowfunctions properly, you can perform procedure stepping. This simply executesthe entire procedure at once, rather than one step at a time. To move through a procedure in this manner, press Shift+<F8>, choose StepOver from the Debug menu, or press the Step Over button on the toolbar. Step over Example: 1. Run the previous example. Single step through it a couple of times. 2. One time through, when you are at the line calling the Fcn function,press the Step overbutton. Notice how the program did not singlestep through the function as it did previously. Function Exit (Step Out): While stepping through your program, if you wish to complete the execution of afunction you are in, without stepping through it line -by-line, choose the Step Outoption. The function will be completed and you will be returned to the procedureaccessing that function. To perform this step out, press Ctrl+Shift+<F8>, choose Step Out from theDebug menu, or press the Step Out button on the toolbar. Try this on theprevious example. Debugging Strategies We’ve looked at each debugging tool briefly. Be aware this is a cursoryintroduction. Use the on-line help to delve into the details of each tool described.Only through lots of use and practice can you become a proficient debugger. There are some guidelines to doing a good job, though. My first suggestion is: keep it simple. Many times, you only have one or two badlines of code. And you, knowing your code best, can usually quickly narrow downthe areas with bad lines. Don’t set up some elaborate debugging procedure ifyou haven’t tried a simple approach to find your error(s) first. Many times, just afew intelligently-placed debug. Printstatements or a few examinations of theimmediate and locals windows can solve your problem. A tried and true approach to debugging can be called Divide and Conquer. Ifyou’re not sure where your error is, guess somewhere in the middle of yourapplication code. Set a breakpoint there. If the error hasn’t shown up by then, youknow it’s in the second half of your code. If it has shown up, it’s in the first half.Repeat this division process until you’ve narrowed your search. And, of course, the best debugging strategy is to be careful when you first designand write your application to minimize searching for errors later. Sequential Files

Page 199: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

In many applications, it is helpful to have the capability to read and writeinformation to a disk file. This information could be some computed data orperhaps information loaded into a Visual Basic object. Visual Basic supports two primary file formats: sequential and random access.We first look at sequential files. A sequential file is a line-by-line list of data. You can view a sequential file withany text editor. When using sequential files, you must know the order in whichinformation was written to the file to allow proper reading of the file. Sequential files can handle both text data and variable values. Sequential accessis best when dealing with files that have lines with mixed information of differentlengths. I use them to transfer data between applications. Sequential File Output (Variables) We first look at writing values of variables to sequential files. The first step is toopena file to write information to. The syntax for opening a sequential file foroutput is: Open SeqFileName for Output As #N WhereSeqFileName is the name of the file to open and N is an integer filenumber. The filename must be a complete path to the file. When done writing to the file, Close it using: Close N Once a file is closed, it is saved on the disk under the path and filename used toopen the file. Information is written to a sequential file one line at a time. Each line of outputrequires a separate Basic statement. There are two ways to write variables to a sequential file. The first uses the Writestatement: Write #N, [variable list] Where the variable list has variable names delimited by commas. (If the variablelist is omitted, a blank line is printed to the file.) This statement will write one lineof information to the file, that line containing the variables specified in the variablelist. The variables will be delimited by commas and any string variables will beenclosed in quotes. This is a good format for exporting files to other applicationslike Excel. Sequential File Input (Variables) To read variables from a sequential file, we essentially reverse the writeprocedure. First, open the file using: Open SeqFileName for Input as #N WhereN is an integer file number and SeqFileName is a complete file path. Thefile is closed using: Close N The Input statement is used to read in variables from a sequential file. Theformat is: Input #N, [variable list] The variable names in the list are separated by commas. If no variables arelisted, the current line in the file N is skipped. Note variables must be read in exactly the same manner as they were written. So,using our previous example with the variables A, B, C, and D, the appropriatestatements are:

Page 200: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

Input #1, A, B, C Input #1, D These two lines read the variables A, B, and C from the first line in the file and Dfrom the second line. It doesn’t matter whether the data was originally written tothe file using Write or Print (i.e. commas are ignored). Writing and Reading Text Using Sequential Files In many applications, we would like to be able to save text information and retrieveit for later reference. This information could be a text file created by anapplication or the contents of a Visual Basic text box. Writing Text Files: To write a sequential text file, we follow the simple procedure: open the file, writethe file, and close the file. If the file is a line-by-line text file, each line of the file iswritten to disk using a single Print statement: Print #N, Line WhereLine is the current line (a text string). This statement should be in a loopthat encompasses all lines of the file. You must know the number of lines in yourfile, beforehand. Random Access Files Note that to access a particular data item in a sequential file; you need to read inall items in the file prior to the item of interest. This works acceptably well forsmall data files of unstructured data, but for large, structured files, this process istime-consuming and wasteful. Sometimes, we need to access data innon-sequential ways. Files which allow non-sequential access are randomaccess files. To allow non-sequential access to information, a random access file has a verydefinite structure. A random access file is made up of a number of records, eachrecord having the same length (measured in bytes). Hence, by knowing the lengthof each record, we can easily determine (or the computer can) where each recordbegins. The first record in a random access file is Record 1, not 0 as used inVisual Basic arrays. Each record is usually a set of variables, of different types,describing some item. The structure of a random access file is: A good analogy to illustrate the differences between sequential files and randomaccess files are cassette music tapes and compact discs. To hear a song on atape (a sequential device), you must go past all songs prior to your selection. Tohear a song on a CD (a random access device), you simply go directly to thedesired selection. One difference here though is we require all of our randomaccess records to be the same length - not a good choice on CD’s! The variable argument in the Get and Put statements is usually a single userdefinedvariable. Once read in, you obtain the component parts of this variableusing dot-notation. Prior to writing a user-defined variable to a random accessfile, you ‘load’ the component parts using the same dot-notation. There’s a lot more to using random access files; we’ve only looked at the basics.Refer to your Visual Basic documentation and on-line help for further information.In particular, you need to do a little cute programming when deleting records froma random access file or when ‘resorting’ records. Note to both write and read sequential and random access files, we need a filename for the Open statement. To ensure accuracy and completeness, it issuggested that common dialog boxes (briefly studied in Class 4) be used to getthis file name information from the user. I’ll provide you with a couple of codesegments that do just that. Both segments assume you have a common dialogbox on your form named cdlFiles, with the Cancel Errorproperty set equal totrue. With this property True, an error is generated by Visual Basic when theuser presses the Cancel button in the dialog box. By trapping this error, it allowsan elegant exit from the dialog box when canceling the operation is desired. The code segment to obtain a file name (MyFileName with default extension Ext)for opening a file to read is:

Page 201: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

Dim MyFileName as String, Ext As String cdlFiles.Filter = "Files (*." + Ext + ")|*." + Ext cdlFiles.DefaultExt = Ext cdlFiles.DialogTitle = "Open File" cdlFiles.Flags = cdlOFNFileMustExist + cdlOFNPathMustExist On Error Go To No_Open cdlFiles.ShowOpen MyFileName = cdlFiles.filename .. Exit Sub No_Open: Resume ExitLIne ExitLine: Exit Sub End Sub A few words on what’s going on here. First, some properties are set such thatonly files with Ext (a three letter string variable) extensions are displayed (Filterproperty), the default extension is Ext (Default Extproperty), the title bar is set(Dialog Titleproperty), and some Flags are set to insure the file and path exist(see Appendix II for more common dialog flags). Error trapping is enabled to trapthe Cancel button. Finally, the common dialog box is displayed and the filenameproperty returns with the desired name. That name is put in the string variableMyFileName. What you do after obtaining the file name depends on what type offile you are dealing with. For sequential files, you would open the file, read in theinformation, and close the file. For random access files, we just open the file here.Reading and writing to/from the file would be handled elsewhere in your coding. Each of these procedures is similar. The dialog box is opened and, if a filenameis returned, the file is read/written. If Cancel is pressed, no action is taken.These routines can be used as templates for file operations in other applications. 4. Save your application. Run it and test the Open and Save functions. Note youhave to save a file before you can open one. Check for proper operation of theCancel button in the common dialog box. 5. If you have the time, there is one major improvement that should be made to thisapplication. Notice that, as written, only the text information is saved, not theformatting (bold, italic, underline, size). Whenever a file is opened, the text isdisplayed based on current settings. It would be nice to save formattinginformation along with the text. This can be done, but it involves a fair amount ofreprogramming. Suggested steps: A. Add lines to the mnuFileSave_Click routine that write the text boxproperties Font Bold, Font Italic, Font Underline, and Font Sizeto aseparate sequential file. If your text file is named TxtFile.ned, I wouldsuggest naming the formatting file TxtFile.fmt. Use string functions toput this name together. That is, chop the Nedextension off the text filename and tack on the fmt extension. You’ll need the Len () and Left ()functions. B. Add lines to the mnuFileOpen_Click routine that read the text boxproperties FontBold, FontItalic, Font Underline, and Font Size fromyour format sequential file. You’ll need to define some intermediatevariables here because Visual Basic won’t allow you to readproperties directly from a file. You’ll also need logic to set/reset anycheck marks in the menu structure to correspond to these inputproperties. C. Add lines to the mnuFileNew_Clickprocedure that, whenthe userwants a new file, reset the text box properties FontBold, FontItalic,FontUnderline, and FontSize to their default values and set/reset thecorresponding menu check marks. D. Try out the modified application. Make sure every new option worksas it should.

Page 202: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

Actually, there are ‘custom’ tools (we’ll look at custom tools in Class 10) that dowhat we are trying to do with this modification that is save text box contents withformatting information. Such files are called ‘rich text files’ or rtf files. You mayhave seen these before when transferring files from one word processor toanother. 6. Another thing you could try: Modify the message box that appears when you try toExit. Make it ask if you wish to save your file before exiting - provide Yes, No,Cancel buttons. Program the code corresponding to each possible response.Use calls to existing procedures, if possible.

Graphics Techniques with Visual Basic Review and Preview In past classes, we've used some graphics tools: line tools, shape tools, imageboxes, and picture boxes. In this class, we extend our graphics programmingskills to learn how to draw lines and circles, do drag and drop, perform simple animation, and study some basic plotting routines. Graphics Methods Graphics methods apply to forms and picture boxes (remember a picture box islike a form within a form). With these methods, we can draw lines, boxes, andcircles. Before discussing the commands that actually perform the graphicsdrawing, though, we need to look at two other topics: screen management andscreen coordinates. In single program environments (DOS, for example), when something is drawn onthe screen, it stays there. Windows is a multi-tasking environment. If you switchfrom a Visual Basic application to some other application, your Visual Basic formmay become partially obscured. When you return to your Visual Basicapplication, you would like the form to appear like it did before being covered. Allcontrols are automatically restored to the screen. Graphics methods drawingsmay or may not be restored - we need them to be, though. To accomplish this, wemust use proper screen management. The simplest way to maintain graphics is to set the form or picture box'sAutoRedraw property to True. In this case, Visual Basic always maintains acopy of graphics output in memory (creates persistent graphics). Another wayto maintain drawn graphics is (with AutoRedraw set to False) to put all graphicscommands in the form or picture box's Paint event. This event is called wheneveran obscured object becomes unsecured. There are advantages anddisadvantages to both approaches (beyond the scope of discussion here). Fornow, we will assume our forms won't get obscured and, hence, beg off thequestion of persistent graphics and using the AutoRedraw property and/or Paintevent. All graphics methods described here will use the default coordinate system:

Page 203: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

Note the x (horizontal) coordinate runs from left to right, starting at 0 and extendingto ScaleWidth - 1. The y (vertical) coordinate goes from top to bottom, starting at0 and ending at ScaleHeight - 1. Points in this coordinate system will always bereferred to by a Cartesian pair, (x, y). Later, we will see how we can use anycoordinate system we want. ScaleWidth and ScaleHeight are object properties representing the “graphics”dimensions of an object. Due to border space, they are not the same as theWidth and Height properties. For all measurements in twips (default coordinates),ScaleWidth is less than Width and ScaleHeight is less than Height. That is, we can’t draw to all points on the form. PSet Method: To set a single point in a graphic object (form or picture box) to a particular color,use the PSet method. We usually do this to designate a starting point for othergraphics methods. The syntax is: ObjectName. PSet (x, y), Color WhereObjectName is the object name, (x, y) is the selected point, and Color isthe point color (discussed in the next section). If the ObjectName is omitted, thecurrent form is assumed to be the object. If Color is omitted, the object'sForeColor property establishes the color. PSet is usually used to initialize somefurther drawing process. Pset Method Example: This form has a ScaleWidth of 3975 (Width 4095) and a ScaleHeight of 2400 (Height 2805). The command: PSet (1000, 500) will have the result:

Page 204: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

The marked point (in color ForeColor, black in this case) is pointed to by theCartesian coordinate (1000, 500) - this marking, of course, does not appear onthe form. If you want to try this example, and the other graphic methods, put thecode in the Form Click event. Run the project and click on the form to see theresults (necessary because of the AutoRedraw problem). CurrentX and CurrentY: After each drawing operation, the coordinate of the last point drawn to ismaintained in two Visual Basic system variables, CurrentX and CurrentY. Thisway we always know where the next drawing operation will begin. We can alsochange the values of these variables to move this last point. For example, thecode: CurrentX = 1000 CurrentY = 500 Is equivalent to? PSet (1000, 500) Line Method: The Line method is very versatile. We can use it to draw line segments, boxes,and filled boxes. To draw a line, the syntax is: ObjectName.Line (x1, y1) - (x2, y2), Color WhereObjectName is the object name, (x1, y1) the starting coordinate, (x2, y2)the ending coordinate, and Color the line color. Like PSet, if ObjectName isomitted, drawing is done to the current form and, if Color is omitted, the object’sForeColor property is used. To draw a line from (CurrentX, CurrentY) to (x2, y2), use: ObjectName.Line - (x2, y2), Color There is no need to specify the start point since CurrentX and CurrentY areknown.

Page 205: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

To draw a box bounded by opposite corners (x1, y1) and (x2, y2), use: ObjectName.Line (x1, y1) - (x2, y2), Color, B and to fill that box (using the current Fill Pattern), use: ObjectName.Line (x1, y1) - (x2, y2), Color, BF Circle Method: The Circle method can be used to draw circles, ellipses, arcs, and pie slices.We'll only look at drawing circles - look at on-line help for other drawing modes. The syntax is: ObjectName.Circle (x, y), r, Color This command will draw a circle with center (x, y) and radius r, using Color. Circle Example: With the same example form, the command: Circle (2000, 1000), 800 produces the result:

Print Method: Another method used to 'draw' to a form or picture box is the Print method. Yes,for these objects, printed text is drawn to the form. The syntax is: ObjectName.Print [information to print] Here the printed information can be variables, text, or some combination. If noobject name is provided, printing is to the current form. Information will print beginning at the object's CurrentX and CurrentY value. Thecolor used is specified by the object's ForeColor property and the font isspecified by the object's Font characteristics. Print Method Example:

Page 206: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

The code (can’t be in the Form Load procedure because of that pesky AutoRedraw property): CurrentX=200 CurrentY=200 Print "Here is the line of text" will produce this result (I’ve used a large font):

Cls Method: To clear the graphics drawn to an object, use the Cls method. The syntax is: ObjectName.Cls If no object name is given, the current form is cleared. Recall Cls only clears thelowest of the three display layers. This is where graphics methods draw. For each graphic method, line widths, fill patterns, and other graphics features canbe controlled via other object properties. Consult on-line help for furtherinformation. Using Colors Notice that all the graphics methods can use a Color argument. If that argumentis omitted, the ForeColor property is used. Color is actually a hexadecimal (longinteger) representation of color - look in the Properties Window at some of thevalues of color for various object properties. So, one way to get color values is tocut and paste values from the Properties Window. There are other ways, though. RGB Function: The RGB function can be used to produce one of 224 (over 16 million) colors! Thesyntax for using RGB to specify the color property is: RGB (Red, Green, Blue) WhereRed, Green, and Blue are integer measures of intensity of thecorresponding primary colors. These measures can range from 0 (least intensity)to 255 (greatest intensity). For example, RGB (255, 255, 0) will produce yellow. Any of these four representations of color can be used anytime your Visual Basiccode requires a color value. Mouse Events Related to graphics methods are mouse events. The mouse is a primaryinterface to performing graphics in Visual Basic. We've already used the mouseto Click and DblClick on objects. Here, we see how to recognize other mouse events to allow drawing in forms and picture boxes. Mouse down Event:

Page 207: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

The MouseDown event procedure is triggered whenever a mouse button ispressed while the mouse cursor is over an object. The form of this procedure is: Sub ObjectName_MouseDown (Button As Integer, Shift as Integer, X As Single, Y as Single) . . End Sub The arguments are: Button Specifies which mouse button was pressed. Shift Specifies state of Shift, Ctrl, and Alt keys. X, Y Coordinate of mouse cursor when button waspressed. Values for the Button argument are: Symbolic Constant Value Description VbLeftButton 1 Left button is pressed. vbRightButton 2 Right button is pressed. vbMiddleButton 4 Middle button is pressed. Only one button press can be detected by the Mouse Down event. Values for theShift argument are: Symbolic Constant Value Description vbShiftMask 1 shift key is pressed. vbCtrlMask 2 Ctrl key is pressed. vbAltMask 4 Alt key is pressed. The Shift argument can represent multiple key presses. For example, if Shift = 5(vbShiftMask + vbAltMask), both the Shift and Alt keys are being pressed whenthe MouseDown event occurs. Drag and Drop Events Related to mouse events are drag and drop events. This is the process ofusing the mouse to pick up some object on a form and move it to another location.We use drag and drop all the time in Visual Basic design mode to locate objectson our application form. Drag and drop allows you to design a simple user interface where tasks can beperformed without commands, menus, or buttons. Drag and drop is very intuitiveand, at times, faster than other methods. Examples include dragging a file toanother folder or dragging a document to a printer queue. Any Visual Basic object can be dragged and dropped, but we usually use pictureand image boxes. The item being dragged is called the source object. The itembeing dropped on (if there is any) is called the target. Object Drag Properties: If an object is to be dragged, two properties must be set: Drag Mode Enables dragging of an object (turns off ability toreceive Click or MouseDown events).

Usually use 1-Automatic (vbAutomatic). DragIcon Specifies icon to display as object is being dragged.

Page 208: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

As an object is being dragged, the object itself does not move, only the DragIcon.To move the object, some additional code using the Move method (discussed ina bit) must be used. DragDrop Event: The DragDrop event is triggered whenever the source object is dropped on thetarget object. The procedure form is: Sub ObjectName_DragDrop (Source as Control, X as Single, Y As Single) End Sub The arguments are: Source Object being dragged. X, Y Current mouse cursor coordinates. DragOver Event: The Drag Overevent is triggered when the source object is dragged overanother object. Its procedure form is: Private Sub ObjectName_DragOver (Source as Control, X As Single, YAs Single, State As Integer) .. End Sub The first three arguments are the same as those for the DragDrop event. TheState argument tells the object where the source is. Its values are 0-Entering(vbEnter), 1-Leaving (vbLeave), 2-Over (vbOver). Database Access and Management Review and Preview In past classes, we’ve seen the power of the built-in Visual Basic tools. In thisclass, we look at one of the more powerful tools, the Data Control. Using this tool,in conjunction with associated ‘data-aware’ tools, allows us to access andmanage databases. We only introduce the ideas of database access andmanagement - these topics alone could easily take up a ten week course. A major change in Visual Basic, with the introduction of Version 6.0, is in itsdatabase management tools. New tools based on ActiveX Data Object (ADO)technology have been developed. These new tools will eventually replace theolder database tools, called DAO (Data Access Object) tools. We will onlydiscuss the ADO tools. Microsoft still includes the DAO tools for backwardcompatibility. You might want to study these on your own, if desired. Database Structure and Terminology In simplest terms, a database is a collection of information. This collection isstored in well-defined tables, or matrices. The rows in a database table are used to describe similar items. The rows arereferred to as database records. In general, no two rows in a database table willbe alike. The columns in a database table provide characteristics of the records. Thesecharacteristics are called database fields. Each field contains one specific pieceof information. In defining a database field, you specify the data type, assign alength, and describe other attributes. Here is a simple database example:

Page 209: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

In this database table, each record represents a single individual. The fields(descriptors of the individuals) include an identification number (ID No), Name,Date of Birth, Height, and Weight. · Most databases use indexes to allow faster access to the information in thedatabase. Indexes are sorted lists that point to a particular row in a table. In theexample just seen, the ID No field could be used as an index. · A database using a single table is called a flat database. Most databases aremade up of many tables. When using multiple tables within a database, thesetables must have some common fields to allow cross-referencing of the tables.The referral of one table to another via a common field is called a relation. Suchgroupings of tables are called relational databases. · In our first example, we will use a sample database that comes with Visual Basic.This database (BIBLIO.MDB) is found in the main Visual Basic directory (tryc:\Program Files\Microsoft Visual Studio\VB98). It is a database of books aboutcomputers. Let’s look at its relational structure. The BIBLIO.MDB database ismade up of four tables:

Page 210: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development
Page 211: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

The Authors table consists of author identification numbers, the author’s name,and the year born. The Publishers table has information regarding bookpublishers. Some of the fields include an identification number, the publisher name and pertinent phone numbers. The Title Author table correlates a book’sISBN (a universal number assigned to books) with an author’s identificationnumber. And, the Titles table has several fields describing each individual book,including title, ISBN, and publisher identification. Note each table has two types of information: source data and relational data.Source data is actual information, such as titles and author names. Relationaldata are references to data in other tables, such as Au_ID and PubID. In theAuthors, Publishers and Title Author tables, the first column is used as the tableindex. In the Titles table, the ISBN value is the index.

Here, the book in the Titles table, entitled “Step-by-step dBase IV,” has an ISBNof 0 -0280095-2-5 and a PubID of 52. Taking the PubID into the Publisherstable, determines the book is published by McGraw-Hill and also allows us toaccess all other information concerning the publisher. Using the ISBN in the TitleAuthor table provides us with the author identification (Au_ID) of 171, which,when used in the Authors table, tells us the book’s author is Toby Wraye. · We can form alternate tables from a database’s inherent tables. Such virtualtables, or logical views, are made using queries of the database. A query issimply a request for information from the database tables. As an example withthe

Page 212: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

BIBLIO.MDB database, using pre-defined query languages, we could ‘ask’ thedatabase to form a table of all authors and books published after 1992, or provideall author names starting with B. We’ll look briefly at queries. · Keeping track of all the information in a database is handled by a databasemanagement system (DBMS). They are used to create and maintaindatabases. Examples of commercial DBMS programs are Microsoft Access,Microsoft FoxPro, Borland Paradox, Borland dBase, and Claris FileMaker. Wecan also use Visual Basic to develop a DBMS. Visual Basic shares the same‘engine’ used by Microsoft Access, known as the Jet engine. In this class, we willsee how to use Visual Basic to access data, display data, and perform someelementary management operations. ADO Data Control · TheADO (ActiveX Data Object) data control is the primary interface between aVisual Basic application and a database. It can be used without writing any codeat all! Or, it can be a central part of a complex database management system.This icon may not appear in your Visual Basic toolbox. If it doesn’t, select Projectfrom the main menu, then click Components. The Components window willappear. Select Microsoft ADO Data Control, and then click OK. The control will beadded to your toolbox. · As mentioned in Review and Preview, previous versions of Visual Basic usedanother data control. That control is still included with Visual Basic 6.0 (forbackward compatibility) and has as its icon: Make sure you are not using this data control for the work in this class. Thiscontrol is suitable for small databases. You might like to study it on your own. · The data control (or tool) can access databases created by several otherprograms besides Visual Basic (or Microsoft Access). Some other formatssupported include Btrieve, dBase, FoxPro, and Paradox databases. · The data control can be used to perform the following tasks: 1. Connect to a database. 2. Open a specified database table. 3. Create a virtual table based on a database query. 4. Pass database fields to other Visual Basic tools, for display orediting. Such tools are bound tools (controls), or data aware. 5. Add new records or update a database. 6. Trap any errors that may occur while accessing data. 7. Close the database. · Data Control Properties: Align Determines where data control is displayed. Caption Phrase displayed on the data control. ConnectionString Contains the information used to establish aconnection to a database. Lock Type Indicates the type of locks placed on recordsduring editing (default setting makes

databasesread-only). Record set A set of records defined by a data control’sConnectionString and Record Source

properties.Run-time only. Record Source Determines the table (or virtual table) the datacontrol is attached to. · As a rule, you need one data control for every database table, or virtual table, youneed access to. One row of a table is accessible to each data control at any onetime. This is referred to as the current record. · When a data control is placed on a form, it appears with the assigned caption andfour arrow buttons:

Page 213: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

The arrows are used to navigate through the table rows (records). As indicated,the buttons can be used to move to the beginning of the table, the end of the table,or from record to record. Data Links · After placing a data control on a form, you set the ConnectionString property.The ADO data control can connect to a variety of database types. There are threeways to connect to a database: using a data link, using an ODBC data source, orusing a connection string. In this class, we will look only at connection to aMicrosoft Access database using a data link. A data link is a file with a UDLextension that contains information on database type. · If your database does not have a data link, you need to create one. This processis best illustrated by example. We will be using the BIBLIO.MDB database in ourfirst example, so these steps show you how to create its data link: 1. Open Windows Explorer. 2. Open the folder where you will store your data link file. 3. Right-click the right side of Explorer and choose New. From the list of files,select Microsoft Data Link. 4. Rename the newly created file BIBLIO.UDL 5. Right-click this new UDL file and click Properties. 6. Choose the Provider tab and select Microsoft Jet 3.51 OLE DB Provider(an Access database). 7. Click the Next button to go to the Connection tab. 8. Click the ellipsis and use the Select Access Database dialog box to choosethe BIBLIO.MDB file which is in the Visual Basic main folder. Click Open. 9. Click Test Connection. Then, click OK (assuming it passed). The UDL fileis now created and can be assigned to ConnectionString, using the stepsbelow. · If a data link has been created and exists for your database, click the ellipsis that appears next to the ConnectionString property. Choose Use Data Link File. Then, click Browse and find the file. Click Open. The data link is now assignedto the property. Click OK. Assigning Tables · Once the ADO data control is connected to a database, we need to assign atable to that control. Recall each data control is attached to a single table,whether it is a table inherent to the database or the virtual table we discussed.Assigning a table is done via the RecordSource property. · Tables are assigned by making queries of the database. The language used tomake a query is SQL (pronounced ‘sequel,’ meaning structured query language).

Page 214: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

SQL is an English-like language that has evolved into the most widely useddatabase query language. You use SQL to formulate a question to ask of thedatabase. The data base ‘answers’ that question with a new table of records and Fields that match your criteria. · A table is assigned by placing a valid SQL statement in the RecordSourceproperty of a data control. We won’t be learning any SQL here. There are manytexts on the subject - in fact; many of them are in the BIBLIO.MDB database we’vebeen using. Here we simply show you how to use SQL to have the data control‘point’ to an inherent database table. · Click on the ellipsis next to RecordSource in the property box. A PropertyPages dialog box will appear. In the box marked Command Text (SQL), typethis line: SELECT * FROM Table Name This will select all fields (the * is a wildcard) from a table named TableName inthe database. Click OK. · Setting the RecordSource property also establishes the Record setproperty,which we will see later is a very important property. · In summary, the relationship between the data control and its two primaryproperties (ConnectionString and RecordSource) is:

Bound Data Tools · Most of the Visual Basic tools we’ve studied can be used as bound, or data aware,tools (or controls). That means, certain tool properties can be tied to aparticular database field. To use a bound control, one or more data controls mustbe on the form. · Some bound data tools are: Label Can be used to provide display-only access to aspecified text data field. Text Box Can be used to provide read/write access to aspecified text data field. Probably, the most

Widely used data bound tool. Check Box Used to provide read/write access to a Booleanfield. Combo Box Can be used to provide read/write access to atext data field. List Box Can be used to provide read/write access to atext data field.

Page 215: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

Picture Box Used to display a graphical image from a bitmap,icon, or metafile on your form. Provides read/writeaccess to a image/binary data field.

Image Box Used to display a graphical image from a bitmap,icon, or metafile on your form (uses fewerresources than a picture box). Providesread/write access to an image/binary data field.

· There are also three ‘custom’ data aware tools, the DataCombo (better thanusing the bound combo box), Data List(better than the bound list box), andDataGrid tools, we will look at later. · Bound Tool Properties: Data Changed Indicates whether a value displayed in a boundcontrol has changed. Data Field Specifies the name of a field in the table pointedto by the respective data control. Data Source Specifies which data control the control is boundto. If the data in a data-aware control is changed and then the user changes focus toanother control or tool, the database will automatically be updated with the newdata (assuming Lock Type is set to allow an update). · To make using bound controls easy, follow these steps (in order listed) in placingthe controls on a form: 1. Draw the bound control on the same form as the data control to which itwill be bound. 2. Set the DataSource property. Click on the drop-down arrow to list thedata controls on your form. Choose one. 3. Set the DataField property. Click on the drop-down arrow to list thefields associated with the selected data control records. Make yourchoice. 4. Set all other properties, as required. By following these steps in order, we avoid potential data access errors. Creating a Virtual Table Many times, a database table has more information than we want to display. Or,perhaps a table does not have all the information we want to display. Forinstance, in Example 8 -1, seeing the Title and ISBN of a book is not realinformative - we would also like to see the Author, but that information is notprovided by the Titles table. In these cases, we can build our own virtual table,displaying only the information we want the user to see. We need to form a different SQL statement in the RecordSource property. Again,we won’t be learning SQL here. We will just give you the proper statement. ‘Rolodex’ Searching of the Books Database 1. We expand the book database application to allow searching for certain authornames. We’ll use a ‘rolodex’ approach where, by pressing a particular letterbutton, books with author last names corresponding to that button appear on theform. 2. We want a row of buttons starting at ‘A’ and ending at ‘Z’ to appear on the lowerpart of our form. Drawing each one individually would be a big pain, so we’ll letVisual Basic do all the work in the Form Loadprocedure. What we’ll do iscreate one command button (the ‘A’), make it a control array, and thendynamically create 25 new control array elements at run-time, filling each with adifferent letter. We’ll even let the code decide on proper spacing. Data Manager · At this point, we know how to use the data control and associated data boundtools to access a database. The power of Visual Basic lies in its ability tomanipulate records in code. Such tasks as determining the values of particularfields, adding records, deleting records, and moving from record to record areeasily done. This allows us to build a complete database management system(DBMS).

Page 216: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

· We don’t want to change the example database, BIBLIO.MDB. Let’s create ourown database to change. Fortunately, Visual Basic helps us out here. TheVisual Data Manager is a Visual Basic Add-In that allows the creation andmanagement of databases. It is simple to use and can create a databasecompatible with the Microsoft Jet (or Access) database engine. To examine an existing database using the Data Manager, follow these steps: 1. Select Visual Data Manager from Visual Basic’s Add-In menu (youmay be asked if you want to add SYSTEM.MDA to the .INI file – answerNo.) 2. Select Open Database from the Data Manager File menu. 3. Select the database type and name you want to examine. Once the database is opened, you can do many things. You can simply lookthrough the various tables. You can search for particular records. You can applySQL queries. You can add/delete records. The Data Manager is a DBMS initself. You might try using the Data Manager to look through the BIBLIO.MDBexample database. · To create a new database, follow these steps: 1. Select Visual Data Manager from Visual Basic’s Add-In menu (youmay be asked if you want to add SYSTEM.MDA to the .INI file – answerno.) 2. Select New from the Data Manager File menu. Choose database type(Microsoft Access, Version 7.0), then select a directory and enter aname for your database file. Click OK. 3. The Database window will open. Right click the window and selectNew Table. In the Name box, enter the name of your table. Thendefine the table’s fields, one at a time, by clicking Add Field, thenentering a field name, selecting a data type, and specifying the size ofthe field, if required. Once the field is defined, click the OK button toadd it to the field box. Once all fields are defined, click the Build theTable button to save your table. Custom Data Aware Controls · As mentioned earlier, there are three custom data aware tools, in addition to thestandard Visual Basic tools: the DataList, DataCombo, and DataGrid ADOtools. We’ll present each of these, giving their suggested use, some propertiesand some events. If the icons for these tools are not in the toolbox, select Projectfrom the main menu, then click Components. Select Microsoft DataListControls 6.0 (OLEDB) and Microsoft DataGrid 6.0 (OLEDB) in theComponents window. Click OK - the controls will appear. · Like the data control, previous versions of Visual Basic used DAO versions of thelist, combo, and grid controls, named DBList, DBCombo, and DBGrid. Makesure you are not using these tools. · Data List Box: The first bound data custom tool is the DataList Box. The list box is automatically filled with a field from a specified data control. Selections from thelist box can then be used to update another field from the same data control or,optionally, used to update a field from another data control. Some properties of the DataList box are: DataSource Name of data control that is updated by theselection. DataField Name of field updated in Record set specified byDataSource. RowSource Name of data control used as source of items inlist box. ListField Name of field in Recordset specified byRowSource used to fill list box. BoundColumn Name of field in Recordset specified byRow Source to be passed to DataField, once

Selection is made. This is usually the same asListField.

Page 217: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

BoundText Text value of BoundColumn field. This is the valuepassed to DataField property. Text Text value of selected item in list. Usually thesame as Bound Text. The most prevalent use of the DataList box is to fill the list from the database, thenallow selections. The selection can be used to fill any tool on a form, whether it isdata aware or not. · Data Combo Box: The DataCombo Box is nearly identical to the DataList box; hence we won’t lookat a separate set of properties. The only differences between the two tools is that,with the DataCombo box, the list portion appears as a drop-down box and theuser is given the opportunity to change the contents of the returned Text property. Data Grid Tool: The DataGrid tool is, by far, the most useful of the custom data bound tools. It candisplay an entire database table, referenced by a data control. The table can thenbe edited as desired. The DataGrid control is in a class by itself, when considering its capabilities. It isessentially a separate, highly functional program. The only property we’ll beconcerned with is the DataSource property, which, as always, identifies the tableassociated with the respective data control. Refer to the Visual BasicProgrammer’s Guide and other references for complete details on using theDataGrid control. As an example of the power of the DataGrid control, here’s what is obtained bysimply setting the DataSource property to the dtaExample data control, which isbound to the Titles table in the BIBLIO.MDB database: At this point, we can scroll through the table and edit any values we choose. Anychanges are automatically reflected in the underlying database. Column widthscan be changed at run-time! Multiple row and column selections are possible!Like we said a very powerful tool. Creating a Data Report · Once you have gone to all the trouble of developing and managing a database, itis nice to have the ability to obtain printed or displayed information from your data. The process of obtaining such information is known as creating a data report. · There are two steps to creating a data report. First, we need to create a DataEnvironment. This is designed within Visual Basic and is used to tell the datareport what is in the database. Second, we create the Data Report itself. This,too, is done within Visual Basic. The Data Environment and Data Report filesthen become part of the Visual Basic project developed as a databasemanagement system. The Visual Basic 6.0 data report capabilities are vast and using them is adetailed process. The use of these capabilities is best demonstrated byexample. We will look at the rudiments of report creation by building a tabular report for our phone database. Phone Directory - Building a Data Report We will build a data report that lists all the names and phone numbers in our phonedatabase. We will do this by first creating a Data Environment, then a Data Report. We will then reopen the phone database management project and add data reportingcapabilities. Creating a Data Environment 1. Start a new Standard EXE project.

Page 218: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

2. On the Project menu, click Add Data Environment. If this item is not on themenu, click Components. Click the Designers tab, and choose Data. Environment and click OK to add the designer to your menu. 3. We need to point to our database. In the Data Environment window, right-clickthe Connection1 tab and select Properties. In the Data Link Properties dialogbox, choose Microsoft Jet 3.51 OLE DB Provider. Click Next to get to theConnection tab. Click the ellipsis button. Find your phone database (mdb) file.Click OK to close the dialog box. 4. We now tell the Data Environment what is in our database. Right-click theConnection1 tab and click Rename. Change the name of the tab to Phone. Right-click this newly named tab and click Add Command to create aCommand1 tab. Right-click this tab and choose Properties. Assign thefollowing properties: Command Name PhoneList Connection Phone Database Object Table Object Name PhoneList 5. Click OK. All this was needed just to connect the environment to our database. 6. Display the properties window and give the data environment a name property ofden Phone. Click File and Save den Phone As. Save the environment in anappropriate folder. We will eventually add this file to our phone database Management system. At this point, my data environment window looks like this (Iexpanded the PhoneList tab by clicking the + sign):

Creating a Data Report Once the Data Environment has been created, we can create a Data Report. We willdrag things out of the Data Environment onto a form created for the Data Report, somake sure your Data Environment window is still available. 1. On the Project menu, click Add Data Report and one will be added to yourproject. If this item is not on the menu, click Components. Click the Designerstab, and choose Data Report and click OK to add the designer to your menu. 2. Set the following properties for the report: Name rptPhone Caption Phone Directory Data Source den Phone (your phone data environment - choose,don’t type) Data Member PhoneList (the table name - choose don’t type)

Page 219: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

3. Right-click the Data Report and click Retrieve Structure. This establishes areport format based on the Data Environment. 4. Note there are five sections to the data report: a Report Header, a PageHeader, a Detail section, a Page Footer, and a Report Footer. The headersand footers contain information you want printed in the report and on each page. To place information in one of these regions, right-click the selected region, click Add Control, and then choose the control you wish to place. These controls arecalled data report controls and properties are established just like you do forusual controls. Try adding some headers. 5. The Detail section is used to layout the information you want printed for eachrecord in your database. We will place two field listings (Name, Phone) there.Click on the Name tab in the Data Environment window and drag it to the Detailsection of the Data Report. Two items should appear: a text box Name and atext box Name (PhoneList). The first text box is heading information. Move thistext box into the Page Header section. The second text box is the actual value forName from the PhoneList table. Line this text box up under the Name header.Now, drag the Phone tab from the Data Environment to the Data Report. Adjustthe text boxes in the same manner. Our data report will have page headers Nameand Phone. Under these headers, these fields for each record in our databasewill be displayed. When done, the form should look something like this:

In this form, I’ve resized the labels a bit and added a Report Header. Also, makesure you close up the Detail section to a single line. Any space left in this sectionwill be inserted after each entry. 6. Click File and Save rptPhone As. Save the environment in an appropriatefolder. We will now reopen our phone database manager and attach this and thedata environment to that project and add capabilities to display the report. Accessing the Data Report 1. Reopen the phone directory project. Add a command button named cmdReportand give it a Caption of Show Report. (There may be two tabs in your toolbox,one named General and one named Data Report. Make sure you select from theGeneral tools.)

Page 220: Algacisnews.algacis.com/citm_uploads/All Units of Client Server .pdfa problem. In this dynamic world, the subject system analysis and design (SAD) mainly deals with the software development

2. We will now add the data environment and data report files to the project. Clickthe Project menu item, and then click Add File. Choose den Phoneand click OK.Also add rptPhone. Look at your Project Window. Those files should be listedunder Designers. 3. Use this code in cmdReport_Click: Private Sub cmdReport_Click() rptPhone.Show End Sub 4. This uses the Show method to display the data report.