Download 4. Createa Small Database using MS SQL Server Management Studio

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Oracle Database wikipedia , lookup

DBase wikipedia , lookup

Tandem Computers wikipedia , lookup

Microsoft Access wikipedia , lookup

Database wikipedia , lookup

Microsoft Jet Database Engine wikipedia , lookup

Entity–attribute–value model wikipedia , lookup

Ingres (database) wikipedia , lookup

Extensible Storage Engine wikipedia , lookup

Clusterpoint wikipedia , lookup

Open Database Connectivity wikipedia , lookup

Relational model wikipedia , lookup

Microsoft SQL Server wikipedia , lookup

Database model wikipedia , lookup

SQL wikipedia , lookup

PL/SQL wikipedia , lookup

Transcript
CIS 2109 First SQL Server Lab
Creating Tables & Relationships, Loading Data
Inserting, Updating, and Deleting Records
TABLE OF CONTENTS
1. Objectives ...................................................................................................................................................................................... 2
2. Introduction .................................................................................................................................................................................... 2
3. Start MS SQL Server and Connect to a Database ......................................................................................................................... 3
4. Create a Small Database using MS SQL Server Management Studio ........................................................................................... 4
4.1. Create Tables using Management Studio (Customers and Orders tables) ............................................................................. 6
4.2. Create Index using Management Studio (on the Customers table) ....................................................................................... 8
4.3. Create ER Diagram and Create Relationship (between Customers & Orders tables) ........................................................... 11
5. Create Tables (Order_Line & Products) using SQL Commands, Update ER-D............................................................................. 14
6. Modify table Definitions Using SQL (Add Fields to Customer Table) ...................................................................................... 17
7. Inserting, Updating, and Deleting Data ........................................................................................................................................ 18
7.1. Insert Data and Run Queries using Management Studio ...................................................................................................... 18
7.2. Insert Data with SQL INSERT Statements .............................................................................................................................. 19
7.3. Backup Tables Using SQL Commands (INSERT INTO, DROP TABLES) .................................................................................... 20
7.4. SQL UPDATE commands ....................................................................................................................................................... 21
7.5. SQL Delete (Deletes Records but not Table Structure) ......................................................................................................... 21
8. Loading a Database with Data .................................................................................................................................................... 22
8.1. Import database from MSAccess .......................................................................................................................................... 22
8.2 Load Database using SQL Script ............................................................................................................................................ 24
9. Homework Submission ............................................................................................................................................................... 26
Good reference for SQL syntax and examples: http://www.w3schools.com/sql
1
1. OBJECTIVES
In this lab, you will be
Getting started with Microsoft SQL Server
Creating tables, relationships, and ER Diagrams using Microsoft SQL Server Management Studio
Entering data and running Queries using Management Studio
Creating tables and relationships using SQL DDL commands (using a SQL Query Window)
Inserting, updating, and deleting data with SQL commands (using a SQL Query Window)
Importing a database
Creating a database (tables, relationships, and data) by using SQL scripts
As you go through these instructions, you will be asked to copy and paste various things into a word document. You
may want to go to section 9 now (“Homework Submission”) to get a list of the items you’ll be submitting and paste this
list into a Word document (for later submission to the TA). Then as you encounter items that you need to copy, you’ll
have a place to put them. 
2. INTRODUCTION
In the previous labs we used Access as the database management system (DBMS) for managing relational databases. In
this Lab you will work with a different relational DBMS - Microsoft SQL Server. The lab is based on the SQL lecture
material and will enable you to practice with SQL commands. Note, as you create and execute the SQL statements, try
also to focus on the database design and the practical use of the statements.
The system configuration we use in this lab is based on a client/server architecture that includes clients, a server and a
network as in Fig 2.1. The clients are the individual PCs of the system. Each client is typically loaded with some
application software (such as accounting) and data access software (API) such as ADO.NET. Each client PC, is
installed with the client software portion of Microsoft’s SQL Server 2000. The client software includes various user
tools that we will use in this lab, such as the Management Studio and the Query Analyzer. The server (aka: database
server) is a computer on the network that stores the database files and requires a DBMS software such as SQL Server (or
Oracle). The server in our lab is called Dwarf. The network consists of the cabling, communication lines and other
components that connect the clients and the server of the system. In our labs the client/server system are part of the CIS
LAN.
Figure 2.1 Client/Server Configuration
Note that Windows XP and Microsoft SQL Server 2000 enable you to install the database server on your client, (called
MSDE - Microsoft SQL Server Desktop Engine), and run the client/server configuration on a single PC. This way you
can run client/server configuration on your home computer and execute SQL commands.
The database is typically stored on:
c:\Program Files\Microsoft SQL Server\MSSQL\Data
and the extension of the Microsoft SQL Server database file is: MDF (Ex: mydemo.MDF)
2
3. START MS SQL SERVER AND CONNECT TO A DATABASE
To start MS SQL Server, click:
Start



