microsoft sql 2008 server in a day

93
www.ogutu.org MASTER SQL SERVER 2008 IN A DAY. Stephen Ogutu

Upload: xogutu

Post on 13-Apr-2015

42 views

Category:

Documents


1 download

DESCRIPTION

Just go a job interview for Microsoft SQL server and feeling a bit rusty? Or just want to learn Microsoft SQL server fast? This is the book for you.

TRANSCRIPT

Page 1: Microsoft SQL  2008 Server in a day

www.ogutu.org

MASTER SQL SERVER 2008 IN A DAY.

Stephen Ogutu

Page 2: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

2

Copyright

ALL RIGHTS RESERVED.

No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying,

recording or otherwise without the prior written permission of the copyright owner. This publication may not be lent, resold, hired or otherwise disposed of in anyway of trade

without the prior written consent of the copyright owner.

Page 3: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

3

Acknowledgment We gratefully acknowledge the help got from Microsoft website and the various user communities.

Page 4: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

4

Contents

CHAPTER 1 ................................................................................................................................................ 6

Installation ................................................................................................................................................... 7

Hardware requirements. ........................................................................................................................ 8

Release Notes ........................................................................................................................................ 9

System Configuration Checker. ........................................................................................................... 9

Feature selection .................................................................................................................................. 12

SQL Management Studio ........................................................................................................................ 21

Getting Started.......................................................................................................................................... 25

a. Master database ........................................................................................................................... 26

b. Model database ............................................................................................................................ 27

c. Tempdb database ........................................................................................................................ 28

d. The msdb database ..................................................................................................................... 28

Example I: Create a database called antony ...................................................................................... 28

Example 2. ................................................................................................................................................ 31

CHAPTER 2 .................................................................................................................................................. 36

SQL Server Login. ........................................................................................................................................ 37

Database Schemas. ..................................................................................................................................... 46

CHAPTER 3 .................................................................................................................................................. 51

DATABASE DESIGN ...................................................................................................................................... 52

Entity-Relationship Diagram. .................................................................................................................. 52

ONE-TO-MANY relationship. ................................................................................................................... 53

MANY-TO-MAY relationship. .................................................................................................................. 53

Page 5: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

5

EXAMPLE APPLICATION. ................................................................................................................. 54

CHAPTER 4 .................................................................................................................................................. 63

SELECT Statement. ................................................................................................................................. 64

Displaying everything from a table. ................................................................................................... 65

The WHERE clause. ................................................................................................................................ 67

Logical Operators. ....................................................................................................................................... 71

Table Joins. ............................................................................................................................................... 73

Joins. .......................................................................................................................................................... 73

Inner Joins. ............................................................................................................................................ 73

CHAPTER 5 .................................................................................................................................................. 79

Install Microsoft SQL Server 2008 R2 Report Builder 3.0 ........................................................................... 80

Introduction to Microsoft SQL Server 2008 R2 Report Builder 3.0................................................... 83

Page 6: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

6

CHAPTER 1

Introduction to SQL Server and SQL server management Studio.

OBJECTIVES.

After studying this chapter, you should be able to:

1. Install and configure SQL Server Express edition.

2. Install and configure Microsoft SQL Server Management Studio.

3. Differentiate between master, model, tempdb and msdb.

4. Create a database.

5. Configure database storage.

6. Create table in a database.

Page 7: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

7

Installation

After downloading the SQL Server Express edition, double click on

SQLEXPR32_x86_ENU to begin installation.

Under the Planning link, ensure that you understand the following.

Page 8: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

8

Hardware requirements.

According to http://msdn.microsoft.com/library/ms143506%28SQL.100%29.aspx we will

need a minimum of Windows XP SP2 Home, Pentium III-compatible processor or faster

with a minimum of 1.0 GHz processor to install.

Security Documentation

Visit http://msdn.microsoft.com/en-us/library/ms144228%28SQL.100%29.aspx to read

about the security consideration you should put in oplace before and after installing an

SQL server. They are:

1. Physical Security – The server should be physically secure and should be

accessible by only authorized personell. This should be in a data center with all

standard protection like theft, fire and floods. The database servers should not be

directly connected to the internet to avoid hacking. The database should be

backed up regularly.

2. You should secure your database server using firewalls.

3. Isolate Services – each SQL server Service should run under a separate

account. This reduces the risk of a compromised service affecting others. Also

the accounts should not be administrator but low rights accounts.

4. Disable NetBIOS and Server Message Block - Disable NetBIOS and Server Message Block. Servers in the perimeter network should have all unnecessary protocols disabled, including NetBIOS and server message block (SMB).

