0% found this document useful (0 votes)
15 views15 pages

SQL_Server_2008_ephrem

Uploaded by

masti1987
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views15 pages

SQL_Server_2008_ephrem

Uploaded by

masti1987
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Debre Markos University College of Technology Department of IT

Training manual for sql server 2008

April 2005 E.C


Debre Markos, Ethiopia

Microsoft Structured Query Language (SQL) server 2008 Training Manual 1


Debre Markos University College of Technology Department of IT

Contents
1. DDL (DATA DEFINITION LANGUAGE) _________________________________________________ 3

1.1. HOW TO CREATE A DATABASE __________________________________________________________ 3


1.2. RENAMEING A DATABASE _____________________________________________________________ 3
1.3. HOW TO CREATE TABLE _______________________________________________________________ 3
1.4. RENAMING A TABLE __________________________________________________________________ 4
1.5. TO SEE THE STRUCTURE OF THE CREATED TABLE ____________________________________________ 4
1.6. HOW TO ALTER/ MODIFY THE STRUCTURE OF THE TABLE _____________________________________ 5
1.6.1. To Drop a column _______________________________________________________________ 5
1.6.2. To Add a column ________________________________________________________________ 5
1.6.3. How to modify the data type of the column ____________________________________________ 5
1.7. TO DROP A TABLE ____________________________________________________________________ 5
1.8. TO TRUNCATE _______________________________________________________________________ 6

2. DML (DATA MANUPILATION LANGUAGE) ____________________________________________ 6

2.1. INSERT VALUES ______________________________________________________________________ 6


2.2. UPDATE VALUES IN A TABLE ___________________________________________________________ 6
2.3. DELETE A SINGLE ROW IN A TABLE_______________________________________________________ 7
2.4. CREATING SAVE POINT ________________________________________________________________ 7
2.5. ROLLBACK / RESTORING_______________________________________________________________ 7

3. DRL(DATA RETRIEVAL LANGUAGE ) __________________________________________________ 8

3.1. SELECT ____________________________________________________________________________ 8

4. SPECIAL ______________________________________________________________________________ 9

4.1. HOW TO ASSIGN OUR OWN NAME FOR THE COLUMNS IN THE DATABASE ________________________ 9
4.2. TRANSACT-SQL: LIKE ________________________________________________________________ 9
4.3. HOW TO USE GROUP BY ______________________________________________________________ 11
4.4. GETDATE () ________________________________________________________________________ 11
4.5. LEFT JOIN AND RIGHT JOIN ___________________________________________________________ 12
4.6. HOW TO CREATE VIEW _______________________________________________________________ 13
4.7. AVERAGE, MAXIMUM AND MINIMUM ___________________________________________________ 13
4.8. DISTINCT ________________________________________________________________________ 13
4.9. SELECT INTO _______________________________________________________________________ 14
4.10. TOP ______________________________________________________________________________ 14
4.11. HOW TO BACK UP A DATABASE ________________________________________________________ 14

Microsoft Structured Query Language (SQL) server 2008 Training Manual 2


Debre Markos University College of Technology Department of IT

1. DDl (Data Definition Language)


1.1. Create database
1.2. Rename a database
1.3. Creating table
1.4. Renaming table
1.5. To see the structure of the created table
1.6. Alter table
1.7. Drop table
1.8. Truncate table
1.1. How to Create a database
To create a database in SQL, use the following formula:

Syntax: CREATE DATABASE DatabaseName


Example :
create database RegistrarDB
use RegistrarDB

If you want the name of the database to be in different words, include them in square brackets.
Here is an example:

CREATE DATABASE [Registrar DB];

1.2. Renameing a database


To change the name of a database, Transact-SQL provides sp_renamedb. The formula used would
be:

EXEC sp_renamedb 'ExistingName', 'NewName';


The EXEC sp_renamedb expression is required.
The ExistingName factor is the name of the database that you want to rename.
The NewName factor is the name you want the database to have after renaming it.
Here is an example of renaming a database:
Example : EXEC sp_renamedb 'MyDatabase', 'MyDb';

1.3. How to create table


To create a table, you can follow this formula/syntax:

CREATE TABLE TableName (Column1, Column2, Column3)


Or:

CREATE TABLE TableName (


Column1,
Column2,
Column3);
Example :
use RegistrarDB

Microsoft Structured Query Language (SQL) server 2008 Training Manual 3


