Top Banner
Data Base Lab Islamic University – Gaza Engineering Faculty Computer Department Lab -4- The Microsoft SQL Server Management Studio Part-2- By :Eng.Alaa I.Haniy.
21

Data Base Labsite.iugaza.edu.ps/ahaniya/files/Data-Base-Lab4.pdf · SQL Statement (DML, DDL) Most of the actions you need to perform on a database are done with SQL statements. SQL

Sep 21, 2020

Download

Documents

dariahiddleston
Welcome message from author
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
Page 1: Data Base Labsite.iugaza.edu.ps/ahaniya/files/Data-Base-Lab4.pdf · SQL Statement (DML, DDL) Most of the actions you need to perform on a database are done with SQL statements. SQL

Data Base Lab

Islamic University – Gaza Engineering Faculty Computer Department Lab -4-

The Microsoft SQL Server Management Studio Part-2-

By :Eng.Alaa I.Haniy.

Page 2: Data Base Labsite.iugaza.edu.ps/ahaniya/files/Data-Base-Lab4.pdf · SQL Statement (DML, DDL) Most of the actions you need to perform on a database are done with SQL statements. SQL

2

Creating New Database

You can create a new database using one of the following methods:

Method 1

Page 3: Data Base Labsite.iugaza.edu.ps/ahaniya/files/Data-Base-Lab4.pdf · SQL Statement (DML, DDL) Most of the actions you need to perform on a database are done with SQL statements. SQL

3

Write the database Name as shown then press OK. Now you can see that your created database is added

Method 2

Select a new query.

Using the following SQL statement you can create a new database.

Create Database Database_name;

From the menu you will find a drop down list that contains all the existed

Databases, select the master database.

To execute your command press the Execute button from the same menu.

After executing, refresh the databases by right click >> refresh to see your

Created one.

Page 4: Data Base Labsite.iugaza.edu.ps/ahaniya/files/Data-Base-Lab4.pdf · SQL Statement (DML, DDL) Most of the actions you need to perform on a database are done with SQL statements. SQL

4

SQL Statement (DML, DDL)

Most of the actions you need to perform on a database are done with SQL statements. SQL can be

divided into two parts: Data Manipulation Language (DML)

Data Definition Language (DDL).

The query and update commands form the DML part of SQL:

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

The DDL part of SQL permits database tables to be created or deleted. It also define indexes (keys),

specify links between tables, and impose constraints between tables. The most important DDL

statements in SQL are:

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

Page 5: Data Base Labsite.iugaza.edu.ps/ahaniya/files/Data-Base-Lab4.pdf · SQL Statement (DML, DDL) Most of the actions you need to perform on a database are done with SQL statements. SQL

5

Tables Fundamentals

Introduction

A table is primarily a list of items or a group of lists. To manage such a list, it

should be meticulously organized. To organize this information, it is divided in sections. Here is an example:

Based on this, a list is simply an arrangement of information and this information, also called data, is stored in tables.

Tables Names

A name will start with a letter. Examples are act or Second.

After the first character as an underscore or a letter, the name will have combinations of underscores, letters, and digits. Examples are _n24, act_52_t.

Unless stated otherwise, a name will not include special characters such as! @, #, $, %, ^, &, or *

If the name is a combination of words, each word will start in uppercase.

Examples are Staff Members or Video Titles.

Page 6: Data Base Labsite.iugaza.edu.ps/ahaniya/files/Data-Base-Lab4.pdf · SQL Statement (DML, DDL) Most of the actions you need to perform on a database are done with SQL statements. SQL

6

Tables Maintenance e

Creating a Table With SQL

To assist you with creating a table, you use a Data Definition Language (DDL) command that is CREATE TABLE, followed by a name. Therefore, to create a table,

you start with the following statement:

CREATE TABLE TableName;

The CREATE TABLE expression is required. The TableName factor specifies the name of the new table. The TableName can use the rules and suggestions we

reviewed for the tables.