All Programs
Microsoft SQL Server 2005
SQL Server Management Studio
The name of the server for this class is “DWARF”. Select that server name from the pick list (shown below). If
the Server Dwarf is not displayed, you may need to register it (if so, ask your TA).
Under Authentication, select "SQL Server Authentication" (since your assigned SQL Server user name and
password are not the same as your Windows user name and password.)
Under the Login and Password fields, enter your assigned user name and password for this class (user name
format is like: fa08_c2109xxxx).
Figure 3.1 Connecting to a database
Click on the Connect button to see the Microsoft SQL Server Management Studio Object Explorer.
Figure 3.2 SQL Server Management Studio
3
Underneath the DWARF server, open the ‘Databases’ folder to display all the databases in Dwarf. It may take a few
minutes to find and open your database (named the same as your class user name, format like: fa08_c2109XXXX). You
always should open your database first when you are working with SQL Server.
Figure 3.3 Opening Your Database in SQL Server Management Studio
Note that you are not authorized to create new databases. Therefore, all the tables that you will create must be done in a
single database schema assigned to you.
4. CREATE A SMALL DATABASE USING MS SQL SERVER MANAGEMENT STUDIO
In this lab, we will use these features (as shown in figure 3.3 above).




Tables – to create tables and enter data.
Diagrams – to create an Entity Relationship Diagram (ERD) and create relationships between the tables in your
database.
Views – to create views.
SQL Query Window (by clicking the “New Query” button, top left in menu) – to run SQL commands.
(Some of the other options relate to database security and only the database administrator can use these.)
4
Your first exercise is to create a portion of the schema of the manufacturing database from the textbook. Recall that the
normalized manufacturing Entity Relationship Diagram (ERD) looks like this:
Figure 4.1 The Manufacturing System ER DIAGRAM
5
4.1. CREATE TABLES USING MANAGEMENT STUDIO (CUSTOMERS AND ORDERS TABLES)
To create the Customers table, right click the ‘tables’ folder and select ‘New Table’.
Figure 4.2 Creating a New Table
Enter the following column specifications (Column Name, Data Type, and Allow Nulls).
Figure 4.3 Specifying Columns in Creating a New Table
Right click on the Customer_ID column and select Primary Key.
Figure 4.4 Setting Primary Key for a Table
6
When you are done, click the save icon
and you will be prompted to name the table (“Customers”).
Next, create the Orders table (the same way you created the Customers table).
Figure 4.5 Creating the Orders Table
NOTES:


If a primary key is made up of multiple attributes (Column Names), you would select all those attributes (e.g.,
using the Control key) and then right-click and select Primary Key.
A null value indicates the absence of data.
 Any type of field (e.g., date, numeric, character) can hold a null value, but ONLY if that field specified
“ALLOW NULLS” during table definition.
 A typical use of allowing NULLs is to implement an optional foreign key relationship. For example, you
might want to enforce a constraint on Student records – if a Major is specified, that Major must exist in the
Department Table. However, a Student may not have any value at all in the Major field.
 Note other common data types that are listed in the appendix at the end of this document.
If you need to modify the design of one of your tables, you can always, right click on the table, and select Design:
Figure 4.6 To Modify the Design of a Table
IMPORTANT:


As you work with SQL, realize that all your changes are NEVER SAVED (e.g., creating tables, modifying
data, etc), until you close out the window in which you made those changes. Although you may feel that this is
annoying, it is designed to save the database from unwanted mistakes.
Also, you may have to right-click on your database, its tables folder, or any table underneath that and select
REFRESH in order to see your latest changes.
CLOSE ANY WINDOWS THAT MAY BE OPEN NOW, so that your changes are committed to the database.
7
4.2. CREATE INDEX USING MANAGEMENT STUDIO (ON THE CUSTOMERS TABLE)
MS SQL Server provides for clustered and non-clustered indexes. A clustered index defines the sequence in which the
rows of the table are stored. Thus each table can contain only one clustered index, and many (over 200) non-clustered
indexes. A database can be VERY FAST or VERY SLOW, depending on whether the indexes are appropriate for the
usage. If you put lots of indexes, you get faster queries, but slower updates (because a lot of indexes need to be updated
whenever data is updated).
When to create an index:
 When the column is a foreign key or when the column is used frequently in search conditions
 When the column contains a large number of distinct values
 When the column is updated Infrequently (so the index does not slow down data updates)
In order to make things faster, an index must be specified exactly as the search criterion. For example, suppose there are
lots of queries that look for names (but converted to upper case – all capital letters), like this:
… WHERE UPPER(Customer_name) = “SMITH”
Create an Index on the Customers table, on field Customer_Name.
To create an index on a table, open up the table, then right click on the “Indexes” folder underneath that table, then
select “New Index” as shown in the figure below
Figure 4.7 Creating an Index on a Table
8
When the following window opens,


Give your index a name, such as IX_CUSTOMERS_CUSTOMER_NAME
then click on the ADD button.
Figure 4.8 Naming an Index on a Table
9




When the secondary window pops up (showing you all the fields that are in the Customers table), you select the
field (or fields) on which you want to index. Select Customer_Name in the window shown below, and then
click on OK.
o Now that you have created an index on the Customers table by Customer_Name, all queries that specify
Customer_Name in their condition (WHERE CLAUSE) will run faster. However, updates to the
Customers table may be a bit slower since SQL Server will have to update this index whenever any
Customer_Name changes.
Back in the main window, click on the Unique checkbox. By doing this, the database will not allow two
customers with exactly the same Customer_name to be stored in the Customers table.
If you wanted to add another Index to the Customers table, you would click on Add again, but we will not do
that now.
Click OK and OK to complete your specifications of Indexes on the Customers table.
Figure 4.9 Selecting Column(s) upon which the Table will be Indexed
10
When you have finished creating your Index on the Customers table, you should be able to see it in the Object Explorer
pane. You may have to play around a bit with refreshing in order to see this (right-click on and select REFRESH for the
Indexes folder, the Tables folder, your database folder, closing and opening your database).
Figure 4.10 New Index Shown in Object Explorer
4.3. CREATE ER DIAGRAM AND CREATE RELATIONSHIP (BETWEEN CUSTOMERS & ORDERS TABLES)
Next create an ERD (Entity Relationship Diagram) that will enable you to specify relationships between the tables in
your database by right clicking on the “Database Diagrams” folder (underneath your database in the Object Explorer).
Figure 4.11 Create an Entity Relationship Diagram (ERD)
Add tables to your ER Diagram.

When the “Add Table” window pops up, select the Customers table and the Orders table to be added to your
diagram. If you do not see these tables as choices, click on the Refresh button so you see the latest list of tables
in your database.
11
At this point, your ERD should look like this:
Figure 4.12 ER Diagram with Two Tables Added (no relationships yet)
Add a relationship (from Orders.Customer_ID to Customers.Customer_ID).



Drag the grey box before the Orders.Customer_ID attribute to the Customers.Customer_ID attribute.
When this window pops up, check that you have the right primary key table and field, the right Foreign key
table and field.
Then click OK.
Figure 4.13 Columns Specified in a Relationship in ER Diagram
12
Then, you’ll see the Foreign Key Relationship main window. If you open up “INSERT and UPDATE specifications”,
(similar to Access relationships) you have the option to select
 No action – This is the normal choice. With this selected, the database will not allow a primary key
record to be deleted if there are any foreign key records pointing to it.
 Cascade
 Set null
 Set default
Figure 4.14 Specifying Cascade Update or Delete for a Relationship in ER Diagram
This is how your final ER Diagram will look. (If you make a mistake, you can right-click on the relationship line, delete
it and then try again.)