NetBIOS uses the following ports:

a. UDP/137 (NetBIOS name service) b. UDP/138 (NetBIOS datagram service) c. TCP/139 (NetBIOS session service)

SMB uses the following ports:

1. TCP/139 2. TCP/445

Web servers and Domain Name System (DNS) servers do not require NetBIOS

or SMB. On these servers, disable both protocols to reduce the threat of user

enumeration

Page 9: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

9

Release Notes

Please visit http://social.technet.microsoft.com/wiki/contents/articles/1486.microsoft-sql-

server-2008-sp2-release-notes.aspx to know what is new in service pack 2.

System Configuration Checker.

Click on the System Configuration checker to test if the installation of the SQL server

will be a success.

You should have a status of Passed.

Page 10: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

10

Next click on Installation and select the first option.

Under Setup support rules, click OK.

Under product key click next.

Page 11: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

11

Accept the licence and click next.

Under Setup support files, click on Install.

Page 12: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

12

Feature selection

Select the following:

1. The Database Engine - This is the core service for storing, processing, and

securing data.

2. SQL server replication – Used to copy data from once database to another and

then synchronizing them.

3. SQL client connectivity SDK – Tools used to communicate between client and

servers.

Instance Configuration.

There are two types of instances, a default instance and a named instance. The

default instance is called SQLExpress or MSSQLSERVER if installing the main

Page 13: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

13

installation of SQL server. Alternatively you can use the named instance where

you specify the instance name yourself. We will use named instance.

4. Under disk usage, click on next.

Page 14: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

14

5. Create a local user that will own the instance.

Page 15: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

15

6. Under server configuration, select this user as Microsoft recommends using a

separate user for each SQL service.

7. Under Account provisioning, you can either use :

a. Windows Authentication Mode which is the default. If you use this, then

SQL Server validates the account name and password using the Windows

principal token in the operating system. This is the most secure.

b. Mixed Mode (Windows Authentication or SQL Server Authentication) –

Here, you have to setup a password for the sa (System Administrator)

user in SQL server.

In our case, we will use Windows Authentication. Select Add and specify

the user we created previously as the SQL server administrator. You can

also add other users, both local and Domain users.

Page 16: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

16

8. Under data directories, specify the location of database directory, database log

directory, TEMP DB directory, TEMP Db log directory and backup directory. We

will discuss each of these in a later session.

Page 17: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

17

9. Enable file stream – file stream is used to manage unstructured data like word

documents. Instead of storing the document on the database as a blob, the data

is stored in the NT file system.

Page 18: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

18

10. Under Error and Usage settings, click next.

Page 19: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

19

11. Under Installation rules, click next.

12. Verify your selections and if you are satisfied, click on Install.

Page 20: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

20

13. The Installer will take a while.

Page 21: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

21

14. After a successful installation, you should have this screen.

SQL Management Studio

According to Wikipedia, the online encyclopedia, SQL Server Management

Studio (ssms) is a software application first launched with the Microsoft SQL

Server 2005 that is used for configuring, managing, and administering all

components within Microsoft SQL Server. The tool includes both script editors

and graphical tools which work with objects and features of the server.

A central feature of SQL Server Management Studio is the Object Explorer,

which allows the user to browse, select, and act upon any of the objects within

the server. It also has an "express" version that can be freely downloaded.

Download and double click on SQLManagementStudio_x86_ENU to begin

installation. Proceed with the same choices as we had done for SQLServer

Express installation. After accepting licence, select management tools basic.

Page 22: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

22

Select Next on Disk Usage summary.

Page 23: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

23

Under Error and Usage reporting, select Next.

Under Installation rules click Next.

Page 24: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

24

Click on install.

Once the installation is complete, you should get this.

Page 25: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

25

Getting Started.

Under Microsoft SQL Server 2008, select SQL Server Management Studio.

It will take a while to open as it will be configuring the environment for the first time use.

Select the server to connect to.

1. Under Server type, select “Database Engine”.

2. For Server name, select SQl server Authentication.

3. Under login, select windows authentication and click on connect.

Page 26: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

26

SQL server 2008 is a relational database management system and consists of the

following components which can be seen on the microsoft SQL server management

studio.

1. Databases – This is the location where we store the actual data. SQL server

2008 comes with four system databases installed by default.

a. Master database – This is like the meta data of your SQL server RDBMS.

It has information about login accounts and system configurations. It also

have information about all other databases. It should be backed up

regularly.

Page 27: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

27

b. Model database – This is the template upon which all other databases

created in the system are based. It must always exist in your installation