After specifying the name of the table, you must create at least one category, called a column of data.

Renaming a Table

If you find out that the name of a table is not appropriate, you can change it. To change the name of a table in the SQL Server Management Studio, in the Object

Explorer, right-click the table and click Rename. Type the desired name and press Enter. To change the name of a table with code, execute sp_rename, followed by

the current name of the table, a comma, and the new desired name of the table. The formula to use is:

sp_rename ExistingTableName, TableNewName;

The names of tables should be included in single-quotes. Here is an example:

sp_rename N'StaffMembers', N'Employees';

Deleting a Table

If you have an undesired table in a database, you can remove it. To delete a table

in the SQL Server Management Studio, in the Object Explorer, right-click the table under its database node and click Delete. You will receive a warning giving you a

chance to confirm your intentions. If you still want to remove the table, click OK. To delete a table using SQL, use the following formula:

DROP TABLE TableName

Page 7: Data Base Labsite.iugaza.edu.ps/ahaniya/files/Data-Base-Lab4.pdf · SQL Statement (DML, DDL) Most of the actions you need to perform on a database are done with SQL statements. SQL

7

Columns Fundamentals

Referring to a Table

In those expressions, you may need to specify a particular table you want to use.

There are three main ways you can do this. To refer to, or to indicate, a table:

You can simply type its name. An example would be Students

You can type dbo, followed by the period operator, followed by the name of the

table.

An example would be dbo.Students

You can type the name of the database to which the table belongs, followed by

the period operator, followed by dbo, followed by the period operator, and followed by the name of the table. An example would be RedOakHighSchool.dbo.Students

Programmatic Creation of Columns

CREATE TABLE Country(Column1, Column2, Column3)

Alternatively, to make your statement easier to read, you should create each

column on its own line as follows: CREATE TABLE Country(

Column1,

Column2,

Column3);

There are two primary pieces of information you must specify for each column: its name and its type. Therefore, the syntax of creating a column is:

ColumnName DataType Options

Example

CREATE TABLE Customers (

DrvLicNbr nvarchar(32),

DateIssued DATE,

DateExpired date,

CustomerName nvarchar(50),

CustomerAddress NVARCHAR(120),

CustomerCity NvarChar(40),

CustomerState NVarChar(50),

Page 8: Data Base Labsite.iugaza.edu.ps/ahaniya/files/Data-Base-Lab4.pdf · SQL Statement (DML, DDL) Most of the actions you need to perform on a database are done with SQL statements. SQL

8

Columns Maintenance

CustomerPostalCode nvarchar(20),

HomePhone nvarchar(20),

OrganDonor BIT);

Referring to a Column

We will write many expressions that include the names of columns. In such

expressions, you will need to indicate the particular column you are referring to. There are various ways you can do this. To refer to, or to indicate, a table:

You must type the name of the table to which the column belongs, followed by the

period operator, followed by the name of the column. An example would be Employee.LastName.

You can type dbo, followed by the period operator, followed by the name of the table to which the column belongs, followed by the period operator, followed by the name of the column. An example would be dbo.Employee.LastName.

You can type the name of the database that owns the table's column, followed by

the period operator, followed by dbo, followed by the period operator, followed by the name of the table to which the column belongs, followed by the period operator, followed by the name of the column. An example would be

RedOakHighSchool.dbo.Employee.LastName.

Introduction

Column maintenance consists of reviewing or changing any of its aspects. This

includes reviewing the structure of columns of a table, renaming a column, deleting a column, changing the data type or the nullity of a column, etc.

Column Review

To see the structure of a table in the SQL Server Management Studio, in the Object Explorer, you can expand it:

Page 9: Data Base Labsite.iugaza.edu.ps/ahaniya/files/Data-Base-Lab4.pdf · SQL Statement (DML, DDL) Most of the actions you need to perform on a database are done with SQL statements. SQL

9

To view the columns of a table using SQL code, in a query window, execute