Debre Markos University College of Technology Department of IT

create table Studenttbl


(Sid varchar(20) primary key, Studname varchar(50) not null, StudCollege varchar(20) not
null, StudAge int not null, StudGender varchar(6) not null);

create table Coursetbl


(Ccode varchar(20) primary key, CTitle varchar(50) not null,
CCredit int not null);

create table CourseRegistrationtbl


(RegID varchar(20) primary key,
Sid varchar(20) foreign key references Studenttbl(Sid) ,
CCode varchar(20) foreign key references Coursetbl(Ccode),
RegDate datetime not null, StudYear varchar(10) not null,
StudSemister varchar(10) not null);

create table Resulttbl(ResultID int IDENTITY(1,1) primary key,


Sid varchar(20) foreign key references Studenttbl(Sid),
CCode varchar(20) foreign key references Coursetbl(Ccode),
LetterGrade varchar(10) not null );

create table StudStatustbl(StatusID int IDENTITY(1,1) primary key,


Sid varchar(20) foreign key references Studenttbl(Sid) ,
SGPA float not null,
CGPA float not null,
StudStatus varchar(20));

1.4. Renaming a table


To rename a table using code, execute the sp_rename stored procedure using the following
formula:
sp_rename ExistingTableName, TableNewName;
Here is an example:
sp_rename 'StaffMembers', 'Employees';
In this case, the interpreter would look for a table named StaffMembers in the current or selected database.
If it finds it, it would rename it Employees. If the table doesn't exist, you would receive an error.

1.5. To see the structure of the created table


To see the structure of the table once created the formula is
Sp_help TableName

Example :
use RegistrarDB
sp_help Resulttbl;

Microsoft Structured Query Language (SQL) server 2008 Training Manual 4


Debre Markos University College of Technology Department of IT

1.6. How to alter/ Modify the structure of the table


1.6.1. To Drop a column
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:
Example:
use RegistrarDB
alter table CourseRegistrationtbl drop RegID;
1.6.2. To Add a column
To add a new column to a table, follow this formula:

ALTER TABLE TableName


ADD ColumnName Properties;
Example1:
use RegistrarDB
alter table CourseRegistrationtbl add RegID int IDENTITY(1,1) primary key;
Example2:
use RegistrarDB
alter table Studenttbl
add StudDepartment varchar(50);

1.6.3. How to modify the data type of the column


To modify the data type for a column in a table we can us ethe following formula:
Alter table TableName
Alter column ColumnName DataType;
Example:
use RegistrarDB
alter table Coursetbl
alter column CTitle varchar(100);

1.7. To drop a table


To delete a table using SQL, use the following formula:

DROP TABLE TableName;


The DROP TABLE expression is required and it is followed by the name of the undesired
table. (since drop is DDl it canot be restored if once dropped)
Example :
use RegistrarDB
drop table employeetbl;

Microsoft Structured Query Language (SQL) server 2008 Training Manual 5


Debre Markos University College of Technology Department of IT

1.8. To truncate
The keyword truncate removes all values from the table once and cannot be rolled back.
The formula:
truncate table TableName;
example:
use RegistrarDB
truncate table StudStatustbl;

2. DML (Data Manupilation language)


1.1. Insert values
1.2. Update
1.3. Delete
1.4. Creating save point
1.5. Rollback
2.1. Insert values
 destination columns should match.
 if no value is given for a column, null will be taken by defualt
 else if that column has “not null” constraint, it returns error
The syntax to insert values within a table
INSERT INTO TableName
([column1],[column2],[column3],[column4],[column5],[column6])
VALUES
(<column1, DataType,>,< column1, DataType,>, < column1,
DataType,> ,< column1, DataType,> ,< column1, DataType,> ,< column1,
DataType,>)
Example:
use RegistrarDB
insert into Coursetbl values('c005','internet programming', 3);

Or
use RegistrarDB
INSERT INTO [Coursetbl]([Ccode],[CTitle],[CCredit])
VALUES(‘c005’,’internet programming’,’3’);

2.2. Update values in a table


To update a single field with in a table we can use the following syntax
Update TableName set ColumnName=’TheNewValue’
Where PrimaryKey=’TheValueOfThePrimaryKeyForThatColumn’;
Example:
use RegistrarDB
update Coursetbl set CTitle='computer organization and architecture'
where Ccode='c001';