Click the SAVE icon and name your diagram (perhaps “MY_ERD”).
It is important to CLOSE OUT of the ERD window and say yes to SAVE – so that your changes will be
committed to the database (the addition of the FOREIGN KEY reference from Orders to Customers).
Figure 4.15 ERD (Entity Relationship Diagram) with Relationship
13
5. CREATE TABLES (ORDER_LINE & PRODUCTS) USING SQL COMMANDS, UPDATE ER-D
To run SQL commands, click on New Query in Microsoft SQL Server Management Studio. This opens up a SQL
Command window into which you enter the SQL you want to run:
Figure 5.1 Opening a SQL Query Window (so you can run SQL Commands)
Type a simple SQL command into the SQL Query Window: SELECT * FROM CUSTOMERS Then, click on the
red exclamation point icon to run your SQL. This causes the results window to open up on the bottom. Right now,
you only see the column headings (Customer_ID, Customer_Name), but no data since data has not been entered yet.
Figure 5.2 Executing SQL Commands from the SQL Query Window
You can also click on the blue checkmark icon
to the right of the Execute icon, if you just want to check the syntax
of your SQL commands (see if you made any spelling errors, etc) before running it.
14
Use SQL to create Products and Order_Line tables, by entering the following SQL DDL commands into the SQL
Query Window and then executing them (red exclamation icon).
CREATE TABLE products
(product_id
product_description
product_quantity
INT IDENTITY PRIMARY KEY NOT NULL,
CHAR(30) NOT NULL,
INT);
CREATE TABLE order_line
(order_id
INT NOT NULL REFERENCES orders(order_id),
order_quantity
INT NOT NULL CHECK (order_quantity > 2),
product_id
INT NOT NULL REFERENCES products(product_id));
The bottom Results window should show you this message:
Command(s) completed successfully.
Just for fun, run those commands again (just click on the red exclamation point again). This time you should get this
message:
Msg 2714, Level 16, State 6, Line 1
There is already an object named 'products' in the database.
It’s saying that it can’t create a Products table because one is already created. It’s a good idea to pay careful attention to
error messages rather than just try to guess what went wrong.
In the Object Explorer, right click on your Tables folder and select REFRESH. Then, you should see the new tables that
you just created by using the above SQL DDL commands.
Figure 5.3 New Tables Shown in Object Explorer
Note that there is NO NEED TO SAVE when you close out a SQL Query Window-- unless you think you might want
to run that SQL script again (if you do want to save it, give it a good name so you can find it in the future). Generally,
for this lab, we do not need to save the SQL scripts, but for the other Windows, it is important to Save successfully.
15
Using the Obeject Explorer, open the ER Diagram you created earlier (Figure 4.15) and add the two additional tables
(order_lines and Products) to your ER Diagram. To add the tables, right-click on any blank space in the diagram. If
the relationships are not shown, make these connections now.
Figure 5.4 The complete ER Diagram (with four tables)
Note for your Assignment (that you will print and email to the TA)
If you haven’t already done so, create a word document that will hold the various items that you will be copy/pasting for
your homework submission. (See step 9 for more about homework submission.) Into your Word document:
Part A:
copy/paste the SQL commands you used in this step -- to create the two tables (products and order_line)
Part B:
copy the ER DIAGRAM (as an image, Prt-Sc) and paste into word.
16
6. MODIFY TABLE DEFINITIONS USING SQL (ADD FIELDS TO CUSTOMER TABLE)
You can use SQL DDL (Data Definition Language) to modify table definitions as discussed below.

To add a new attribute (phone ) to our customers table, you would run this SQL DDL code:
ALTER TABLE customers
ADD phone CHAR (10);

To remove this attribute from the table, you would run this code:
ALTER TABLE customers
DROP COLUMN phone;

Add the Phone field back to the Customers table (pretend your client has trouble making up their minds).