simply because every time you start SQL server, it will create tempdb and

the model will be required.

Page 28: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

28

c. Tempdb database - Is used to hold temporary objects like temporary

tables or stored procedures. Every time the SQL server is started, tempdb

is re-created. Tempdb is global and used by all users of the SQL server.

d. The msdb database – Used to schedule alerts and jobs.

Example I: Create a database called antony with the following properties.

Page 29: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

29

Click on New->Database. Under database name, enter antony.

Database name – antony.

Initial Database Size – 100MB.

Page 30: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

30

When full, Increment by – 50MB to a maximum size of 200MB.

Page 31: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

31

Your database should be created.

Example 2.

Create the table with the following data on the antony database above.

Steps:

1. Expand antony, right click on table and select new table.

Page 32: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

32

2. Enter the column names as shown.

3. Right click EMPLOYEE_ID and set it as the primary key.

Page 33: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

33

4. On the properties tab, under name select employees.

5. Your table is created, now Save the table.

6. Next insert the data. Right click on the table and select Edit top 200 rows.

Page 34: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

34

7. Type the data into the cells and press enter.

Page 35: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

35

REFERENCES.

1. www.microsoft.com

2. www.ogutu.org

Page 36: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

36

CHAPTER 2

SQL server security.

OBJECTIVES.

After studying this chapter, you should be able to:

1. Create logins and map them to database users.

2. Differentiate between login and users.

3. Work with database schemas.

Page 37: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

37

SQL Server Login.

Let us assume that you have just got a job as a system administrator of Shemma Global

LTD as the Database Administrator in charge of their CRM database. On your first day,

you have been requested to create accounts in the CRM database for the developers in

the billing department. Shemma global has the following two developers.

1. Stephen Mwangi

2. Antony Kariuki

The company has a policy of single sign on for developers which means once you login

to the computer, then you do not need to login to the database. Here are the steps you

would follow to create logins for the two developers.

STEPS:

1. The developers will first need to access the SQL server instance. For you to

access the sql server instance, you need a login name. There are two type of

logging in to SQL Server instance:

a. Windows authentication – With windows authentication, once you login

to the operating system, you do not need to specify a password for logging

in to the SQL server instance.

b. SQL server authentication – With SQL server authentication, you will

need a separate account created on the SQL server itself to allow you

login.

2. As per the policy of Shemma Global, we will use the Windows authentication.

Navigate to the windows operating system control panel and create the accounts

for the two developers.

a. Create the operating system user for Stephen Mwangi

Page 38: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

38

b. Create the operating system user for Antony Kariuki.

Now remember all we have done is create operating system users. We

cannot yet login to the SQL server instance until we map these operating

Page 39: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

39

system users to the respective SQL server Login. To do this, login to the

SQL server as a user with administrative privileges, expand the security

folder and click on New Login.

c. Under login name, select Windows authentication and click on search.

d. Under Advanced, search for the user s.mwangi we created previously.

Page 40: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

40

e. Click on Ok.

f. Do the same for the user a.kariuki.

Now that we have created the developers on the operating system and mapped then to

their logins in SQL server, let us logout and login as Antony Kariuki, then try and see if

we can access SQL Server.

Follow the following steps.

1. Logout of the operating system and login as user Antony Kariuki and start SQL

management studio.

Page 41: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

41

2. Under server type, select Database Engine. For the server name, select the SQL

server to connect to. For authentication, select Windows Authentication and click

connect.

3. You will be logged in to the SQL server.

Page 42: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

42

Try to connect to the CRM or the antony database we had created in chapter 1. You will

get this error!

This is because SQL server logins only enables you to login to the SQL server instance

but do not give you access to the database! We will repeat that because it is important,

SQL Server login allows you to login to the SQL server instance but do not give you

access to the SQL server database. If you want to access the SQL server database,

then you will need to create a database user and map it to the SQL server login. Hope

we are on the same page now. If not read this until you get it!

Next, we will need to create database users for our two developers and map them to the

logins we created.

Page 43: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

43

STEPS:

1. Expand the CRM database, select security and right click on users and select

new user.

2. Under username, enter kariuki and for login name enter a.kariuki.

Page 44: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

44

3. As the database administrator, you have been told that the two developers

should only be able to read data from the CRM database but they should not be

able to perform anything else like delete, insert, backup etc. To achieve this,

under database role membership, select db_datareader and click on OK.

4. Perform the same steps for the other developer and confirm that the users

Kariuki and Mwangi have been created.

Now that we have created the database login and mapped it to a database user, let us

try to access the CRM database again.