Microsoft Structured Query Language (SQL) server 2008 Training Manual 6


Debre Markos University College of Technology Department of IT

2.3. Delete a single row in a table


Example:
use RegistrarDB
delete from Coursetbl
where Ccode='c001';
2.4. Creating save point
A user can set a savepoint, or marker, within a transaction. The savepoint defines a location to which
a transaction can return if part of the transaction is conditionally canceled. If a transaction is rolled
back to a savepoint, it must proceed to completion with more Transact-SQL statements if needed
and a COMMIT TRANSACTION statement, or it must be canceled altogether by rolling the
transaction back to its beginning. To cancel an entire transaction, use the form ROLLBACK
TRANSACTION transaction_name. All the statements or procedures of the transaction are undone.
Duplicate savepoint names are allowed in a transaction, but a ROLLBACK TRANSACTION
statement that specifies the savepoint name will only roll the transaction back to the most recent
SAVE TRANSACTION using that name.

Example :
use RegistrarDB
begin transaction
save transaction s1
delete from Coursetbl
where Ccode='c002';
2.5. Rollback / Restoring
ROLLBACK TRANSACTION without a savepoint_name or transaction_name rolls back to the
beginning of the transaction.
When nesting transactions, this same statement rolls back all inner transactions to the outermost
BEGIN TRANSACTION statement.
In both cases, ROLLBACK TRANSACTION decrements the @@TRANCOUNT system function to
0. ROLLBACK TRANSACTION savepoint_name does not decrement @@TRANCOUNT.
A transaction cannot be rolled back after a COMMIT TRANSACTION statement is executed,
except when the COMMIT TRANSACTION is associated with a nested transaction that is
contained within the transaction being rolled back.
In this instance, the nested transaction will also be rolled back, even if you have issued a
COMMIT TRANSACTION for it.
Within a transaction, duplicate savepoint names are allowed, but a ROLLBACK TRANSACTION
using the duplicate savepoint name rolls back only to the most recent SAVE TRANSACTION
using that savepoint name.
Example:
use RegistrarDB
begin transaction s1
rollback transaction

Microsoft Structured Query Language (SQL) server 2008 Training Manual 7


Debre Markos University College of Technology Department of IT

3. DRl(Data Retrieval Language )


3.1. Select
The SELECT operator can be used, among other things, to display a value. The SELECT keyword
uses the following syntax:
SELECT What;
Based on this, to use it, where it is needed, type SELECT followed by a number, a word, a string,
or an expression.
To display a sentence using SELECT, type it in single-quotes on the right side of this operator.
Here is an executed example

Use RegistrarDB
select * from Statussampleview;
select * from Resulttbl;
select * from CourseRegistrationtbl;
select *from Student_Backup;
select *from Coursetbl;
select *from StudStatustbl;
select Studenttbl.Studname,Studenttbl.StudDepartment,Resulttbl.LetterGrade from
Studenttbl,Resulttbl
where Resulttbl.Sid=Studenttbl.Sid;

Microsoft Structured Query Language (SQL) server 2008 Training Manual 8


Debre Markos University College of Technology Department of IT

4. Special
4.1. How to assign our own name for the columns in the database
Example:
use RegistrarDB
select Studname "Full Name",StudCollege "College",StudDepartment "Department" from
Studenttbl;

4.2. Transact-SQL: LIKE


The LIKE operator of Transact-SQL is used to with a wildcard (missing letters in the pattern) to specify a
pattern to select one or more records from a table or a view.
If you are visually creating the statement, in the Criteria section, in the box corresponding to
Filter for the column on which the condition would be applied, type the LIKE condition.
In Transact-SQL, the LIKE operator is used in a formula as follows:

Expression LIKE pattern;

The Expression factor is the expression that will be evaluated. This must be a clear and valid
expression.
The pattern factor can be a value to be found in Expression. For example, it can be the same type of
value used in a WHERE statement. In this case, the equality operator would be the same as LIKE.

If you want to match any character, in any combination, for any length, use the %wildcard. If you
precede it with a letter, as in S%, the condition would consist of finding any string that starts with
S.

Microsoft Structured Query Language (SQL) server 2008 Training Manual 9


Debre Markos University College of Technology Department of IT

