Uploaded by Mrs Kanimozhi K AI & DS

DDM Record

advertisement
Ex. No.: 1
Date:
Database Development Life cycle
AIM:
To Analyze, Design and implement the problem and come with the entities in it. Identify
what Data has to be persisted in the databases.
Getting started with PostgreSQL:
Download the PostgreSQL software from the given link and install it.
https://www.postgresql.org/download/
Database Development Life cycle:
Life cycle of database begins with analysis and defining of the problems and objectives.
Let us see the steps involved –
Stage of Database
system
development Lifecycle
Example of Facts
Database Planning
Example of Documentation
Produced
Aims and objectives of database Mission statements and objectives.
projects.
System Identification Description of major user views Definition of scope and boundary
(Job roles, business application
of database system, definition of
areas).
user views to be supported.
Requirements
Requirements of user views, User requirement specification,
Collection and
system specifications, including
systemspecification.
Analysis
performance
and
security
requirements.
Database design
User’s responses to checking the Logical database design, data
logical
database
design, dictionary,
physical
database
functionality provided by target
design.
DBMS.
Application Design
Users’ response to checking Application design.
interface design.
DBMS Selection
Functionality provided by target DBMS evaluation
DBMS.
Prototyping
User response to prototype.
Modified
user
requirement
specification
and
system
specification.
Implementation
Functionality provided by target
DBMS.
Data conversion and Format of current data, data import
loading
capability of target DBMS.
Testing
Test Results.
Testing strategies used
Performance testing results, new
Operational
User
manual,
analysis
of
or changing user and system performance results, modified
maintenance
requirements.
users requirements and system
specification.
1
Database Creation and Constraints:
SQL CREATE DATABASE Statement
The CREATE DATABASE statement is used to create a new SQL database.Syntax
CREATE DATABASE databasename;
Example
CREATE DATABASE testDB;
SQL DROP DATABASE Statement
The DROP DATABASE statement is used to drop an existing SQL database.Syntax
DROP DATABASE databasename;
Example
DROP DATABASE testDB;
Note: Use the \dt or \dt+ command in psql to show tables in a specific database.
PostgreSQL – Show Tables
PostgreSQL does not support the SHOW TABLES statement directly like MySQL does
but provides userswith an alternative.
SELECT * FROM tablename;
SQL CREATE TABLE Statement
The CREATE TABLE statement is used to create a new table in a database.Syntax
CREATE TABLE table_name (column1 datatype, column2 datatype, column3 datatype,);
The column parameters specify the names of the columns of the table.
The datatype parameter specifies the type of data the column can hold (e.g. varchar,
integer, date, etc.).
Example
CREATE TABLE Persons ( PersonID int, LastName varchar(255), FirstName
varchar(255),Address varchar(255), City varchar(255));
Create Table Using Another Table
A copy of an existing table can also be created using CREATE TABLE.
The new table gets the same column definitions. All columns or specific columns can be
selected.
If you create a new table using an existing table, the new table will be filled with the
existing values fromthe old table.
Syntax
CREATE TABLE new_table_name ASSELECT column1, column2,...
FROM existing_table_name
WHERE .......................... ;
The following SQL creates a new table called "TestTables" (which is a copy of the
"Customers" table):
Example
CREATE TABLE TestTable AS SELECT customername, contactnameFROM customers;
SQL DROP TABLE Statement
The DROP TABLE statement is used to drop an existing table in a database.Syntax
DROP TABLE table_name;SQL TRUNCATE TABLE
The TRUNCATE TABLE statement is used to delete the data inside a table, but not the
table itself.Syntax
TRUNCATE TABLE table_name;
2
SQL ALTER TABLE Statement
The ALTER TABLE statement is used to add, delete, or modify columns in an existing
table.
The ALTER TABLE statement is also used to add and drop various constraints on an
existing table.
ALTER TABLE - ADD Column
To add a column in a table, use the following syntax:ALTER TABLE table_name
ADD column_name datatype;
The following SQL adds an "Email" column to the "Customers" table: ALTER TABLE
Customers ADD Email varchar(255);
ALTER TABLE - DROP COLUMN
To delete a column in a table, use the following syntax (notice that some database systems
don't allowdeleting a column):
ALTER TABLE table_name
DROP COLUMN column_name;
The following SQL deletes the "Email" column from the "Customers" table: ALTER
TABLE Customers
DROP COLUMN Email;
ALTER TABLE - ALTER/MODIFY COLUMN
To change the data type of a column in a table, use the following syntax:ALTER TABLE
table_name
ALTER COLUMN column_name datatype;
Example
Look at the "Persons" table:
ID
1
2
3
LastName
Hansen
Svendson
Pettersen
FirstName
Ola
Tove
Kari
Address
Timoteivn 10
Borgvn 23
Storgt 20
City
Sandnes
Sandnes
Stavanger
Now we want to add a column named "DateOfBirth" in the "Persons" table. We use the
following SQL statement:
ALTER TABLE PersonsADD DateOfBirth date;
Notice that the new column, "DateOfBirth", is of type date and is going to hold a date. The
data typespecifies what type of data the column can hold.
The "Persons" table will now look like this:
ID
1
2
3
LastName
Hansen
Svendson
Pettersen
FirstName
Ola
Tove
Kari
Address
Timoteivn 10
Borgvn 23
Storgt 20
City
DateOfBirth
Sandnes
Sandnes
Stavanger
Change Data Type Example
Now we want to change the data type of the column named "DateOfBirth" in the "Persons"
table.We use the following SQL statement:
ALTER TABLE Persons
3
ALTER COLUMN DateOfBirth year;
Notice that the "DateOfBirth" column is now of type year and is going to hold a year in a
two- or four-digit format.
DROP COLUMN Example
Next, we want to delete the column named "DateOfBirth" in the "Persons" table. We use
the following SQL statement:
ALTER TABLE Persons DROP COLUMN DateOfBirth;
The "Persons" table will now look like this:
ID
1
2
3
LastName
Hansen
Svendson
Pettersen
FirstName
Ola
Tove
Kari
Address
Timoteivn 10
Borgvn 23
Storgt 20
City
Sandnes
Sandnes
Stavanger
SQL Constraints
SQL constraints are used to specify rules for data in a table.SQL Create Constraints
Constraints can be specified when the table is created with the CREATE TABLE
statement, or after thetable is created with the ALTER TABLE statement.
Syntax
CREATE TABLE table_name ( column1 datatype constraint, column2 datatype
constraint, column3 datatype constraint, .......... );
SQL constraints are used to specify rules for the data in a table.
Constraints are used to limit the type of data that can go into a table. This ensures the
accuracy and reliability of the data in the table. If there is any violation between the
constraint and the data action, the action is aborted.
Constraints can be column level or table level. Column level constraints apply to a
column, and table levelconstraints apply to the whole table.
The following constraints are commonly used in SQL:
•
•
•
•
•
•
•
NOT NULL - Ensures that a column cannot have a NULL value
UNIQUE - Ensures that all values in a column are different
PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies
each row in a table
FOREIGN KEY - Prevents actions that would destroy links between tables
CHECK - Ensures that the values in a column satisfies a specific condition
DEFAULT - Sets a default value for a column if no value is specified
CREATE INDEX - Used to create and retrieve data from the database very quickly
SQL NOT NULL Constraint
By default, a column can hold NULL values.
The NOT NULL constraint enforces a column to NOT accept NULL values.
This enforces a field to always contain a value, which means that you cannot insert a new
record, or updatea record without adding a value to this field.
SQL NOT NULL on CREATE TABLE
The following SQL ensures that the "ID", "LastName", and "FirstName" columns will
NOT accept NULLvalues when the "Persons" table is created:
4
Example
CREATE TABLE Persons ( ID int NOT NULL, LastName varchar(255) NOT NULL,
FirstName varchar(255) NOT NULL,Age int);
SQL NOT NULL on ALTER TABLE
To create a NOT NULL constraint on the "Age" column when the "Persons" table is
already created, usethe following SQL:
ALTER TABLE Persons MODIFY Age int NOT NULL;
SQL UNIQUE Constraint
The UNIQUE constraint ensures that all values in a column are different.
Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for uniqueness
for a column orset of columns.
A PRIMARY KEY constraint automatically has a UNIQUE constraint.
However, you can have many UNIQUE constraints per table, but only one PRIMARY
KEY constraint pertable.
SQL UNIQUE Constraint on CREATE TABLE
The following SQL creates a UNIQUE constraint on the "ID" column when the "Persons"
table is created: CREATE TABLE Persons (ID int NOT NULL, LastName varchar(255)
NOT NULL, FirstName varchar(255), Age int, UNIQUE (ID));
SQL UNIQUE Constraint on ALTER TABLE
To create a UNIQUE constraint on the "ID" column when the table is already created, use
the followingSQL:
ALTER TABLE PersonsADD UNIQUE (ID);
DROP a UNIQUE Constraint
To drop a UNIQUE constraint, use the following SQL: ALTER TABLE Persons DROP
INDEX UC_Person;
SQL PRIMARY KEY Constraint
The PRIMARY KEY constraint uniquely identifies each record in a table. Primary keys
must contain UNIQUE values, and cannot contain NULL values.
A table can have only ONE primary key; and in the table, this primary key can consist of
single or multiplecolumns (fields).
SQL PRIMARY KEY on CREATE TABLE
The following SQL creates a PRIMARY KEY on the "ID" column when the "Persons"
table is created: CREATE TABLE Persons (ID int NOT NULL, LastName varchar(255)
NOT NULL,FirstName varchar(255), Age int, PRIMARY KEY (ID));
SQL PRIMARY KEY on ALTER TABLE
To create a PRIMARY KEY constraint on the "ID" column when the table is already
created, use thefollowing SQL:
ALTER TABLE Persons ADD PRIMARY KEY (ID);
To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY
constraint onmultiple columns, use the following SQL syntax:
ALTER TABLE Persons ADD CONSTRAINT PK_Person PRIMARY KEY
(ID,LastName);
5
DROP a PRIMARY KEY Constraint
To drop a PRIMARY KEY constraint, use the following SQL:
ALTER TABLE PersonsDROP PRIMARY KEY;
The FOREIGN KEY constraint is used to prevent actions that would destroy links between
tables.
A FOREIGN KEY is a field (or collection of fields) in one table, that refers to the
PRIMARY KEY inanother table.
The table with the foreign key is called the child table, and the table with the primary key
is called thereferenced or parent table.
Look at the following two tables:
Persons Table
PersonID LastName FirstName Age
1
Hansen
Ola
30
2
Svendson
Tove
23
Orders Table
OrderID OrderNumber PersonID
1
77895
3
2
44678
3
3
22456
2
4
24562
1
Notice that the "PersonID" column in the "Orders" table points to the "PersonID" column
in the "Persons"table.
The "PersonID" column in the "Persons" table is the PRIMARY KEY in the "Persons"
table. The "PersonID" column in the "Orders" table is a FOREIGN KEY in the "Orders"
table.
The FOREIGN KEY constraint prevents invalid data from being inserted into the foreign
key column,because it has to be one of the values contained in the parent table.
SQL FOREIGN KEY on CREATE TABLE
The following SQL creates a FOREIGN KEY on the "PersonID" column when the
"Orders" table iscreated:
CREATE TABLE Orders (OrderID int NOT NULL, OrderNumber int NOT NULL,
PersonID int, PRIMARY KEY (OrderID), FOREIGN KEY (PersonID) REFERENCES
Persons(PersonID)); FOREIGN KEY (PersonID) REFERENCES Persons(PersonID));
6
Ex. No.: 2
Date:
DATABASE DESIGN USING CONCEPTUAL MODELING (EREER)
AIM:
To create database using conceptual modeling using (ER-EER) model using SQL
workbench.
PROCEDURE:
ENHANCED ENTITY RELATIONSHIP (EER) MODEL:
Enhanced Entity Relationship (EER) Model is a high level data model which provides
extensions to original Entity Relationship (ER) model. EER Models supports more details
design. EER Modelingemerged as a solution for modeling highly complex databases.
EER uses UML notation. UML is the acronym for Unified Modeling Language; it is a
general purpose modeling language used when designing object oriented systems. Entities
are represented as class diagrams. Relationships are represented as associations between
entities. The diagram shown below illustrates an ER diagram using the UML notation.
We can deduce from this that the nature of the relationship between members and
paymentsentities is one-to-many.Now lets create EER model using MySQL Workbench In
the MySQL workbench , Click - "+"Button
7
Double click on Add Diagram button to open the workspace for ER diagrams.
Following window appears
8
Let's look at the two objects that we will work with.
The table object allows us to create entities and define the attributes associated with the
particular entity.
The place relationship button allows us to define relationships between entities.
The members' entity will have the following attributes
• Membership number
• Full names
• Gender
• Date of birth
• Physical address
• Postal address
Let's now create the members table
1. Drag the table object from the tools panel
2. Drop it in the workspace area. An entity named table 1 appears 3.Double
click on it. Theproperties window shown below appears
9
Next ,
1. Change table 1 to Members
2. Edit the default idtable1 to membership_number
3. Click on the next line to add the next field
4. Do the same for all the attributes identified in members' entity.
Your properties window should now look like this.
Repeat the above steps for all the identified entities.
Your diagram workspace should now look like the one shown below.
10
Lets create relationship between Members and Movie Rentals
1. Select the place relationship using existing columns too
2. Click on membership_number in the Members table
3. Click on reference_number in the MovieRentals table
Repeat above steps for other relationships. Your ER diagram should now look like this –
11
12
Ex.No.: 3
Implement the database using SQL Data definition with constraints
Date:
Aim:
To implement database using SQL Data definition with constraints
Procedure:
Do with pgAdmin application in your PostgreSQL
•
•
Launch pgAdmin 4.
•
Let’s create a table by right clicking on Tables and click Table…
Give your table a name and then click Columns
13
•
Click the + symbol to add columns
•
Name your column, select the data type, and give a length if needed. Then click Save
•
•
Now that you have created a table, view it under the Tables object. Right click and
refresh if it didn’t update.
14
•
Query Tool Example:
Note: I’m showing you my database with data for demonstration purposes
• When an object is selected under the database tree view menu, you can click the Tools
tab andclick Query Tool. Query tool brings up an editor to execute SQL statements.
• You can also right click the database and click Query Tool …
•
A tab called query editor will open up on the right. You can write SQL statements
and click the play button toexecute. Your results will show below the editor on the Data
Output tab.
15
CREATE TABLE products(product_no integer,name text,price numeric CHECK (price>0));
CREATE TABLE product0(product_no integer,name text,price numeric);
CREATE TABLE products0(products_no integer,name text,price numeric DEFAULT 9.99);
CREATE TABLE product(product_no integer NOT NULL,name text NOT NULL,price numeric);
CREATE TABLE product1(product_no integer UNIQUE,name text,price numeric);
CREATE TABLE product2(product_no integer UNIQUE NOT NULL,name text,price numeric);
CREATE TABLE example(a integer,b integer,c integer,PRIMARY KEY(a,c));
CREATE TABLE t1(a integer PRIMARY KEY,b integer,c integer,FOREIGN
KEY(b,c)REFERENCES example);
16
INSERT into products values(1,'Paste',75);
INSERT into products values(2,'Brush',20);
INSERT into products values(3,'pen',10);
INSERT into products values(4,'Pencil',05);
SELECT*from products;
ALTER TABLE products ADD COLUMN description text;
ALTER TABLE products DROP COLUMN description;
ALTER TABLE products ADD CONSTRAINT some_name UNIQUE(product_no);
ALTER TABLE products DROP CONSTRAINT some_name;
ALTER TABLE products ALTER COLUMN price SET DEFAULT 7.77;
ALTER TABLE products ALTER COLUMN price TYPE numeric(10,2);
ALTER TABLE products RENAME COLUMN product_no TO product_number;
ALTER TABLE products RENAME TO items;
17
Ex.No.: 4
QUERY THE DATABASE USING SQL MANIPULATION
Date:
Aim:
To query the database using SQL Data Manipulation commands
Procedure:
SQL Statements
Most of the actions you need to perform on a database are done with SQL statements.The
following SQL statement selects all the records in the "Customers" table:
SELECT * FROM Customers;
Semicolon after SQL Statements?
Some database systems require a semicolon at the end of each SQL statement.
Semicolon is the standard way to separate each SQL statement in database systems that
allow more than one SQLstatement to be executed in the same call to the server.
In this tutorial, we will use semicolon at the end of each SQL statement.Some of The Most
Important SQL Commands
•
•
•
•
•
•
•
•
•
•
•
SELECT - extracts data from a database
UPDATE - updates data in a database
DELETE - deletes data from a database
INSERT INTO - inserts new data into a database
CREATE DATABASE - creates a new database
ALTER DATABASE - modifies a database
CREATE TABLE - creates a new table
ALTER TABLE - modifies a table
DROP TABLE - deletes a table
CREATE INDEX - creates an index (search key)
DROP INDEX - deletes an index
CREATE TABLE products(no integer,name text,cost numeric);
INSERT into products values(2,'Paste',55);
INSERT into products values(3,'Soap',70);
INSERT into products values(4,'Shampoo',105);
18
SELECT*from products;
SELECT DISTINCT no from products;
SELECT DISTINCT name from products;
SELECT*from products where no=2;
19
SELECT no,name from products where no=1 and cost=20;
SELECT no,name from products where no=2 or cost=55;
SELECT no,name from products where not no=1;
SELECT no,name from products order by no desc;
SELECT no from products where no isnull;
20
SELECT no from products where no is not null;
update products set no=0 where cost=45;
delete from products where no=0;
SELECT min(no) from products where no=1;
SELECT max(cost) from products where no=1;
SELECT count(no) from products;
21
SELECT avg(cost) from products;
SELECT sum(no) from products;
SELECT no from products where no in(1,2);
SELECT *from products where cost not in(1,3);
SELECT *from products where cost between 40 and 80;
22
SELECT *from products where cost not between 40 and 80;
23
Ex.No.: 5
Date:
QUERYING / MANAGING THE DATABASE USING SQL
PROGRAMMING STORED PROCEDURES / FUNCTIONS,
CONSTRAINTS AND SECURITY USING
TRIGGERS
Aim:
To Querying/Managing the database using SQL Programming – Stored Procedures /
Functions – Constraints and security using Triggers
Procedure:
SQL Stored Procedures for SQL ServerWhat is a Stored Procedure?
A stored procedure is a prepared SQL code that you can save, so the code can be reused
over and over again.
So if you have an SQL query that you write over and over again, save it as a stored
procedure, and then just call itto execute it.
You can also pass parameters to a stored procedure, so that the stored procedure can act
based on the parametervalue(s) that is passed.
CREATE TABLE employee(ID int,first_name varchar(40) not null,last_name varchar(40)
not null,primary key(ID));
CREATE TABLE employee_audit(ID int,employee_id int not null,last_name
varchar(40)not null,changed_on timestamp(6) not null);
SELECT *FROM employee;
SELECT *FROM employee_audit;
24
CREATE OR REPLACE FUNCTION log_last_name_changes()
returns trigger
language PLPGSQL
as
$$
BEGIN
if NEW.last_name<>OLD.last_name then INSERT into
employee_audit(employee_id,last_name,changed_on)values(OLD.ID,OLD.last_name,NO
W());
END if;
return new;
END;
$$
CREATE trigger last_name_changes
before update
on employee
for each row
execute procedure log_last_name_changes();
INSERT into employee VALUES(101,'John','Doe');
INSERT into employee VALUES(102,'Lily','Bush');
SELECT *FROM employee;
UPDATE employee set last_name='Brown' WHERE ID=102;
25
SELECT *FROM employee;
SELECT *FROM employee_audit;
26
Ex.no: 6
DATABASE DESIGN USING NORMALIZATION
Date:
AIM:
Apply the database Normalization techniques for designing relational database tables to
minimize duplication of information like 1NF, 2NF, 3NF, BCNF and for creating
relationship betweenthe databases as tables using SQL commands.
PROCEDURE
Normalization is a database design technique which organizes tables in a manner that
reduces redundancy and dependency of data.
It divides larger tables to smaller tables and links them using relationships.
The inventor of the relational model Edgar Codd proposed the theory of normalization
with the introduction of First Normal Form, and he continued to extend theory with Second
and Third NormalForm. Later he joined with Raymond F. Boyce to develop the theory of
Boyce-Codd Normal Form.
Theory of Data Normalization in SQL is still being developed further. For example, there
are discussions even on 6thNormal Form. However, in most practical applications,
normalization achieves its best in 3rd Normal Form. The evolution of Normalization
theories is illustrated below-
Database Normalization Examples Assume a video library maintains a database of movies rented out. Without any
normalization, allinformation is stored in one table as shown below.
1NF (First Normal Form) Rules
• Each table cell should contain a single value.
• Each record needs to be unique.
The above table in 1NF1NF Example
27
Table 1: In 1NF Form
2NF (Second Normal Form) Rules
•
•
Rule 1- Be in 1NF
Rule 2- Single Column Primary Key
Table 1
Table 2
We have divided our 1NF table into two tables viz. Table 1 and Table2. Table 1 contains
memberinformation. Table 2 contains information on movies rented.
We have introduced a new column called Membership_id which is the primary key for
table 1.Records can be uniquely identified in Table 1 using membership id.
Database - Foreign Key
In Table 2, Membership_ID is the Foreign Key
3NF (Third Normal Form) Rules
28
• Rule 1- Be in 2NF
• Rule 2- Has no transitive functional dependencies
To move our 2NF table into 3NF, we again need to again divide our table.
3NF Example
Table 1
Table 2
Table 3
Boyce-Codd Normal Form (BCNF)
Even when a database is in 3rd Normal Form, still there would be anomalies resulted if it
has more than one Candidate Key.
Sometimes is BCNF is also referred as 3.5 Normal Form. 4NF (Fourth Normal Form)
Rules
5NF (Fifth Normal Form) Rules
A table is in 5th Normal Form only if it is in 4NF and it cannot be decomposed into any
number of smaller tables without loss of data.
6NF (Sixth Normal Form) Proposed
6th Normal Form is not standardized, yet however, it is being discussed by database experts
for sometime. Hopefully, we would have a clear & standardized definition for 6th Normal
Form in thenear future...
29
30
Ex. No.: 7
Date:
DEVELOPMENT OF DATABASE APPLICATIONS USING
NETBEANS
AIM
To develop a database application using NetBeans.
IMPLEMENTION
Creating Application using Netbeans
Step 1: click services > database > java DB > right click > create database. Thencreate
java DBdatabase box is popped.
Step 2: give database name > give user name as PECAI&DS > set password as
PECAI&DS > clickOK button.
The java DB database will start to process. Once the process is stopped, the javaDB will be
created.
Step 3: select the created one > right click > connect
31
Once you are connected, you can see the database list.
Step 4: select test > tables > create table > give table name
Step 5: click add column button > give name > select type > give size > then click OK
button
If you want more columns, you can repeat this step 5and add columns. Then the table will
be created.
Step 6: at the top corner, select project. In the empty space under project, right click.
32
Step 7: select new project > java > java application > click NEXT
Step 8: give project name > remove tick in create main class > click FINISH
So, the project will be created under the project menu.
Step 9: click the project you created. Under that, click source packages > defaultpackage
> new >java package> give package name > click finish.
33
The package will be created in the source package under your project.
Step 10: click the package created under source package > new > JFrame Form >
A new JFrame form window will be popped. Give class name and click finish.
Step 11: This window will be shown. Click panel (if you want you can
resize it). Then click properties and start doing designing your application.
34
35
36
37
Ex. No.:8
Date:
DATABASE DESIGN USING EER-TO-ODB
MAPPING / UML CLASS DIAGRAMS
AIM:
To create ER/ UML diagram of a database using MySQL workbench
PROCEDURE:
Step 1: First make sure you have a Database and Tables created on the MySQL
server.
For Example :Database - bank.
Tables - account, branch, customer, loan, trandetails
QUERYING/MANAGING THE DATABASE USING SQL PROGRAMMING
• STORED PROCEDURES/FUNCTIONS
• CONSTRAINTS AND SECURITY USING TRIGGERS
.
Step 2: Click on Database -> Reverse Engineer.
38
Step 3: Select your stored connection (for connecting to your MySQL Server in which
database is present) from the dropdown. Then click Next.
Step 4: After the execution gets completed successfully (connection to DBMS), click Next.
39
Step 5: Select your Database from the MySQL Server for which you want to create the ER
Diagram(in our case the database name is “bank”), then click Next.
Step 6: After the retrieval gets completed successfully for the selected Database, click
Next.
40
Step 7: Select the Tables of the Database which you want to be visible on the ER
Diagram (In thiscase I am importing all the tables of the DB), then click Execute>.
Step 8: After the Reverse Engineering Process gets completed successfully, click Next.
41
Step 9: Click Finish.
42
Ex. No.:9
USER-DEFINED TYPES IN SQLSERVER
Date:
AIM:
Creating datas using User-Defined Types (UDTs) in SQL server.
PROCEDURE:
You can access user-defined type (UDT) functionality in Microsoft SQL Server from the
Transact- SQL language by using regular query syntax. UDTs can be used in thedefinition
of database objects, as variables in Transact-SQL batches, in functions and stored
procedures, and as arguments in functions and stored procedures.
• Defining UDT Tables and Columns
Describes how to use Transact-SQL to create a UDT column in a table.
• Manipulating UDT Data
Describes how to use Transact-SQL to work with UDT data in SQL Server.
•
Defining UDT Tables and Columns
CREATING TABLES WITH UDTS
There is no special syntax for creating a UDT column in a table. You can use the
name of the UDT in a column definition as though it were one of the intrinsic SQL
Server data types. The following CREATE TABLE Transact-SQL statement creates a
table named Points, with a columnnamed ID, which is defined as an int identity
column and the primary key for the table. The second column is namedPointValue, with
a data type of Point. The schema name used in this exampleis dbo. Note that you must
have the necessary permissions to specify a schema name. If you omit the schema name,
the default schema for the database user is used.
CREATE TABLE dbo.Points
(ID int IDENTITY(1,1) PRIMARY KEY, PointValue Point)
• Manipulating UDT Data
• Inserting Data in a UDT Column
The following Transact-SQL statements insert three rows of sample data into the Points
table. The Point data type consists of X and Y integer values that are exposedas properties
of the UDT. You must use either the CAST or CONVERT function to cast the commadelimited X and Y values to the Point type. The first two statements use the CONVERT
function to convert a string value to the Point type, and the thirdstatement uses the CAST
function:
INSERT INTO dbo.Points (PointValue) VALUES (CONVERT(Point, '3,4')); INSERT
INTO dbo.Points(PointValue) VALUES (CONVERT(Point, '1,5'));INSERT
INTO dbo.Points (PointValue) VALUES (CAST ('1,99' AS Point));
43
SELECTING DATA
The following SELECT statement selects the binary value of the UDT.
SQLCopy
SELECT ID, PointValue FROM dbo.Points
To see the output displayed in a readable format, call the ToString method of
the Point UDT, which converts the value to its string representation.
SQLCopy
SELECT ID, PointValue.ToString() AS PointValue
FROM dbo.Points;
This produces the following results.
Copy
ID PointValue
1 3,4
2 1,5
3 1,99
You can also use the Transact-SQL CAST and CONVERT functions to achieve the same
results.
SQLCopy
SELECT ID, CAST(PointValue AS varchar)
FROM dbo.Points;
SELECT ID, CONVERT(varchar, PointValue)
FROM dbo.Points;
The Point UDT exposes its X and Y coordinates as properties, which you can then select
individually. The following Transact-SQL statement selects the X and Y coordinates
separately:
SQLCopy
SELECT ID, PointValue.X AS xVal, PointValue.Y AS yVal
FROM dbo.Points;
The X and Y properties return an integer value, which is displayed in the result set.
Copy
ID xVal yVal
1 3 4
2 1 5
3 1 99
44
WORKING WITH VARIABLES
You can work with variables using the DECLARE statement to assign a variable to a UDT
type. The following statements assign a value using the Transact-SQL SET statement and
display the results by calling the UDT's ToString method on the variable:
SQLCopy
DECLARE @PointValue Point;
SET @PointValue = (SELECT PointValue FROM dbo.Points
WHERE ID = 2);
SELECT @PointValue.ToString() AS PointValue;
The result set displays the variable value:
Copy
PointValue
-1,5
The following Transact-SQL statements achieve the same result using SELECT rather than
SET for the variable assignment:
SQLCopy
DECLARE @PointValue Point;
SELECT @PointValue = PointValue FROM dbo.Points
WHERE ID = 2;
SELECT @PointValue.ToString() AS PointValue;
The difference between using SELECT and SET for variable assignment is that SELECT
allows you to assign multiple variables in one SELECT statement, whereas the SET syntax
requires each variable assignment to have its own SET statement.
COMPARING DATA
You can use comparison operators to compare values in your UDT if you have set
the IsByteOrdered property to true when defining the class. For more information,
see Creating a User-Defined Type.
SQLCopy
SELECT ID, PointValue.ToString() AS Points
FROM dbo.Points
WHERE PointValue > CONVERT(Point, '2,2');
You can compare internal values of the UDT regardless of the IsByteOrdered setting if the
values themselves are comparable. The following Transact-SQL statement selects rows
where X is greater than Y:
SQLCopy
SELECT ID, PointValue.ToString() AS PointValue
45
FROM dbo.Points
WHERE PointValue.X < PointValue.Y;
You can also use comparison operators with variables, as shown in this query that searches
for a matching PointValue.
SQLCopy
DECLARE @ComparePoint Point;
SET @ComparePoint = CONVERT(Point, '3,4');
SELECT ID, PointValue.ToString() AS MatchingPoint
FROM dbo.Points
WHERE PointValue = @ComparePoint;
INVOKING UDT METHODS
You can also invoke methods that are defined in your UDT in Transact-SQL.
The Point class contains three methods, Distance, DistanceFrom, and DistanceFromXY.
For the code listings defining these three methods, see Coding User-Defined Types.
The following Transact-SQL statement calls the PointValue.Distance method:
SQLCopy
SELECT ID, PointValue.X AS [Point.X],
PointValue.Y AS [Point.Y],
PointValue.Distance() AS DistanceFromZero
FROM dbo.Points;
The results are displayed in the Distance column:
Copy
ID X Y Distance
1 3 4
5
2 1 5 5.09901951359278
3 1 99 99.0050503762308
The DistanceFrom method takes an argument of Point data type, and displays the distance
from the specified point to the PointValue:
SQLCopy
SELECT ID, PointValue.ToString() AS Pnt,
PointValue.DistanceFrom(CONVERT(Point, '1,99')) AS DistanceFromPoint
FROM dbo.Points;
The results display the results of the DistanceFrom method for each row in the table:
Copy
ID Pnt DistanceFromPoint
46
1 3,4 95.0210502993942
2 1,5
94
3 1,9
90
The DistanceFromXY method takes the points individually as arguments:
SQLCopy
SELECT ID, PointValue.X as X, PointValue.Y as Y,
PointValue.DistanceFromXY(1, 99) AS DistanceFromXY
FROM dbo.Points
The result set is the same as the DistanceFrom method.
UPDATING DATA IN A UDT COLUMN
To update data in a UDT column, use the Transact-SQL UPDATE statement. You can also
use a method of the UDT to update the state of the object. The following Transact-SQL
statement updates a single row in the table:
SQLCopy
UPDATE dbo.Points
SET PointValue = CAST('1,88' AS Point)
WHERE ID = 3
You can also update UDT elements separately. The following Transact-SQL statement
updates only the Y coordinate:
SQLCopy
UPDATE dbo.Points
SET PointValue.Y = 99
WHERE ID = 3
If the UDT has been defined with byte ordering set to true, Transact-SQL can evaluate the
UDT column in a WHERE clause.
SQLCopy
UPDATE dbo.Points
SET PointValue = '4,5'
WHERE PointValue = '3,4';
UPDATING LIMITATIONS
You cannot update multiple properties at once using Transact-SQL. For example, the
following UPDATE statement fails with an error because you cannot use the same column
name twice in one UPDATE statement.
SQLCopy
UPDATE dbo.Points
SET PointValue.X = 5, PointValue.Y = 99
WHERE ID = 3
47
To update each point individually, you would need to create a mutator method in the Point
UDT assembly. You can then invoke the mutator method to update the object in a TransactSQL UPDATE statement, as in the following:
SQLCopy
UPDATE dbo.Points
SET PointValue.SetXY(5, 99)
WHERE ID = 3
DELETING DATA IN A UDT COLUMN
To delete data in a UDT, use the Transact-SQL DELETE statement. The following
statement deletes all rows in the table that match the criteria specified in the WHERE
clause. If you omit the WHERE clause in a DELETE statement, all rows in the table will be
deleted.
SQLCopy
DELETE FROM dbo.Points
WHERE PointValue = CAST('1,99' AS Point)
Use the UPDATE statement if you want to remove the values in a UDT column while
leaving other row values intact. This example sets the PointValue to null.
SQLCopy
UPDATE dbo.Points
SET PointValue = null
WHERE ID = 2
48
Ex. No.:10
Date:
QUERYING THE OBJECT-RELATIONAL DATABASE
USING OBJECT QUERYLANGUAGE
AIM:
Querying object-relational database using object query language..
PROCEDURE:
OQL is ap powerful and easy-to-use SQL-like query language with special features dealing
with complex objects, values and methods
Example:
The following is the sample query:
“what are the names of the black product?” Firstly, create table and insert columns.
Then,
Select distinct p.name From products p Where p.color= ”black”
The above is valid for both SQL and OQL, but the results are different.
49
Download