Page 45: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

45

Logout of the operating system and login as the user a.kariuki.

Try ro expand the CRM database. Since now your login is mapped to a user with

access to CRM database, you should be able to access it.

Page 46: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

46

When you try to create a table in the CRM database, you will get the error below since

the user a.kariuki was granted the read only privilege.

Database Schemas.

This is a good place to intoduce a third SQL server term, the schema. In other

databases like Oracle, the schema is synonymous with the database user in that the

database user and the schema own objects like tables. So in Oracle, when someone

talks about a schema, it refers to the same thing as a user. In SQL server 2008,

database users do not own database objects like tables. Rather, it is schema’s that own

objects.

If you expand the Tables folder under any database like under the antony database

above, you will note that the employees table is preceded by the word dbo. Dbo here is

the default schema name. Schemas can be owned by a user or a role but bear in mind

Page 47: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

47

that a schema can only be owned by one user at a time though a user can own many

schemas. So what are schemas and what are their uses?

The major advantage of using schemas is that objects are now independent of the

users that created them. If you want to delete a user for example, you do not need to

delete all the tables he created since the tables are owned by a schema. Schemas also

allow us to better manage database objects by giving us a location to group objects

together. For example, if our two developers created above were working on a project

for the HR department, we would create a schema called hr and this schema would own

all objects for that are related to this particular project. This grouping of objects

simplifies administration and security.

Example.

As the database administrator, you have been asked to create a schema that will be

used by the two developers who will be programming a new Payroll system for HR.

STEPS:

On the CRM database, select security and right click on schemas. Select New Schema.

Page 48: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

48

For schema name enter HR and for schema owner enter Kariuki. Click OK.

Now let us add the users who will access objects that are owned by this schema. Under

schemas, right click on HR and click on properties. Select the permissions page and

add all our developers. Since they will be developing, let us give them select, insert,

delete, update and execute privileges.

Page 49: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

49

Next let us grant Kariuki db_datawriter and db_ddladmin rights so that he will be able to

create a table. Do this by expanding CRM, go to security then users and right click on

Kariuki then select properties. Select db_datawriter and db_ddladmin and click on OK.

Logout and login as user Kariuki. Under CRM, right click on tables and select New

Table. Under properties, on schema, click on the drop down and select the HR schema

we created above.

For the table name, enter employees.

Page 50: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

50

Create the column empid and empname and save the table.

Your table employees is now owned by the schema HR.

You should now be able to organize your database objects using schemas.

Page 51: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

51

CHAPTER 3

Database Design

OBJECTIVES.

After studying this chapter, you should be able to:

1. Use Entity-Relationship Diagram (ERD).

2. Use Entities, Attributes & Keys.

3. Table relationships.

Page 52: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

52

DATABASE DESIGN

Entity-Relationship Diagram.

We normally use Entity-Relationship Diagrams (ER) to describe a database during the

design phase of the software life cycle. It gives us a visual representation of how the

relationships on the tables will appear. It also aids us in understanding the organizations

data needs. Tables in an ER diagram are represented by the diagram below. When

called upon to build any application for an organization, there is always an object that

we normally would wish to store information about in our application. For example, if

you are building a school management system, you would design your application such

that it stores information about students, teachers, classes etc. The object that you store

data about is called an entity type. A student is therefore an entity type. A teacher is

another entity type.

An entity therefore is an instance or occurrence of the type. Example, the student

Alexander is entity or an instance or occurrence of the type student. Therefore, entity is

anything about which data can be stored. If you are building a customer relationship

management system, an example of an entity can be customer, supplier etc. An entity is

represented as a rectangle.

We have said that an entity is anything that we can store data about. The data we store

about an entity is called an attribute. For example, one attribute we might want to store

about the entity customer is customer name. Another might be the address. An attribute

is represented as an oval. The diagram below shows the attribute supplier number for

the entity supplier.

CUSTOMER

SUPPLIER

SUPPLIER

SUPPLIER_NO

Page 53: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

53

Normally, there is always one attribute that is used to uniquely identify an entity. This

attribute is called a primary key. For example, supplier numbers are normally unique to

a supplier. Another example is the entity student, the attribute student number is unique

to it. If you are in Kenya, the entity person might have a unique attribute of identification

number since no two people share an id card.

RELATIONSHIPS.

In any application, entities will have some sort of a relationship. If you are building a HR

application, you might have the entity EMPLOYEE who belongs to the entity

DEPARTMENT. We see that there is a relationship between the EMPLOYEE and the

department. The relationship here is “employee belongs to a department”.