Imagine that you want to get a list of students whose last names start with S. You would type the
condition as LIKE 'S%'.
If you set the letter in between (%letter%) with a letter, as in %S%, the condition would consist of
finding any string that contains S in the middle.
Example:
select StudName,StudAge from Studenttbl where Studname like 'm%'; // display sstudent name from
student table where student name starts with ‘m’
select StudName,StudAge from Studenttbl where Studname like '%m'; // display sstudent name from
student table where student name end with ‘m’
select StudName,StudAge from Studenttbl where Studname like '%m%'; // display sstudent name from
student table where student name has ‘m’ letter in between.
select StudName,StudAge from Studenttbl where Studname like '[G or g]%'; // displays student name
from student table where name strats with upper case or small case g.
select StudName,StudAge from Studenttbl where Studname like '_t%'; // displays student name from
student table where second letter name is t.
select StudName,StudAge from Studenttbl where Studname not like '_t%';

Example:
use RegistrarDB
select Studenttbl.Studname,
Studenttbl.StudCollege,
StudStatustbl.CGPA,
StudStatustbl.StudStatus
from Studenttbl,StudStatustbl where Studenttbl.Sid=StudStatustbl.Sid;
example:
use RegistrarDB
select studenttbl.sid from Studenttbl
where Studenttbl.StudCollege like '[T or t]%'
intersect
(select StudStatustbl.Sid from StudStatustbl)

Microsoft Structured Query Language (SQL) server 2008 Training Manual 10


Debre Markos University College of Technology Department of IT

Example:
Select studCollege, count(*) as NumOfStudInEachCollege
From Studenttbl
Group by StudCollege;

use RegistrarDB
select studenttbl.sid from Studenttbl
where Studenttbl.StudCollege like '[T or t]%'
union
(select StudStatustbl.Sid from StudStatustbl)

Example:
Select * from Studenttbl order by studAge desc;

4.3. How to use group by


Example:
use RegistrarDB
select StudCollege, count(*) from Studenttbl group by StudCollege;
4.4. getdate ()
example:
use RegistrarDB
select getdate() as Today; // to give specific name for the count column

Microsoft Structured Query Language (SQL) server 2008 Training Manual 11


Debre Markos University College of Technology Department of IT

4.5. Left join and Right join


Example:
Select studenttbl.studname, studStatustbl.studStatus
From studenttbl left join studStatustbl ON
Studenttbl.Sid=studstatustbl.sid;

The right join returns all the rows from the second table (student Status table). Even if there are no
matches in the first table (student table)
Example
use RegistrarDB
select Studenttbl.Studname,StudStatustbl.StudStatus
from Studenttbl left join StudStatustbl ON
Studenttbl.Sid=StudStatustbl.Sid

Example:
use RegistrarDB
select Studenttbl.Studname,StudStatustbl.StudStatus

Microsoft Structured Query Language (SQL) server 2008 Training Manual 12


Debre Markos University College of Technology Department of IT

from StudStatustbl right join Studenttbl ON


Studenttbl.Sid=StudStatustbl.Sid

4.6. How to create view


Example:
CREATE VIEW statusreport
AS
SELECT Sid AS Expr1 FROM Studenttbl;

4.7. Average, maximum and minimum


Example:
Select avg(studstatustbl.SGPA) as averageGrade,
MAX(studstatustbl.SPGA) as SemisterTop
Max(studstatus.CGPA) as YearTOP
From studstatustbl;

4.8. DISTINCT
Example
Select COUNT(DISTINCT studenttbl.studname) as ‘NO OF Students’
From studenttbl
Where studGender like ‘[m or M]%’;

Microsoft Structured Query Language (SQL) server 2008 Training Manual 13


Debre Markos University College of Technology Department of IT

4.9. Select into


use RegistrarDB
SELECT Studenttbl.Studname,
Studenttbl.StudCollege,
StudStatustbl.CGPA INTO Student_Backup
FROM StudStatustbl ,
Studenttbl where Studenttbl.Sid=StudStatustbl.Sid
and
Studenttbl.StudCollege like '[T or t ]%';

4.10. Top
Example ;
Select top 5 studname
From studenttbl;

4.11. How to back up a database


use RegistrarDB
backup database RegistrarDB
to disk ='C:\Users\Gate\Desktop\db\RegistrarDB.ldf';

Microsoft Structured Query Language (SQL) server 2008 Training Manual 14


Debre Markos University College of Technology Department of IT

Microsoft Structured Query Language (SQL) server 2008 Training Manual 15

You might also like