sp_columns followed by the name of the table the columns belong to. Here is an example:

This action displays the list of columns in the COLUMN_NAME column and other characteristics on the right columns.

The Properties of a Column

A column on a table controls what kind of data is appropriate for that particular

column. The characteristics that identify or describe such a table are defined as its properties. As we have seen previously, three primary properties are particularly

important and required for each column: the name, the data type, and the length. Besides these, some other properties can be used to further control the behavior of a particular field.

Page 10: Data Base Labsite.iugaza.edu.ps/ahaniya/files/Data-Base-Lab4.pdf · SQL Statement (DML, DDL) Most of the actions you need to perform on a database are done with SQL statements. SQL

01

Besides the name, data type and length of a column, you can control the columns of a table using the Columns property sheet in the lower section of the table in

Design View. These properties sometimes depend on the data type of the column. Therefore, to specify the properties of a column, you must first select it in the

upper section of the table. This selection can be done by just clicking the name, the data type, or the length of

the column. Then you can press F6 or click the first field in the lower section, select the desired property and type the necessary value:

Description

Description: Common and enabled for all fields, the description is used for a sentence that describes the column. You can type anything on that field.

Collation

Because different languages use different mechanisms in their alphabetic

characters, this can affect the way some sort algorithms or queries are performed on data, you can ask the database to apply a certain language mechanism to the field by changing the Collation property. Otherwise, you should accept the default

specified by the table.

Page 11: Data Base Labsite.iugaza.edu.ps/ahaniya/files/Data-Base-Lab4.pdf · SQL Statement (DML, DDL) Most of the actions you need to perform on a database are done with SQL statements. SQL

00

To specify the collation of a column when creating in, type COLLATE, followed by the desired collation code. Here is an example:

CREATE TABLE Customers(

FullName varchar(50) COLLATE SQL_Latin1_General_CP1_CI_AS

);

Modifying a Column

When making a change on a column, you are also said to alter the table. To support

this operation, SQL starts with the following formula: ALTER TABLE TableName

When using this statement, the ALTER TABLE expression is required and it is followed by the name of the table.

Adding a New Column

After a table has already been created, you can still add a new column to it. To add a new column in SQL Server Management Studio, first right-click the table and click

Design Table. To add a new column to the end of the table, click the first empty field under Column Name, type a name, and specify the other options.

To insert a new column between two existing one, right-click the column that will succeed it and click Insert Column:

This would create a new empty field. Type the desired name and specify the other

options.

Page 12: Data Base Labsite.iugaza.edu.ps/ahaniya/files/Data-Base-Lab4.pdf · SQL Statement (DML, DDL) Most of the actions you need to perform on a database are done with SQL statements. SQL

02

In SQL, the basic formula to add a new column to an existing table is:

ALTER TABLE TableName

ADD ColumnName Properties

The ColumnName factor is required. In fact, on the right side of the ADD keyword, define the column by its name and using all the options we reviewed for columns.

Here is an example:

ALTER TABLE StaffMembers

ADD Address nvarchar(100) NULL

GO

When this code is executed, a new column name Address, of type nvarchar, with a limit of 100 characters, and that allow empty entry, will be added to a table named

StaffMembers in the current database.

You can also use sample code to add a new column to a table. First display an empty query window and display the Templates Explorer. Expand the Table node. Under Table, drag Add Column and drop it in the query window. Delete the

undesired sections of code and keep only the part that deals with adding a column. Here is an example:

--

=====================================================================

=====

-- Add column template

--

-- This template creates a table, then it adds a new column to the

table.

--

=====================================================================

=====

USE <database, sysname, AdventureWorks>

GO

-- Add a new column to the table

ALTER TABLE <schema_name, sysname, dbo>.<table_name, sysname,

sample_table>

ADD <new_column_name, sysname, column3>

<new_column_datatype,, datetime>

<new_column_nullability,, NULL>

GO

Renaming a Column

If you find out that the name of a column is not appropriate, you can change it.