ONE-TO-MANY relationship.

This is the most common type of relationship. In our example above, we can see that an

employee, say Antony belongs to the department IT. The key point here is that Antony

is not the only employee in the department IT. There are other employees. Therefore,

we can visualize this as:

DEPARTMENT has MANY employees.

Remember that a department can have only one employee, but the important thing is

the opposite is not true. An employee cannot belong to two or more departments.

Antony cannot be in HR and also in IT. A relationship is normally achieved using the

primary key and a foreign key. In the DEPARTMENT entity, the primary key will be the

Department ID. In the EMPLOYEES entity, we will also include a Department ID but it

will be referred to as a foreign key. So the primary key is on the one side and the foreign

key is on the many side.

MANY-TO-MAY relationship.

Let us assume once more that we are building a school management system. We have

the entity STUDENT and the entity TEACHER. Now one student is taught by one or

more teachers and once teacher teaches one or more students.

DEPARTMENT

EMPLOYEES

STUDENT

TEACHER

Page 54: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

54

Now ideally we are supposed to model a many-to-may relationship as shown above but

this is not allowed in an ER model. What we are supposed to do is to split the

relationship into to one to many relationships and introduce a junction-entity to link

them. The many side should point to the junction entity.

The STUDENT entity will have a primary key which will become a foreign key in the

STUDENTTABLE entity. The TEACHER entity will have a primary key which will

become a foreign key in the STUDENTTABLE entity.

EXAMPLE APPLICATION.

You are a developer for Shemma Global LTD and you have been tasked with creating a

school managemet application for a client. Before you begin coding, the management

would like to review your ER diagrams for approval. Design the database and forward it

to management.

SAMPLE SOLUTION.

1. First list all entities that you can think of in a school. Since this is an example, we

can list three. They are:

a. STUDENT.

b. TEACHER.

c. COURSE.

2. For every entity, think of attributes that defines it. This is the information we will

store about the entity. For sake of clarity, let us list only three attributes for every

entity.

a. STUDENT

i. Student ID.

ii. Name.

TEACHER

STUDENTTEACHER

STUDENT

Page 55: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

55

iii. Gender.

b. TEACHER.

i. Teacher ID

ii. Name

iii. Gender

c. COURSE

i. Course ID

ii. Name

iii. Type

3. Next draw the relation between the entities using an ER diagram.

There is a MANY-to-MANY relationship between STUDENT and TEACHER.

Now one student is taught by one or more teachers and one teacher teaches one

or more students. Because we are not allowed to show a MANY-to-MANY

COURSE

STUDENTCOURSE

TEACHER

STUDENTTEACHER

STUDENT

Page 56: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

56

relationship directly, we have included a junction entity STUDENTTEACHER to

take care of this. Similarly, the relationship between STUDENT and COURSE is

MANY-to-MANY. Note that there is a relationship between TEACHER and

COURSE but because of simplicity, we have not shown it here.

4. Assuming that the management approves your design, you need to create the

tables on your SQL Server database. Follow these steps.

a. Login to SQL server database and create the database called SCHOOL.

The database should be owned by the user Antony Kariuki we created in

chapter 2. It should have an initial size of 100MB and should grow by

50MB up to a maximum of 200MB.

b. Under the database SCHOOL create the table STUDENT with the

following columns.

i. Student_id (Primary key)

ii. Name (100 characters)

iii. Gender (6 characters)

Page 57: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

57

c. Under the database SCHOOL create the table TEACHER with the

following columns

i. Teacher_ID (Primary key)

ii. Name (100 characters)

iii. Gender (6 characters)

d. Under the database SCHOOL create the table COURSE with the following

columns

i. Course_ID (primary Key)

ii. Name (100 characters)

iii. Type (100 Characters)

e. Next create the table STUDENTTEACHER with the following columns.

i. Student_teacher_ID (primary key)

ii. Student_ID (Foreign key to the column Student_ID in the table

STUDENT)

Page 58: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

58

iii. Teacher_ID (Foreign key to the column Teacher_ID in the table

TEACHER)

f. Lastly create the table STUDENTCOURSE with the following columns.

i. Student_course_ID (Primary key).

ii. Student_ID (Foreign key to the column Student_ID in the table

STUDENT)

iii. Course_ID (Foreign key to the column Course_ID in the table

COURSE)

Page 59: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

59

We are done creating the tables for our school management system. We now need to

create the relationships between the tables using the primary and foreign keys. Follow

these steps.

1. Right click on Database Diagrams under the database SCHOOL.

2. When you click on new database diagram, you will get the below dialog. Click on

Yes.

