Overview of SQL DDL, DML and DCL Commands. DDL is Data Definition Language statements. Some examples: CREATE - to create objects in the database ALTER - alters the structure of the database DROP - delete objects from the database TRUNCATE - remove all records from a table, including all spaces allocated for the records removed COMMENT - add comments to the data dictionary GRANT - gives user's access privileges to database REVOKE - withdraw access privileges given with the GRANT command DML is Data Manipulation Language statements. Some examples: SELECT - retrieve data from the a database INSERT - insert data into a table UPDATE - updates existing data within a table DELETE - deletes all records from a table, the space for the records remain CALL - call a PL/SQL or Java subprogram EXPLAIN PLAN - explain access path to data LOCK TABLE - control concurrency DCL is Data Control Language statements. Some examples: COMMIT - save work done SAVEPOINT - identify a point in a transaction to which you can later roll back ROLLBACK - restore database to original since the last COMMITSET TRANSACTION - Change transaction options like what rollback segment to use
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Overview of SQL DDL, DML and DCL Commands.
DDL is Data Definition Language statements.
Some examples: CREATE - to create objects in the database
ALTER - alters the structure of the database
DROP - delete objects from the database
TRUNCATE - remove all records from a table, including all spaces allocated for the records
removed
COMMENT - add comments to the data dictionary
GRANT - gives user's access privileges to database
REVOKE - withdraw access privileges given with the
GRANT command
DML is Data Manipulation Language statements.
Some examples:
SELECT - retrieve data from the a database
INSERT - insert data into a table
UPDATE - updates existing data within a table
DELETE - deletes all records from a table, the space for the records remain
CALL - call a PL/SQL or Java subprogram
EXPLAIN PLAN - explain access path to data
LOCK TABLE - control concurrency
DCL is Data Control Language statements. Some examples:
COMMIT - save work done
SAVEPOINT - identify a point in a transaction to which you can later roll back
ROLLBACK - restore database to original since the last
COMMITSET TRANSACTION - Change transaction options like what rollback segment to use
Basic SQL DDL Commands.
To practice basic SQL DDL Commands such as CREATE, DROP, etc.
1. SQL - CREATE TABLE
Syntax: CREATE TABLE tablename (column_name data_ type constraints, …)Example:
INPUT:
SQL>CREATE TABLE Emp ( EmpNo short CONSTRAINT PKey PRIMARY KEY,EName
VarChar(15), Job Char(10) CONSTRAINT Unik1 UNIQUE,Mgr short CONSTRAINT FKey1
REFERENCES EMP (EmpNo),Hiredate Date, DeptNo short CONSTRAINT FKey2
REFERENCES DEPT(DeptNo));
RESULT:
Table created.
SQL>Create table prog20 (pname varchar2(20) not null), doj date not null,dob date not null,sex
varchar(1) not null, prof1 varchar(20),prof2 varchar(20),salary number(7,2) not null);
Order by : The order by clause is used to display the results in sorted order.
Group by: The attribute or attributes given in the clauses are used to form groups.
Tuples with the same value on all attributes in the group by clause are placed in one group.
Having: SQL applies predicates (conditions) in the having clause after groups have
been formed, so aggregate function be used.
1. Display total salary spent for each job category
INPUTSQL>select job,sum (sal) from emp group by job;
CONSTRAINTS
SQL PRIMARY KEY Constraint
The PRIMARY KEY constraint uniquely identifies each record in a database table.
Primary keys must contain unique values.
A primary key column cannot contain NULL values.
Each table should have a primary key, and each table can have only ONE primary key.
SQL PRIMARY KEY Constraint on CREATE TABLE
The following SQL creates a PRIMARY KEY on the "P_Id" column when the "Persons" table is created
CREATE TABLE Persons(P_Id int NOT NULL,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255),CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName))
Note: In the example above there is only ONE PRIMARY KEY (pk_PersonID). However, the value of the pk_PersonID is made up of two columns (P_Id and LastName).
SQL PRIMARY KEY Constraint on ALTER TABLE
To create a PRIMARY KEY constraint on the "P_Id" column when the table is already created, use the following SQL:
ALTER TABLE PersonsADD PRIMARY KEY (P_Id)
To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY constraint on multiple columns, use the following SQL syntax:
ALTER TABLE PersonsADD CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName)
Note: If you use the ALTER TABLE statement to add a primary key, the primary key column(s) must already have been declared to not contain NULL values (when the table was first created).
To DROP a PRIMARY KEY Constraint
To drop a PRIMARY KEY constraint, use the following SQL:
A FOREIGN KEY in one table points to a PRIMARY KEY in another table.
Let's illustrate the foreign key with an example. Look at the following two tables:
The "Persons" table:
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
The "Orders" table:
O_Id OrderNo P_Id
1 77895 3
2 44678 3
3 22456 2
4 24562 1
Note that the "P_Id" column in the "Orders" table points to the "P_Id" column in the "Persons" table.
The "P_Id" column in the "Persons" table is the PRIMARY KEY in the "Persons" table.
The "P_Id" column in the "Orders" table is a FOREIGN KEY in the "Orders" table.
The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables.
The FOREIGN KEY constraint also prevents that invalid data form being inserted into the foreign key column, because it has to be one of the values contained in the table it points to.
SQL FOREIGN KEY Constraint on ALTER TABLE
To create a FOREIGN KEY constraint on the "P_Id" column when the "Orders" table is already created, use the following SQL:
To drop a FOREIGN KEY constraint, use the following SQL:
SQL>ALTER TABLE Orders DROP CONSTRAINT fk_PerOrders
SQL CHECK Constraint
The CHECK constraint is used to limit the value range that can be placed in a column.
If you define a CHECK constraint on a single column it allows only certain values for this column.
If you define a CHECK constraint on a table it can limit the values in certain columns based on values in other columns in the row.
SQL CHECK Constraint on CREATE TABLE
The following SQL creates a CHECK constraint on the "P_Id" column when the "Persons" table is created. The CHECK constraint specifies that the column "P_Id" must only include integers greater than 0.
CREATE TABLE Persons(P_Id int NOT NULL CHECK (P_Id>0),LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255))
To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple columns, use the following SQL syntax:
SQL CHECK Constraint on ALTER TABLE
To create a CHECK constraint on the "P_Id" column when the table is already created, use the following SQL:
MySQL / SQL Server / Oracle / MS Access:
SQL>ALTER TABLE Persons ADD CHECK (P_Id>0)
To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple columns, use the following SQL syntax:
MySQL / SQL Server / Oracle / MS Access:
SQL>ALTER TABLE Persons ADD CONSTRAINT chk_Person CHECK (P_Id>0 AND City='Sandnes')
To DROP a CHECK Constraint
To drop a CHECK constraint, use the following SQL:
SQL Server / Oracle / MS Access:
SQL>ALTER TABLE Persons DROP CONSTRAINT chk_Person
SQL>ALTER TABLE Persons NDROP CHECK chk_Person
INDEX
The CREATE INDEX statement is used to create indexes in tables.
Indexes allow the database application to find data fast; without reading the whole table.
Indexes
An index can be created in a table to find data more quickly and efficiently.
The users cannot see the indexes, they are just used to speed up searches/queries.
Note: Updating a table with indexes takes more time than updating a table without (because the indexes also need an update). So you should only create indexes on columns (and tables) that will be frequently searched against.
SQL CREATE INDEX SyntaxCreates an index on a table. Duplicate values are allowed:
SQL>CREATE INDEX index_name ON table_name (column_name)
SQL CREATE UNIQUE INDEX SyntaxCreates a unique index on a table. Duplicate values are not allowed:
SQL>CREATE UNIQUE INDEX index_name ON table_name (column_name)
Note: The syntax for creating indexes varies amongst different databases. Therefore: Check the syntax for creating indexes in your database.
CREATE INDEX Example
The SQL statement below creates an index named "PIndex" on the "LastName" column in the "Persons" table:
SQL>CREATE INDEX PIndex ON Persons (LastName)
If you want to create an index on a combination of columns, you can list the column names within the parentheses, separated by commas:
SQL>CREATE INDEX PIndex ON Persons (LastName, FirstName)
Writing Nested Queries.
To write queries using Set operations and to write nested queries.
SQL> delete from acc72 where accno= (select accno from acc1 where balance=45000);
1 row deleted.
TO UPDATE A TUPLE USING NESTED QUERY:
SQL> update acc72 set balance=75000 where br_name= (select br_name from acc1 where accno =1231);
1 row updated.
TO SELECT A TUPLE USING NESTED QUERY:
SQL> select * from acc72 where accno= 2 (select accno from acc12 where balance=34000);
Triggers:
A trigger is a statement that the system executes automatically.Triggers are similar to stored procedures. A trigger stored in the database can include SQL and PL/SQL or Java statements to run as a unit and can invoke stored procedures. However, procedures and triggers differ in the way that they are invoked. A procedure is explicitly run by a user, application, or trigger. Triggers are implicitly fired by Oracle when a triggering event occurs, no matter which user is connected or which application is being used.
A database trigger has three parts
1. A triggering event 2. A trigger constraint (Optional) 3. Trigger action
A triggering event can be an insert, update, or delete statement or a instance shutdown or startup etc. The trigger fires automatically when any of these events occur A trigger constraint specifies a Boolean expression that must be true for the trigger to fire. This condition is specified using the WHEN clause. The trigger action is a procedure that contains the code to be executed when the trigger fires.
Types of Triggers
The following are the different types of triggers.
Row triggers and statement triggers
A Row trigger fires once for each row affected. It uses FOR EACH ROW clause. They are useful if trigger action depends on number of rows affected.
Statement Trigger fires once, irrespective of number of rows affected in the table. Statement triggers are useful when triggers action does not depend on
Before and afterTriggers
While defining the trigger we can specify whether to perform the trigger action (i.e. execute trigger body) before or after the triggering statement. BEFORE and AFTER triggers fired by DML statements can only be defined on tables.
BEFORE triggers The trigger action here is run before the trigger statement.
AFTER triggers The trigger action here is run after the trigger statement.
INSTEAD of Triggers provide a way of modifying views that can not be modified directly using DML statements.
LOGON triggers fires after successful logon by the user and LOGOFF trigger fires at the start of user logoff.
Trigger uses and limitations:
A trigger cannot include COMMIT, SAVEPOINT and ROLLBACK. We can use only one trigger of a particular type . A table can have any number of triggers. We use correlation names :new and :old can be used to refer to data in command line and
data in table respectively.
Triggers on DDL statements
DDL trigger are of the following types
BEFORE CREATE OR AFTER CREATE trigger is fired when a schema object is created. BEFORE OR AFTER ALTER trigger is fired when a schema object is altered. BEFORE OR AFTER DROP trigger is fired when a schema object is dropped.
A trigger can be enabled means can be made to run or it can disabled means it cannot run. A trigger is automatically enabled when it is created. We need re-enable trigger for using it if it is disabled. To enable or disable a trigger using ALTER TRIGGER command, you must be owner of the trigger or should have ALTER ANY TRIGGER privilege. To create a trigger you must
have CREATE TRIGGER privilege, which is given to as part of RESOURCE privilege at the time of user creation.
Trigger Execution
A trigger is in either of two distinct modes:
Trigger Mode Definition
Enabled An enabled trigger runs its trigger action if a triggering statement is issued and the trigger restriction (if any) evaluates to true.
Disabled A disabled trigger does not run its trigger action, even if a triggering statement is issued and the trigger restriction (if any) would evaluate to true.
A subprogram is a named block of PL/SQL. There are two types of subprograms in PL/SQL namely Procedures and Functions. Every subprogram will have a declarative part, an executable part or body, and an exception handling part, which is optional.
Declarative part contains variable declarations. Body of a subprogram contains executable statements of SQL and PL/SQL. Statements to handle exceptions are written in exception part.
When client executes a procedure are function, the processing is done in the server. This reduces network traffic. The subprograms are compiled and stored in the Oracle database as stored programs and can be invoked whenever required. As they are stored in compiled form when called they only need to be executed. Hence they save time needed for compilation.
Subprograms provide the following advantages
1. They allow you to write PL/SQL program that meet our need 2. They allow you to break the program into manageable modules. 3. They provide reusability and maintainability for the code.
Procedures
Procedure is a subprogram used to perform a specific action. A procedure contains two parts specification and the body. Procedure specification begins with CREATE and ends with procedure name or parameters list. Procedures that do not take parameters are written without a parenthesis. The body of the procedure starts after the keyword IS or AS and ends with keyword END.
In the above given syntax things enclosed in between angular brackets (“< > “) are user defined and those enclosed in square brackets (“[ ]”) are optional. OR REPLACE is used to overwrite the procedure with the same name if there any. AUTHID clause is used to decide whether the procedure should execute with invoker (current-user or person who executes it) or with definer (owner or person created) rights .
Parameter Modes
Parameters are used to pass the values to the procedure being called. There are 3 modes to be used with parameters based on their usage. IN, OUT, and IN OUT. IN mode parameter used to pass the values to the called procedure. Inside the program IN parameter acts like a constant. i.e it cannot be modified.
OUT mode parameter allows you to return the value from the procedure. Inside Procedure the OUT parameter acts like an uninitialized variable. Therefore its value cannot be assigned to another variable.
IN OUT mode parameter allows you to both pass to and return values from the subprogram. Default mode of an argument is IN.
Functions:
A function is a PL/SQL subprogram, which is used to compute a value. Function is same like a procedure except for the difference that it have RETURN clause.
Syntax for Function
Examples
Function without arguments
Function with arguments. Different ways of executing the function.
2. Insert all the possible values into the vb1 table.
3. Enter commit command.
Algorithm for ADO Connection:
After creating the table in Oracle, Go to start menu
1. Start------> Settings------> Control Panel ------>Administrative Tools------>
Data Sources (ODBC) ------>User DSN------>Add------> Select Microsoft
ODBC for Oracle------>Finish------>OK
2. One new window will be appeared. In that window type Data Source Name as
table name created in Oracle. Type user name as Scott. Then click O.K.
Algorithm for ADODC in Visual Basic:
1. In Visual Basic create the labels, command buttons and their text boxes.2. In Visual Basic go to Project menu,3. Project---->Components---->Microsoft ADO Data Control 6.0 for OLEDB-->O.K4. Now ADODC Data Control available in toolbox.5. Drag and drop the ADODC Data Control into the form.6. Right click in ADODC Data Control then click the ADODC properties.7. One New window will be appeared. 8. Choose general tab select ODBC Data source name as the table created in Oracle.9. Choose authentication tab and select username, password as scott and tiger.10. Choose record source------>select Command type as adcmdTable. 11. Select Table or Stored procedure name as table created in Oracle.12. Click Apply------>O.K 13. Set the properties of each text box. 14. Select the data source as ADODC1 15. Select the Data field and set the required field name created in table
Menus in Visual basic 6.0 are created using the Menu object defined in the VB Library. The menu created so are flat Win98 style menus and do not support icons. Further they cannot be created at runtime and require “Menu Editor”, modification though can be made during runtime.
Menu bar is the standard feature of most windows applications. The main purpose of the menus is for easy navigation and control of an application. Some of the most common menu items are File, Edit, View, Tools, Help and more. Each item on the main menu bar also provide a list of options or in the form of a pull-down menu. When you create a Visual Basic 6 program, you need not include as many menu items as a full fledge Windows application such as Microsoft Words. What you need is to include those menu items that can improve the ease of using your program by the user, and not to confuse the user with unnecessary items. Adding menu bar is relatively easy to accomplish in Visual Basic. There are two ways to add menus to your application, one way is to use the Visual Basic's Application Wizard and the other way is to use the menu editor.
Click on “Menu Editor…” under Tools on main menubar. Menu editor is accessible only if a form is focussed.
Adding Menu Bar Using Visual Basic's Application Wizard The easiest
way to add menu bar to your application is by using Visual Basic's Application Wizard. This
wizard allows the user to insert fully customized standard windows menus into his or her
application. To start using Visual Basic's Application Wizard, you click on the Application
Wizard icon at the Visual Basic new project dialog box, as shown below:
REPORT
STEPS TO CREATE DATA REPORT:
Steps for Creating Data Reports
Open the Visual Basic Project Make the connection with the database using either Data Environment or through ADO Add Data Report to the project If using Data Environment then in Report properties
– DataSource : <Data Environment name>– DataMember : <Command name>– Drag the fields from the command into the report
If using ADO then– Create the appropriate no. of textboxes on the report.– In datafield property of textbox write the name of the field name as in Recordset.
Reports are important and useful in many respects because they provide useful and meaningful information concerning a set of data. In this chapter, we will show you how to create a report in Visual Basic 6.
In previous versions of Visual Basic 6, there is no primary reporting . Previous versions of Visual basic 6 uses Crystal Reports tool, a software from Seagate. Fortunately, Microsoft has integrated a good report writer into Visual Basic 6, so you no longer need to use Crystal Report.
Connecting the report to database using Data Environment Designer
Click the Project menu, then select Data Environment. from the drop-down menu. The default data environment will appear, as shown in figure 40.2
Now, to connect to the database, right-click connection1 and select Microsoft OLE DB Provider for Oracle (as we are using MS Access database) from the Data Link Properties dialog (as shown in Figure 40.3), then click next.
Retrieving Information from the Database
In order to use the database in your report, you need to create query to retrieve the information from the database. Here , we will use SQL command to create the query. First of all, right click on MyConnection to add a command to the data environment. The default command is Command1, you can rename it as MyCommand, as shown in Figure 40.5.
In order to use SQL command, right-click MyCommand and you can see its properties dialog. At the General tab, select SQL statement and key in the following SQL statement:
SELECT Au_ID, AuthorFROM Authors ORDER BY Author
This command is to select all the fields from the Authors table in the Biblio.Mdb database. The command ORDER BY Author is to arrange the list in ascending order according to the Authors' Names.
Now, you need to customize a few properties of your data report so that it can connect to the database. The first property to set is the DataSource, set it to MyDataEnvironment. Next, you need to set the DataMember property to MyCommand,as shown in Figure 40.6
To add data to your report, you need to drag the fields from MyCommand in MyDataEnvironment into MyDataReport, as shown in Figure 40.7.Visual Basic 6 will automatically draw a RptTextBox, along with a RptLabel control for each field on the report. You can customize the look of the labels as well as the TextBoxes from the properties window of MyDataReport.
The Final step is to set MydataReport as the Startup form from the Project menu, then run the program. You will see your report as shown in Figure 40.8. You can print out your report.