To rename a column in the Object Explorer, right-click the table that the column belongs to and click Modify. In the design view, highlight the name of the desired column to put it into edit mode and edit it.

Page 13: Data Base Labsite.iugaza.edu.ps/ahaniya/files/Data-Base-Lab4.pdf · SQL Statement (DML, DDL) Most of the actions you need to perform on a database are done with SQL statements. SQL

03

In SQL, to change the name of a column, first open an empty query window. In a

query window, execute sp_rename using the following formula:

sp_rename 'TableName.ColumnName', 'NewColumnName', N'COLUMN'

The sp_rename factor and the 'COLUMN' string are required. The TableName factor is the name of the table that the column belongs to. The ColumnName is the

current name of the column. The NewColumnName is the desired name you want to give to the column. Here is an example:

sp_rename N'StaffMembers.FullName', N'EmployeeName', N'COLUMN'

GO

When this code is executed, the interpreter will look for a column named FullName

in the StaffMembers table of the current or selected database. If it finds that column in the table, then it renames it EmployeeName.

Deleting a Column

If you have an undesired column that you don't want any more in a table, you can remove it. To visually delete a column, in the Object Explorer, expand the

database, the Tables, and the Columns nodes. Right-click the undesired column and click Delete. The Delete Object dialog box would display. If you still want to delete

the column, click OK. To change your mind, click Cancel. To delete a column using code, first open or access an empty query window, and

use the following formula: ALTER TABLE TableName

DROP COLUMN ColumnName

On the right side of the ALTER TABLE expression, type the name of the table.

On the right side of the DROP COLUMN expression, enter the name of the undesired column. Here is an example:

ALTER TABLE StaffMembers

DROP COLUMN CurrentResidence;

GO

When this code is executed, the interpreter will look for a column named CurrentResidence in a table StaffMembers of the current or selected database.

If it finds that column, it will remove it from the table.

Microsoft SQL Server can also generate sample code you can use to delete a column from a table. Before doing this, first display an empty query window and display the Templates Explorer. Expand the Table node. In the Table section, drag

Page 14: Data Base Labsite.iugaza.edu.ps/ahaniya/files/Data-Base-Lab4.pdf · SQL Statement (DML, DDL) Most of the actions you need to perform on a database are done with SQL statements. SQL

04

Records Fundamentals

Drop Column and drop it in the query window. Delete the undesired sections of code and keep only the part that deals with adding a column.

Here is an example:

--============================================

-- Drop column template

--

-- This template creates a table, then it

-- drops one of the columns of the table.

--============================================

USE <database, sysname, AdventureWorks>

GO

-- Drop a column from the table

ALTER TABLE <schema_name, sysname, dbo>.<table_name, sysname,

sample_table>

DROP COLUMN <new_column_name, sysname, column3>

GO

Introduction

A table is an object that holds the information of a database. Because a table is the

central part of a database, the information it holds must be meticulously organized. To better manage its information, data of a table is arranged in a series of fields called cells.

Programmatic Data Entry

The DDL command to perform data entry is INSERT combined with VALUES.

INSERT INTO TableName VALUES(Column1, Column2, Column_n)

The TableName factor must be a valid name of an existing table in the database

you are using. If the name is wrong, the SQL interpreter would simply consider that the table you are referring to doesn't exist. Consequently, you would receive an

error. The VALUES keyword indicates that you are ready to list the values of the

columns. The values of the columns must be included in parentheses.

If the column is a BIT data type; you must specify one of its values as 0 or 1.

If the column is a numeric type, you should pay attention to the number you type.

Page 15: Data Base Labsite.iugaza.edu.ps/ahaniya/files/Data-Base-Lab4.pdf · SQL Statement (DML, DDL) Most of the actions you need to perform on a database are done with SQL statements. SQL

05

If the column was configured to receive an integer (int, bigint, smallint), you should provide a valid natural number without the decimal separator.