Page 60: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

60

3. Press CTRL key and click on all tables and click ok ADD.

4. Let us create a relationship between STUDENT and TEACHER. We will use the

junction table STUDENTTEACHER to link the two as shown below.

Drag the column student_id from the table STUDENT and drop it to the column

student_id in the table STUDENTTEACHER. A dialog box will come up. Leave

the relationship name as it is and click on OK.

TEACHER

STUDENTTEACHER

STUDENT

Page 61: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

61

Do the same for STUDENTTEACHER and TEACHER tables.

You will notice that the relationship between STUDENT and

STUDENTTEACHER. The key icon means one and the infinity icon means

many. So the relation between STUDENT and STUDENTTEACHER is one to

many.

5. Finish all the other relationship between STUDENT and COURSE.

Page 62: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

62

6. Save the relationship with the name school.

7. The relationship will be saved under Database Diagrams.

Page 63: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

63

CHAPTER 4

SELECT Statement

OBJECTIVES.

After studying this chapter, you should be able to:

1. Select from single table.

2. Use the where clause.

3. Join tables.

Page 64: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

64

SELECT Statement.

SELECT statement returns a result from one or more tables. It is the used to query the

contents of tables and views. Before we can use the select statement to query data

from tables, let us insert some data into the tables we created previously using SQl

management Studio.

STEPS.

Right click on STUDENT and select edit top 200 rows.

Assuming that our school has a policy of 10 students per class, enter the following data

in the table STUDENT.

Next on the tool bar, select New Query.

Page 65: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

65

This will open the query editor from where you can run your SQL statements.

Displaying everything from a table.

To display the entire contents of a table, use the statement below.

SELECT * from <database>.<schema>.<table>;

Where:

<database> is the name of the database, in our case SCHOOL.

<schema> is the name of the schema, in our case dbo.

<table> is the name of the table, in our case STUDENT.

So the statement should be:

Select * from SCHOOL.dbo.STUDENT;

The character * means all columns in the table, so this will display all the columns in the

table. Let us give it a try. Type

Page 66: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

66

Sometimes you are not interested in displaying all the columns in a table, perhaps you

only want to display the student name and gender. To do this, instead of using the

character * which means all columns replace it with a comma separated list of column

names e.g.

Select name, gender from SCHOOL.dbo.STUDENT;

This will display the names and gender of all students in the table STUDENT.

Now assume we had millions of records in the table student, how long will it take to

display all records? This depend s on the server resources but it takes really long in

some cases! And mostly, we do not need to see all the records in a table anyway. We

normally just want to see a subset of the data. For example if the Principal of your

school would like to know how many female students he has in the school, it would not

be prudent to display all the students and then start counting how many are female

using a pen or a finger from the screen. This is the use of the where clause.

Page 67: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

67

The WHERE clause.

The where clause is used to restrict the amount of rows that are to be returned based

on a certain criteria. Example:

Display how many female students are in the school.

The criteria here is to display only female students. The first thing is to check for the

column where we store gender as this is what will be used in the where clause. The

statement therefore will be:

Select * from SCHOOL.dbo.STDENT where gender=’female’;

Since female is a string, we have to enclose it in quotes.

This will display only female students.

Another example would be to display students whose id numbers are greater than 4.

Greater than symbol is > while less than symbol is <.

Page 68: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

68

Notice that for integer values, we do not use quotes.

EXAMPLE.

Create a report that shows the male students whose id numbers are greater than or

equal to 4 but not more than 7.

STEPS:

Here we see that there are several criteria to be used.

1. The students must be male.

2. The student ID number must be greater than or equal to 4.

3. The student ID must be less than or equal to 7.

To achieve this we have to combine all these criteria in a single statement as shown.

Select * from SCHOOL.dbo.STUDENT where gender=’male’ and student_id>=4 and

student_id<=7;

Other operators you can use are:

1. = This is the equal operator. We can use this to check students whose id number

is equal to a certain value.

Page 69: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

69

2. <> This is the not equal to operator. We can use this to check for students who

are not male.

Another way to use the not equal to is to use the symbol !=.

3. > Is the greater than symbol. Example, display all students whose id number is

greater than 7.

Note that 7 itself is not included in the resultset.

4. >= Is the greater than or equal to symbol.

5. < is the less than symbol.

Page 70: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

70

6. <= is the less than or equal to.

7. !> is the not greater than symbol. For example, display students whose id

number is not greater than 7.

8. !< is the not less than symbol. For example, display students whose id numbers

is not less than 3.

Page 71: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

71

Logical Operators.