Similarly, you COULD use the ALTER command to add primary keys, foreign keys and other constraints to
your tables. However, we already have the Primary and Foreign Key indices, so don’t do this now. (Note:
IX_cust_orders is just a name you decided to call the index.) You also could drop and re-add indices.
ALTER TABLE orders
ADD FOREIGN KEY (IX_cust_orders) REFERENCES customers(customer_id);
Remember DDL just means Data Definition Language – this subset of SQL creates tables, fields, indices, and
relationships.
Use the SQL DDL commands (ALTER statements) to add these columns to the Customers table:
1. Phone
2. City
3. State
4. Zip
Remember that you must click on the “New Query” button (upper left of screen), if you haven’t already done so – to be
able to run SQL commands. Also, remember to clear out any old SQL commands from the top pane before you type in
the new SQL commands that you want to run.
Note for your Assignment (that you will print and email to the TA):
Part C:
Into your word document, copy/paste the SQL commands you used above to alter the Customers table.
17
7. INSERTING, UPDATING, AND DELETING DATA
In the next steps, you will insert data using two techniques;
Using the GUI of the Management Studio, and
Using SQL INSERT statements
7.1. INSERT DATA AND RUN QUERIES USING MANAGEMENT STUDIO
Like MSAccess, Management Studio enables you to enter data using a grid format. To see or edit all the records (rows)
in a table, you right-click the table (from the Object Explorer), and select Open Table.
Figure 7.1 Opening up a Table in Grid Format (Management Studio)
Just like MSAccess, you can enter data into a grid; also, like MSAccess, the row of data is saved only when you move
OFF the row. If the row violates any database constraints, you will get an error message when you try to move off the
row (e.g., PK is not unique, FK does not reference a PK in another table, domain constraints for any field).
Figure 7.2 Editing Table in Grid Format (Management Studio)
Using Management Studio, enter at least 3 rows of data into each of your four tables (Products, Customers, Orders,
Order_Line). Make up your own data (not meaningless data) for each table. Keep in mind that you must enter the data
in a particular order, for example, you must enter data into the Customers table before you can enter data into the Oders
table (because each order must reference a customer). Keep in mind also, that if you have not moved OFF a row, that
row has not been stored into the database and therefore cannot be referenced. It is safest if you close out of each
window after you enter data into that table.
When you enter data into the Products table, remember that the Product_Id field was specified as IDENTITY (like the
MSAccess auto-number type field), so you will not be allowed to type anything into the Productn_ID field.
18
As you enter data into the Orders table, you must enter dates in a format that the database will accept. The following
format (e.g., “20-MAR-2009”) works. When you click off the row and the database accepts the data, it redisplays the
date in a different format (e.g., “3/20/2009 …”) as shown below.
Figure 7.3 Format to Enter Dates
As you enter data into the Order_Line table, remember the DDL you used to create that table (see below). It specified
a domain constraint that all values for order_quantity must be greater than 2. Enter an order_quantity value lower than 2
and see what kind of error message you get when you try to move off that row.
CREATE TABLE order_line
(order_id
order_quantity
product_id
INT NOT NULL REFERENCES orders(order_id),
INT NOT NULL CHECK (order_quantity > 2),
INT NOT NULL REFERENCES products(product_id));
7.2. INSERT DATA WITH SQL INSERT STATEMENTS
Another way to get data into a table is by using SQL DML (Data Manipulation Language) commands in the SQL Query
Window.
Recall that our Customers table now has these fields in it:
Customer_id, customer_name, Phone, City, State, Zip
To insert a record, you could (but please don’t) run this SQL INSERT statement:
INSERT INTO customers
VALUES (11, 'Contemporary Casuals', ‘215-222-4444’, '100 Main St.', 'Phila', 'PA', '19111');
And this (above statement) would probably work – BUT ONLY IF the fields of the Customer table were created in the
order listed above. It’s MUCH safer to (and I insist that you) use this INSERT statement (especially when writing these
Insert statements inside a VB or C# program):
INSERT INTO customers ( Customer_id, customer_name, phone, city, state, zip)
VALUES (12, 'Old Timer Dress-up Clothes', ‘215-222-4445’, '200 Main St.', 'Phila', 'PA', '19111');
Notice that the value for Customer_id does not have quotes around it but the zip code does. Do you have any idea why?
(Check the data types for these two fields.)
19
Remember in Access how you never entered any data into those “auto-number” type fields? The same is true in MS
SQL Server for the “IDENTITY” type fields. Recall that table products was created with this SQL DDL:
CREATE TABLE products
(product_id
product_description
product_quantity
INT IDENTITY PRIMARY KEY NOT NULL,
CHAR(30) NOT NULL,
INT);
So, the following Insert statement WILL NOT WORK:
INSERT INTO products (product_id, product_description, product_quantity)
VALUES (10, 'shiny shoes', 225);
But this one WILL WORK (because it does NOT specify a value for product_id):
INSERT INTO products (product_description, product_quantity)
VALUES ('shiny shoes', 225);
Another important fact – you write a SQL INSERT command that does not insert data into some of the fields, but this
will work only of those fields are allowed to accept null values (when the table was designed). For instance, this
statement WILL FAIL because Product_Description was specified as “not null” when the Products table was created.
INSERT INTO products (product_quantity) VALUES (500);
You can also use a sub-query to select rows to be inserted from another table as shown below:
INSERT [INTO] table_name [(column_list)]
SELECT column_list
FROM table-source
[WHERE search condition]
Use SQL INSERT statements to add at least two additional records to each of your four tables.
7.3. BACKUP TABLES USING SQL COMMANDS (INSERT INTO, DROP TABLES)
Backing up is always important – especially before testing any update or delete commands. Back up each of your 4
tables now using the example syntax below. (Give good names to the new backup tables, e.g., bak_products.) The
statements below assumes that new_table_name does not exist prior to running the statement.
SELECT * INTO new_table_name FROM old_tablename;
If you want to remove a table (structure plus data), you use the DROP statement, as shown below. The following SQL
code works all the time (because it drops the new table before creating and copying data into it). However, you do get a
warning when you try to drop a table that does not exist.
DROP TABLE cust_bak;
SELECT * INTO cust_bak FROM customers;
Msg 3701, Level 11, State 5, Line 1 Cannot drop the table 'cust_bak', because it does
not exist or you do not have permission.
(3 row(s) affected)
20
7.4. SQL UPDATE COMMANDS
Here is the basic syntax for a SQL UPDATE statement
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value
Here is the SQL DML to update a column in a record of your Products table (this assumes your table has a
product_id=1. Try it out:
UPDATE products SET product_description = 'Bannana' WHERE Product_id = 1;
Here is the SQL DML to update two columns in a record of your Products table (this assumes your table has a
product_id=1. Try it out:
UPDATE products SET
product_description = 'Apple',
product_quantity=33
WHERE Product_id = 1;
Make up a couple of your own SQL update statements and run them – to make sure you understand how to do this.
7.5. SQL DELETE (DELETES RECORDS BUT NOT TABLE STRUCTURE)
Go to this website and find out the sample syntax for the DELETE command: http://www.w3schools.com/sql
Compose a Delete statement that deletes one record from one of your tables (make sure the table is backed up first).
Note that the following statement is pretty destructive. All rows are deleted. The table (structure) still remains but with
no data, no records inside
DELETE FROM my_customers;
Note for your Assignment (that you will print and email to the TA):
Part D:
Into your word document, copy/paste SQL you used for step 7:
 Backup commands (preceded by with drop table for any one table).
 One SQL INSERT command for each of the 4 tab les.
 One SQL UPDATE command that updates at least 2 columns (any table).
 One SQL DELETE command that commands deletes one record (any table).
21
8. LOADING A DATABASE W ITH DATA
There are two ways to fill our database with lots of data:
 Import the ACCESS database or
 use a SQL script.
Since you named your tables differently (no “_t” suffix), the import and SQL loading should not destroy the work you
have completed for this lab.
8.1. IMPORT DATABASE FROM MSACCESS
From Management Studio, right click your database, select tasks, then import data. This will start the Wizard.
8.1 Starting the Import Wizard
22
For ‘data source’, select ‘Microsoft Access’ and browse to where ANY Access database is stored – it doesn’t matter
because we WILL cancel before we actually import the data.
8.2 Selecting the Data Source for the Import Wizard





The next Wizard Window will prompt for Username and Password on the destination database (on Dwarf) –
make sure to select SQL Server Authentication so that you may enter your class username and password.
From the next window, select the “COPY DATA” option.
From the next window, click on the source check box (this will select all the tables and views).
IF you clicked Next until the Wizard finished, it would import all the tables and views.
BUT cancel here (we prefer to load data in the next step – using SQL scripts).
23
8.2 LOAD DATABASE USING SQL SCRIPT
From Management Studio, open up a SQL query window (click on the New Query button).
Now, we want to delete the tables we just imported (so we can create them a different way).
 From blackboard, save the file called drop_tables.sql and then open it in Notepad.
 Copy the contents of the file into the clipboard and paste into a SQL Query window (making sure to delete any
old SQL that was in that window).
 You can click on the Blue Check mark -- just to see if SQL thinks this code is syntactically correct.
 Execute this query.
 Refresh your database and its tables. Check the Object Explorer to see that most of the tables were deleted.
 Right click on any remaining “_t” tables that did not get deleted and delete these. (Leave the 4 tables you
created in this exercise – don’t delete them).
Next we want to create new empty tables with all the relationships (SQL DDL – Data Definition Language)
 From blackboard, save the file called SQLServerCreateTables.sql and then open it in Notepad.
 Copy the contents of the file into the clipboard and paste into a SQL Query window (making sure to delete any
old SQL that was in that window).
 You can click on the Blue Check mark -- just to see if SQL thinks this code is syntactically correct.
 Execute this query.
 Refresh your database and its tables. Check the Object Explorer to see all the tables that were newly created.
Next we want to load the new empty tables with data (SQL DML – Data Manipulation Language)
 From blackboard, save the file called SQLServeMfgData.sql and then open it in Notepad.
 Copy the contents of the file into the clipboard and paste into a SQL Query window (making sure to delete any
old SQL that was in that window).
 You can click on the Blue Check mark -- just to see if SQL thinks this code is syntactically correct.
 Execute this query.
 Refresh your database and its tables.
 From the Object Explorer, open a couple of tables to verify that the data came in OK.
As you did previously, create a new ER Diagram and add all the newly entered tables. You may have to do some
refreshing etc in order to be able to see all the tables and add them onto the ERD. Move the tables around so that no lines
are crossing, all the fields are shown in every table, and you minimize the space between the tables. When you bring
these tables into your diagram, the relationships should already be there, so you will not have to create them with the
drag/drop as you did before.
24
Here is one version of how your ER Diagram might look – you just need to move things around so that the tables that
point to nothing are towards the outside and related tables are near each other – this makes the diagram become a good
reference for programmers who need to know table names, field names, and relationships all the time.
8.3 ER Diagram Showing Tables and Relationships (as Created by Import SQL Script)
Save your diagram to make sure that everything is OK. Then open up your diagram again to get a screen capture of it
(for homework submission). -- To view all the tables at once, you can do a CTRL-A (Select all tables in the diagram),
then select the Zoom setting “fit to selection”.
Note for your Assignment (that you will print and email to the TA):
Part E:
Into your word document, copy/paste the ERD you created above.
25
9. HOMEWORK SUBMISSION
You are expected to know how to use the ‘SQL Query Window’ and the ‘Management Studio’
and understand the SQL commands that you have executed in this lab.
Submit (print for and email to) the TA:
A.
B.
C.
D.
The SQL script from step 5 which you used to create the 2 tables (Products & Order_Line).
An image of the final ER DIAGRAM from step 5 showing the four tables with their relationships.
The SQL script from step 6 script that altered the Customers table, adding the extra columns.
SQL script from step 7 (SQL statements to backup any one table, insert a record into each of your
4 tables, update 2 fields in a record in any table, delete exactly one record in any table).
E. ERD that shows all the 17 tables (and their relationships) as imported in step 8.
Appendix – Common Data Types
String




char[(n)]
Fixed-length string of length n
varchar[(n)] variable-length string of length n
nchar(n)
Fixed-length string of Unicode character data, used for languages around the world
nvarchar(n)
Numeric
 Integer type
 Int: Integers from -2,147,483,648 through 2,147,483,647
 Smallint: Small integers from -32,768 through 32,767
 Bit: Binary (0 or 1)
 decimal[(p[,s])], specify # of digits and # of digits to the right of the decimal point
 numeric[(p[,s])]: Synonymous with decimal
 Real data type:
 float[(n)] Double-precision floating point numbers in the range of - or + 1.79*10308
 real: Single-precision floating point numbers in the range of – or + 3.4*1038
Temporal (date/time)
 datetime: Dates and times from 1/1/1753 through 12/31/9999
Common date formats
yyyy-mm-dd
mm/dd/yyyy
mm-dd-yy
month dd, yyyy
mon dd, yy
dd Mon yy
2004-08-15
8/15/2004
8-15-2004
August, 15 2004
Aug 15, 04
15 Aug 04
Common time formats
hh:mm
14:35
hh:mi am/pm
2:35 pm
hh:mi:ss
2:35:38
hh:mi:ss:mmm 2:20:38:10
26