If the column is for a decimal number (float, real, decimal, numeric), you can type the value with its character separator (the period for US English).

If the column was created for a date data type, make sure you provide a valid date.

Adjacent Data Entry

The most common technique of performing data entry requires that you know the sequence of fields of the table in which you want to enter data. With this

subsequent list in mind, enter the value of each field in its correct position. Example:

INSERT INTO Countries

VALUES(N'Mexico', 1972550, 107449525, N'Mexico City', N'mx');

(N'South Africa', 1219912, 44187637, N'Pretoria', N'za');

(N'Iraq', 0, 0, N'Baghdad', N'iq');

(N'United States', 9826630, 0, N'', N'');

(N'Saudi Arabia', 2149690, 0, N'Riyadh', N'');

To perform data entry in an order of your choice, you must provide your list of the

fields of the table. You can either use all columns or provide a list of the same columns but in your own order. In the same way, you don't have to provide data

for all fields, just those you want, in the order you want. Example:

INSERT Countries(Capital, [Internet Code], [Country Name])

VALUES(N'Nouakchott', N'mr', N'Mauritania')

Outputting the Insertion Result

In the techniques we have used so far, when or if the records have been added to a table, whether the operation was successful or not, we had no way of finding out. One way you can get this information is to store the inserted records in another

table. To support this, Transact-SQL provides the OUTPUT operator. The formula to use it is:

INSERT INTO TableName

OUTPUT INSERTED.Columns

VALUES(Value_1, Value_2, Value_X)

Example:

Page 16: Data Base Labsite.iugaza.edu.ps/ahaniya/files/Data-Base-Lab4.pdf · SQL Statement (DML, DDL) Most of the actions you need to perform on a database are done with SQL statements. SQL

06

Creating a SQL Expression

You can also create an expression in SQL expression you are using to create a

table. To do this, in the placeholder of the column, enter the name of the column, followed by AS, and followed by the desired expression. Here is an example:

CREATE TABLE Circle

(

CircleID int identity(1,1) NOT NULL,

Radius decimal(8, 3) NOT NULL,

Area AS Radius * Radius * PI()

);

Page 17: Data Base Labsite.iugaza.edu.ps/ahaniya/files/Data-Base-Lab4.pdf · SQL Statement (DML, DDL) Most of the actions you need to perform on a database are done with SQL statements. SQL

07

The Nullity of a Field

Introduction

During data entry, users of your database will face fields that expect data. Sometimes, for one reason or another, data will not be available for a particular

field. An example would be an MI (middle initial) field: some people have middle initial, some others either don't have it or would not (or cannot) provide it. This aspect can occur for any field of your table. Therefore, you should think of a way to

deal with it.

A field is referred to as null when no data entry has been made to it:

Saying that a field is null doesn't mean that it contains 0 because 0 is a value

Saying that a field is null doesn't mean that it is empty. A field being empty could mean that the user had deleted its content or that the field itself would not accept what the user was trying to enter into that field, but an empty field

can have a value.

A field is referred to as null if there is no way of determining the value of its content (in reality, the computer that is, the operating system, has its own internal mechanism of verifying the value of a field) or its value is simply unknown. As you

can imagine, it is not a good idea to have a null field in your table. As a database developer, it is your responsibility to always know with certainty the value held by

each field of your table. A field is referred to as required if the user must provide a value for it before

moving to another record. In other words, the field cannot be left empty during data entry.

To solve the problem of null and required fields, Microsoft SQL Server proposes one of two options: allow or not allow null values on a field. For a typical table, there

are pieces of information that the user should make sure to enter; otherwise, the data entry would not be validated. To make sure the user always fills out a certain

field before moving to the next field, that is, to require the value, if you are visually creating the table, clear the Allow Nulls check box for the field. On the other hand, if the value of a field is not particularly important, for example if you don't intend to

involve that value in an algebraic operation, check its Allow Nulls check box.