Logical operators are used to test for truth in a certain expression.

The AND operator.

The AND operator returns true if both expressions are true. Let us assume that the

Principal of your school wants to know how many female students have id numbers

greater than 5, how would you produce the report? We will notice that there are two

expressions here.

The student must be female.

This expression will be gender=’female’.

The student must have an ID number greater than 5.

This expression will be student_id>5. Therefore the entire expression will be true if both

the expression in gender=’female’ is true and student_id>5 is true. If only one part of

the expression is true, the entire expression becomes false.

The OR operator is similar to the AND operator except that it returns true if either of the

expressions is true. Example, change the report to display how many students are

female or have id numbers greater than 5. The two expressions are.

The student should be a female or the student should have an id number greater than 5.

Page 72: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

72

Notice that the result returns male students also.

Other logical operators are ALL, ANY, BETWEEN, EXISTS, IN, LIKE, NOT, OR, SOME.

Investigate them at your own free time.

Page 73: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

73

Table Joins.

It is very rare that you will be creating reports from a single table. Most of the data will

be in several tables and you will need to combine them using foreign keys as we had

seen in the previous chapter. Insert the following data in the tables TEACHER and

STUDENTTEACHER.

TEACHER.

STUDENTTEACHER.

Joins.

An SQL join is used to combine fields from two tables using values that are common to

the tables.

Inner Joins.

An inner join used comparison operators to compare columns. It is the most commonly

used join. As an example, we can write the following report to show all students that

are taught by the teacher Peter Musila.

Page 74: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

74

To better answer this, remember from our diagram that we need to combine three

tables. First we combine the table STUDENT and STUDENTTEACHER then we

combine the table STUDENTTEACHER with TEACHER. We will be combining them

using the primary key/ foreign key pair.

Here are the steps.

1. Select the columns you want to display on the report from the tables.

a. We need to display the student name form table STUDENT. We will need

the column school.dbo.student.name.

b. We need to display the teacher name from the table TEACHER. We will

need the column school.dbo.teacher.name.

2. Let us see how the query looks thus far.

select school.dbo.student.name, school.dbo.teacher.name from

school.dbo.student, school.dbo.teacher, school.dbo.studentteacher;

TEACHER

STUDENTTEACHER

STUDENT

Page 75: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

75

There are several problems with this query.

a. The table names are too long. Instead of using the entire table name, we

can give it an alias or shorter name as shown below.

select st.name, tr.name from school.dbo.student st, school.dbo.teacher tr,

school.dbo.studentteacher str;

Inn the list of tables, after every tablename put a short text which will be

used instead of the tablename e.g. school.dbo.student now becomes st,

school.dbo.teacher becomes tr and school.dbo.studentteacher becomes

str. The field names are now more readable. Instead of using

school.dbo.student.name we now use st.name.

Let us give it a spin.

The second problem persists; it returns 270 rows though we only have 10

students. This is called a cross join because we have not specified the

join. The next thing we need to do is join the tables.

Page 76: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

76

b. Let us start with the join between STUDENT and STUDENTTEACHER.

In the STUDENT table, the primary key is student_id, in the

STUDENT_TEACHER table, the foreign key is student_id so we join the

two tables using the id student_id as shown below.

The query now returns 30 rows. There is still repetition as you can see in

the above diagram since each name is returned 4 times.

c. We need to join the table STUDENTTEACHER and TEACHER to finish

the join. The table STUDENTTEACHER has the foreign key teacher_id

and the table TEACHER has the primary key teacher_id. We therefore link

them on the column teacher_id.

TEACHER

STUDENTTEACHER

STUDENT

Page 77: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

77

A small problem remains, both the columns are named “name” and we do

not know which is student name and which is the name of the teacher. To

fix the problem, put an alias after the column name as you did for the

table.

d. Finally we need to select students taught by teacher Peter Musila. Peter

Musila’s id is 1 so we include this in the query.

Page 78: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

78

Other joins exist like outer joins, left outer join, right outer join,full outer join

e.tc but since they are not as commonly used as the inner join, we will not

discuss them.

Page 79: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

79

CHAPTER 5

Report sever

OBJECTIVES.

After studying this chapter, you should be able to:

1. Install Microsoft SQL Server 2008 R2 Report Builder 3.0

2. Create reports using table or matrix wizard.

3. Join tables.

Page 80: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

80

Install Microsoft SQL Server 2008 R2 Report Builder 3.0

Download Microsoft SQL Server 2008 R2 Report Builder 3.0 from the URL

http://www.microsoft.com/en-us/download/details.aspx?id=6116 and save it in your local