Page 18: Data Base Labsite.iugaza.edu.ps/ahaniya/files/Data-Base-Lab4.pdf · SQL Statement (DML, DDL) Most of the actions you need to perform on a database are done with SQL statements. SQL

08

NULL or NOTNULL

CREATE TABLE Persons

(

FirstName varchar(20) NULL,

LastName varchar(20) NOT NULL,

Gender smallint

);

After specify that a column would NOT allow NULL values, if the user tries creating a record but omits to create a value for the column, an error would display. Here is

an example:

Page 19: Data Base Labsite.iugaza.edu.ps/ahaniya/files/Data-Base-Lab4.pdf · SQL Statement (DML, DDL) Most of the actions you need to perform on a database are done with SQL statements. SQL

09

The Default Value of Column

Visually Creating a Default Value

You can create a default value of a column when creating a table. To specify the

default value of a column, in the top section, click the column. In the bottom section, click Default Value or Binding, type the desired value following the rules of

the column's data type:

Programmatically Creating a Default Value

To specify the default value in a SQL statement, when creating the column, after specifying the other pieces of information of the column, type DEFAULT followed by an empty space and followed by the desired value. Here are examples:

CREATE TABLE Employees

(

FullName VARCHAR(50),

Address VARCHAR(80),

City VARCHAR(40),

State VARCHAR(40) DEFAULT 'NSW',

PostalCode VARCHAR(4) DEFAULT '2000',

Country VARCHAR(20) DEFAULT 'Australia'

);

GO

Page 20: Data Base Labsite.iugaza.edu.ps/ahaniya/files/Data-Base-Lab4.pdf · SQL Statement (DML, DDL) Most of the actions you need to perform on a database are done with SQL statements. SQL

21

Identity Columns

The Uniqueness of Records

Visually Creating an Identity Column

After specifying the name of the column, set its data type to an integer-based type. Usually, the data type used is int. In the bottom section, click and expand the

Identity Specification property. The first action you should take is to set its (Is Identity) property from No to Yes.

Creating an Identity Column Using SQL If you are programmatically creating a column, to indicate that it would be used as

an identity column after its name and data type, type identity followed by parentheses. Between the parentheses, enter the seed value, followed by a comma, followed by the increment value. Here is an example:

CREATE TABLE StoreItems(

ItemID int IDENTITY(1, 1) NOT NULL,

Category varchar(50),

[Item Name] varchar(100) NOT NULL,

Size varchar(20),

[Unit Price] money);

Creating a Uniqueness Rule

To assist you with creating columns whose values will be distinguishable, Transact-SQL provides the UNIQUE operator. To apply it on a column, after the data type,

type UNIQUE. Here is an example: CREATE TABLE Students

(

StudentNumber int UNIQUE,

FirstName nvarchar(50),

LastName nvarchar(50) NOT NULL

);

GO

INSERT INTO Students

VALUES(24880, N'John', N'Scheels'),

(92846, N'Rénée', N'Almonds'),

Page 21: Data Base Labsite.iugaza.edu.ps/ahaniya/files/Data-Base-Lab4.pdf · SQL Statement (DML, DDL) Most of the actions you need to perform on a database are done with SQL statements. SQL

20

Collation

(47196, N'Peter', N'Sansen'),

(92846, N'Daly', N'Camara'),

(36904, N'Peter', N'Sansen');

GO

By the time the fourth record is entered, since it uses a student number that exists already, the database engine would produce an error:

Msg 2627, Level 14, State 1, Line 2

Violation of UNIQUE KEY constraint 'UQ__Students__DD81BF6C145C0A3F'.

Cannot insert duplicate key in object 'dbo.Students'.

The statement has been terminated.

Because different languages use different mechanisms in their alphabetic characters, this can affect the way some sort algorithms or queries are performed

on data, you can ask the database to apply a certain language mechanism to the field by changing the Collation property. Otherwise, you should accept the default

specified by the table. To find out what language your server is currently using, in a Query window or from

PowerShell, you can type:

SELECT @@LANGUAGE;