computer. Note that before you start installation, you will need Microsoft .NET

Framework version 3.5 SP1 if it is not already installed in your computer.

INSTALLATION STEPS.

1. Double click on ReportBuilder3.msi to begin installation. On the Welcome screen,

click next.

2. Accept the license.

Page 81: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

81

3. Enter the registration information.

4. Select the Microsoft SQL Server Report Builder 3.0.

Page 82: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

82

5. For the default target server, leave it blank.

6. Click install to begin installation.

Page 83: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

83

Introduction to Microsoft SQL Server 2008 R2 Report Builder 3.0

The Microsoft SQL Server 2008 R2 Report Builder 3.0 (Report Builder) is a component

of the SQLServer reporting services (SSRS) and is used as an end user tool for

creating reports. SSRS have other components like Report Manager, Report Server,

database, report designer and data sources which are briefly described below.

REPORT SERVER.

This is the core engine

for reporting

Report Server

Database

This is the metadata

about the reports.

Report Manager

The administrative

interface for reporting

services

Report Builder

Tool for building reports.

Used by business users.

Data Sources

This is the source of the

report data.

Page 84: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

84

In this section, we will see how to create reports using the report builder.

STEPS.

1. Under new report, select Table or Matrix wizard.

2. Select create dataset.

Page 85: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

85

3. Under name, enter SchoolConn and select use connection embedded in my report.

4. For connection type, select “Microsoft SQL Server” and click on Build.

5. For Server name, enter your full server name in the format hostname\SQL Server

6. Select Use Windows Authentication.

7. Select SCHOOL as the database.

Page 86: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

86

8. Click on Test Connection. This should succeed.

Page 87: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

87

9. Click on OK to create the data source.

10. Under Design Query, select the tables STUDENT, STUDENTTEACHER and TEACHER.

11. Click on autodetect, this will automatically detect the relationship between the tables.

Page 88: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

88

12. Under Arrange fields, populate data as shown and click on Next.

13. Under layout, select “Show subtotals and grand totals” and “Expand /Collapse Groups” then

click next.

Page 89: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

89

14. For style, select Ocean. Click on Run to test your report by expanding all buttons.

Page 90: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

90

15. The report has data but the headings are not very descriptive. Click on Design and make the

following changes.

a. For the heading, enter “Teacher Student Ratio”. Resize the report as shown below.

b. Click on Run to test the report again.

This report shows that.

i. There are both male and female teachers in the school.

ii. The female teachers name is Ann Aoko.

iii. The teacher Ann teaches both male and female students.

iv. The total number of female students taught by Ann is one, Shallin Awino.

v. The teacher Ann also teaches two male students, George Owino and Mathew

Mwangi.

Page 91: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

91

vi. The total number of students taught by Ann is three.

vii. The male teacher Peter Musila teaches one female student Pricilla Otieno.

viii. Peter Musila also teaches two male students Antony Mwangi and John Otieno.

ix. The total number of students taught by both teachers is six.

c. Now save the report. It will be saved with the .rdl extension.

d. One nice thing about the report builder is that it allows you to export the report in

various formats such as XML, CSV, TIFF, MHTML, WORD and EXCEL which you can then

send to the management as an email attachment.

e. STEPS.

i. Click on page setup and select landscape.

ii. Click on export and select excel.

Page 92: Microsoft SQL  2008 Server in a day

[MASTER SQL SERVER 2008] www.ogutu.org

92

iii. Save your report as TeacherStudentRatio.xls. You can then send this report to

management.

Page 93: Microsoft SQL  2008 Server in a day

Most IT books are theory based and takes the reader through acres and acres of text

to explain a simple principle. Our approach is to help the reader get on his feet fast

then allow him/her to continue the learning on his own.

[MASTER SQL SERVER 2008] www.ogutu.org

About the author.

Stephen Ogutu is a

Administrator

creativity and enjoys experimenting

with various technologies.

He has vast experience in business

intelligence

particularly oracle and Unix operating

systems.

Follow his daily findings on Twitter at

@xogutu.

him a line at [email protected].

Most IT books are theory based and takes the reader through acres and acres of text

to explain a simple principle. Our approach is to help the reader get on his feet fast

then allow him/her to continue the learning on his own.

www.ogutu.org

93

About the author.

Stephen Ogutu is an experienced IT

Administrator who has a love for

creativity and enjoys experimenting

with various technologies.

He has vast experience in business

intelligence technologies, databases

particularly oracle and Unix operating

systems.

Follow his daily findings on Twitter at

@xogutu. If you have a question, drop

him a line at [email protected].