Вы находитесь на странице: 1из 16

MS SQL Server - Lesson 08: The Tables of a Database

<a

href="http://c.casalemedia.com/c?s=56757&f=2&id=2055502211.8234618" target="_blank"><img src="http://as. casalemedia.com/s?s=56757&u=http%3A//functionx.com/sqlserver/Lesson08. htm&f=2&id=2055502211.8234618&if=0" width="728" height="90" border="0"></a>

The Tables of a Database


Tables Fundamentals
Introduction
A table is primarily a list of items or a group of lists. To manage such a list, it should be meticulously organized. To organize this information, it is divided in sections. Here is an example: Name Judie Ernest Bill David Hermine Age 18 24 52 36 12 Gender Relationship Female Male Male Sister Cousin Brother

Unknown Uncle Unknown Niece

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

Practical Learning: Starting a Database


1. Start Microsoft SQL Server, connect and, in the Object Explorer, expand the Databases node 2. In the Object Explorer, right-click Databases and click New Database... 3. In the New Database dialog box, set the Database Name to BCR 4. Under Initial Size (MB) column, set the size of the PRIMARY filegroup to 10 5. Click OK

Visual Creation of a Table


The information of a table is organized in categories called columns and horizontal arrangements called records or rows. A column holds a category of data that is common to all records. A table must have at least one column. This means that you cannot create a table without defining at least one column.

Practical Learning: Creating a Table


1. In the Object Explorer, expand the BCR node (click its + button) 2. Under BCR, right-click Tables and click New Table...

file:///C|/Documents%20and%20Settings/michael.musyoki/Desktop/SS/Lesson08.htm (1 of 16)11/27/2008 8:10:30 AM

MS SQL Server - Lesson 08: The Tables of a Database

3. As the cursor is blinking in the first empty field under the Column Name column, type name and press Enter

Tables Names
To complete the creation of a table, you must save it. If you are freshly creating a table and decide to save it, you would be prompted to name it. The name of a table:
q

Can be made of digits only. For example you can have a table called 148 Can start with a digit, a letter, or an underscore Can be made of letters, digits, and spaces

Besides these rules, you can make up yours. To avoid confusion, here are the rules we will use to name our tables:
q

A name will start with a letter. Examples are act or Second After the first character as an underscore or a letter, the name will have combinations of underscores, letters, and digits. Examples are _n24, act_52_t Unless stated otherwise, a name will not include special characters such as !, @, #, $, %, ^, &, or * If the name is a combination of words, each word will start in uppercase. Examples are Staff Members or Video Titles

Practical Learning: Naming a Table


1. To save your table, on the Standard toolbar, click the Save button

file:///C|/Documents%20and%20Settings/michael.musyoki/Desktop/SS/Lesson08.htm (2 of 16)11/27/2008 8:10:30 AM

MS SQL Server - Lesson 08: The Tables of a Database

2. In the Choose Name dialog box, type Employees and press Enter 3. After saving the table, close it by clicking its system Close button

Creating a Table With SQL


Introduction
In SQL, to create a table, you start with the following statement: CREATE TABLE TableName; The CREATE TABLE expression is required. The TableName factor specifies the name of the new table. The TableName can use the rules and suggestions we reviewed for the tables. After specifying the name of the table, you must create at least one category, called a column of data.

Using Sample Code


To assist you with creating a table, Microsoft SQL Server can generate sample code for you. You can then simply modify or customize it. First display or open an empty query window. To display the Templates Explorer, on the main menu, you can click View -> Templates Explorer. In the Templates Explorer, expand the Table node. Under table, drag Create Table and drop it in the query window. Sample code would be generated for you.

Tables Maintenance
Introduction
Table maintenance consists of reviewing or changing its aspects. This includes reviewing the list of tables of a database, renaming a table, or deleting it.

Viewing the Properties of a Table


Like every other object of a database or of the computer, a table possesses some characteristics that are proper to it. To view these characteristics, in the Object Explorer, right-click the table and click Properties.

Opening a Table
Most operations require that you open a table before using it. There are various ways a table displays, depending on how you want to examine it:
q

To view the structure of a table, perhaps to change its columns, in the Object Explorer, expand your database and its Tables node. Right-click the table and click Modify. The table would open in design view, the same view you use to visually create a table. If you want to view the SQL code of a table, in the Object Explorer, right-click the table, position the mouse on Script Table AS, CREATE To, and click New Query Editor Window To open a table to view its data, perhaps to perform data entry, in the Object Explorer, rightclick the table and click Open Table

Tables Review
To see the list of tables of a database in the Object Explorer, you can click the Tables node:

file:///C|/Documents%20and%20Settings/michael.musyoki/Desktop/SS/Lesson08.htm (3 of 16)11/27/2008 8:10:30 AM

MS SQL Server - Lesson 08: The Tables of a Database

To see the list of tables of a database using SQL, in a Query window, specify the database (using a USE statement), and execute sp_help (it is a stored procedure). Here is an example:

Renaming a Table
If you find out that the name of a table is not appropriate, you can change it. To change the name of a table in the SQL Server Management Studio, in the Object Explorer, right-click the table and click Rename. Type the desired name and press Enter.

file:///C|/Documents%20and%20Settings/michael.musyoki/Desktop/SS/Lesson08.htm (4 of 16)11/27/2008 8:10:30 AM

MS SQL Server - Lesson 08: The Tables of a Database

To change the name of a table with code, execute sp_rename, followed by the current name of the table, a comma, and the new desired name of the table. The formula to use is: sp_rename ExistingTableName, TableNewName; The names of tables should be included in single-quotes. Here is an example: sp_rename 'StaffMembers', 'Employees'; GO 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.

Deleting a Table
If you have an undesired table in a database, you can remove it. To delete a table in the SQL Server Management Studio, in the Object Explorer, right-click the table under its database node and click Delete. You will receive a warning giving you a chance to confirm your intentions. If you still want to remove the table, click OK. To delete a table using SQL, use the following formula: DROP TABLE TableName The DROP TABLE expression is required and it is followed by the name of the undesired table. When you execute the statement, you will not receive a warning before the table is deleted. You can also use sample code that Microsoft SQL Server can generate for you. First display an empty query window. Also display the Templates Explorer and expand the Table node. Under Table, drag Drop Table and drop it in the empty query window. Sample code would be generated for you. You can then simply modify it and execute the statement.

Referring to a Table
In future lessons, we will write various expressions that involve the names of tables. In those expressions, you will need to specify a particular table you want to use. There are three main ways you can do this. To refer to, or to indicate, a table:
q

You can simply type its name. An example would be Students You can type dbo, followed by the period operator, followed by the name of the table. An example would be dbo.Students You can type the name of the database to which the table belongs, followed by the period operator, followed by dbo, followed by the period operator, and followed by the name of the table. An example would be RedOakHighSchool.dbo.Students

The Columns of a Table


Introduction
In our introduction to tables, we saw that a list could be organized in categories called columns. Here is the example we saw: Name Judie Ernest Bill David Hermine Age 18 24 52 36 12 Gender Relationship Female Male Male Sister Cousin Brother

Unknown Uncle Unknown Niece

As you can see from this arrangement, a column is used to particularly classify one type of data. For example, one column can be used to list some names. Another column can be used to list numbers. Yet another column can be used for a select list of items that keep repeating those items.
file:///C|/Documents%20and%20Settings/michael.musyoki/Desktop/SS/Lesson08.htm (5 of 16)11/27/2008 8:10:30 AM

MS SQL Server - Lesson 08: The Tables of a Database

To organize the information that a column holds, a table needs a series of details about each column. Two aspects are particularly important: a name and the type of data that a column should/must/can hold.

The Name of a Column


To be able to recognize the categories of information that a column holds, the column should have a name. In Microsoft SQL Server, the name of a column displays in the top, the header part, of the column. The name of a column allows the database as a file to identify the column. The name of a column also will help you, the database developer, to identify that column. There are rules and suggestions you must or should follow when naming the columns of a table. The name of a column:
q

Can start with a letter, a digit, or an underscore Can include letters, digits, and spaces in any combination

After respecting these rules, you can add your own rules. In our lessons, here are the rules we will use to name our columns:
q

A name will start with a letter. Examples are n, act, or Second After the first character as an underscore or a letter, the name will have combinations of underscores, letters, and digits. Examples are n24 or col_52_t Unless specified otherwise, a name will not include special characters such as !, @, #, $, %, ^, &, or * If the name is a combination of words, each word will start in uppercase. Examples are Date Hired, LastName, Drivers License Number, or EmailAddress

Practical Learning: Setting Columns Names


1. Under the Column Name column, double-click name to highlight it 2. Type FirstName to replace it and press Enter

The Types of Data


After deciding on the name of a column, the database needs to know what kind of information the column would hold. Since there are various kinds of information a database can deal with, we saw in Lesson 3 the types of data that Microsoft SQL Server supported. Therefore, you must specify the data type that is necessary for a particular column.

Practical Learning: Setting Data Types


1. Click the arrow of the combo box under the Data Type column 2. Scroll down and select varchar from the list

file:///C|/Documents%20and%20Settings/michael.musyoki/Desktop/SS/Lesson08.htm (6 of 16)11/27/2008 8:10:30 AM

MS SQL Server - Lesson 08: The Tables of a Database

3. Click the first empty field under FirstName and type MI 4. Press the down arrow key to position the cursor under MI 5. Type LastName and press the down arrow key 6. Type DateHired 7. Press Tab and type d 8. Notice that the datetime data type is selected. 9. Press Enter three times to position the mouse cursor under DateHired 10. Type EmployeeNumber and press the down arrow key 11. Complete the table as follows:

file:///C|/Documents%20and%20Settings/michael.musyoki/Desktop/SS/Lesson08.htm (7 of 16)11/27/2008 8:10:30 AM

MS SQL Server - Lesson 08: The Tables of a Database

12. Save the table

The Length of Data


A database deals with various types of data, appropriate or not for certain fields. This means that you should take care of jobs behind the scenes as much as you can. One way you can do this is by controlling the amount of information that can be stored in a particular field. As various columns can hold different types of data, so can the same data type control its own mechanism of internal data entry. The length of data means different things to different fields. Columns that carry the same data type can have different lengths. Bit Fields: We saw already that a bit column type is meant for one of two answers. The user is supposed to simply let the database know that the answer is yes or no, true or false, on or off, 1 or 0. Therefore, the only length of this field is 1. Integers: The length of an integer is the number of bytes its field can hold. For an int type, that would be 4 bytes. Decimal and Floating-Point Numbers: The Length specifies how many bytes the field can store. Strings: The Length of a character or string column specifies the maximum number of characters that the field can hold. In some circumstances, you will need to change or specify the length as it applies to a particular field. For example, since you should use the varchar data type for a string field whose content will change from one record to another, not all varchar columns need to have the same length. Although a First Name and a Book Title columns should use the varchar type, both columns would not have the same length of entries. As it happens, people hardly have a first name that is beyond 20 characters and many book titles go beyond 32 characters. In this case, both fields would use the same data type but different lengths. On the other hand, for columns of datetime and money data types, you should accept the default length suggested by the database. There are two ways you can change the length of a string-based column:
q

In the top section of the windo, to change the length of the field, in the parentheses of the data type, enter the desired value In the top section of the window, click the name of the column. In the bottom section, click the Length field and type the desired value

file:///C|/Documents%20and%20Settings/michael.musyoki/Desktop/SS/Lesson08.htm (8 of 16)11/27/2008 8:10:30 AM

MS SQL Server - Lesson 08: The Tables of a Database

Practical Learning: Setting Data Types


1. In the top section, click EmployeeNumber to select it 2. In the bottom section, click Length and type 6 3. In the top section of the table, click Address and press Tab 4. For the data type, type VARCHAR(100) 5. In the same way, complete the table as follows:

6. Save the table

Programmatic Creation of Columns


We saw that the primary formula to create a table was: CREATE TABLE TableName After specifying the name of the table, you must list the columns of the table. The list of columns starts with an opening parenthesis "(". The list ends with a closing parenthesis ")". Each column must be separated from the next with a comma, except for the last column. You can include all columns on the same line if possible as follows: CREATE TABLE Country(Column1, Column2, Column3) Alternatively, to make your statement easier to read, you should create each column on its own line as follows: CREATE TABLE Country( Column1, Column2, Column3); There are two primary pieces of information you must specify for each column: its name and its type.
file:///C|/Documents%20and%20Settings/michael.musyoki/Desktop/SS/Lesson08.htm (9 of 16)11/27/2008 8:10:30 AM

MS SQL Server - Lesson 08: The Tables of a Database

Therefore, the syntax of creating a column is: ColumnName DataType Options The name of a column should follow the same rules and suggestions we reviewed for the columns. After typing the name of the column, type the desired or appropriate data type for the column. For this example, use one of the (appropriate) data types we reviewed. Remember that some of the data types need to have a length. This is certainly true for all string or text-based columns (char, text, varchar, etc). In the case of text-based columns, when using SQL to create your columns, because it is less visual than the table design of the SQL Server Management Studio, you cannot rely on the default length of strings suggested by SQL (in fact, in MySQL, you must specify a length for varchar). As it happens, the SQL Server Management Studion specifies different default values for text-based columns. Therefore, when using SQL to create your columns, you should (strongly) specify your own default length for text-based columns. We also saw that you could use sample code to create a table. This allows you to have more control over the various columns you want the table to have. To do this, open an empty query window and display the Templates Explorer. Expand the Table node. Under Table, you can drag Create Table, Add Column, or Drop Column, and drop it in the query window. If you use dropped Add Column or Drop Column, you can delete the undesired sections of the code and isolate only the part that handles table creation. Here is an example: --========================================================================== -- Add column template --- This template creates a table, then it adds a new column to the table. --========================================================================== USE <database, sysname, AdventureWorks> GO CREATE TABLE <schema_name, sysname, dbo>.<table_name, sysname, sample_table> ( column1 int, column2 char(10) ) GO

Practical Learning: Creating a Table Using the SQL Query Analyzer


1. In the Object Explorer, right-click BCR and click New Query 2. In the code editor, type the following: CREATE TABLE Customers ( DrvLicNbr VarChar(50), DateIssued DateTime, DateExpired DateTime, FullName varchar(120), Address VARCHAR(120), City varchar(50), State varchar(100), PostalCode varchar(20), HomePhone varchar(20), OrganDonor bit) GO

3. To execute the statement, press F5 4. Close the SQL Query Analyzer window 5. When asked whether you want to save the text, click Yes 6. Type Customers as the name of the file and press Enter

file:///C|/Documents%20and%20Settings/michael.musyoki/Desktop/SS/Lesson08.htm (10 of 16)11/27/2008 8:10:30 AM

MS SQL Server - Lesson 08: The Tables of a Database

Referring to a Column
Introducion
We will write many expressions that include the names of columns. In such expressions, you will need to indicate the particular column you are referring to. There are various ways you can do this. To refer to, or to indicate, a table:
q

You must type the name of the table to which the column belongs, followed by the period operator, followed by the name of the column. An example would be Employee.LastName You can type dbo, followed by the period operator, followed by the name of the table to which the column belongs, followed by the period operator, followed by the name of the column. An example would be dbo.Employee.LastName You can type the name of the database that owns the table's column, followed by the period operator, followed by dbo, followed by the period operator, followed by the name of the table to which the column belongs, followed by the period operator, followed by the name of the column. An example would be RedOakHighSchool.dbo.Employee.LastName

Using the Alias Name of a Table


You can create an alias name of a table to use in an expression that involves a column. To do this, type a letter or a word that will represent the table to which the column belongs. The letter or the word is followed by a period operator, and followed by the name of the column. An example would be empl.LastName. At the end of the statement, you must type the name of the table, followed by space, and followed by the letter or the word. An example would be Employee empl .

Columns Maintenance
Introduction
Column maintenance consists of reviewing or changing any of its aspects. This includes reviewing the structure of columns of a table, renaming a column, deleting a column, changing the data type or the nullity of a column, etc.

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

To view the columns of a table using SQL code, in a query window, execute sp_columns followed by
file:///C|/Documents%20and%20Settings/michael.musyoki/Desktop/SS/Lesson08.htm (11 of 16)11/27/2008 8:10:30 AM

MS SQL Server - Lesson 08: The Tables of a Database

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

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

The Properties of a Column


A column on a table controls what kind of data is appropriate for that particular column. The characteristics that identify or describe such a table are defined as its properties. As we have seen previously, three primary properties are particularly important and required for each column: the name, the data type, and the length. Besides these, some other properties can be used to further control the behavior of a particular field. Besides the name, data type and length of a column, you can control the columns of a table using the Columns property sheet in the lower section of the table in Design View. These properties sometimes depend on the data type of the column. Therefore, to specify the properties of a column, you must first select it in the upper section of the table. This selection can be done by just clicking either the name, the data type, or the length of the column. Then you can either press F6 or click the first field in the lower section, select the desired property and type the necessary value:

file:///C|/Documents%20and%20Settings/michael.musyoki/Desktop/SS/Lesson08.htm (12 of 16)11/27/2008 8:10:30 AM

MS SQL Server - Lesson 08: The Tables of a Database

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

Collation
Because different languages use different mechanisms in their alphabetic characters, this can affect the way some sort algorithms or queries are performed on data, you can ask the database to apply a certain language mechanism to the field by changing the Collation property. Otherwise, you should accept the default specified by the table. To specify the collation of a column when creating in, type COLLATE, followed by the desired collation code. Here is an example: CREATE TABLE Customers( FullName varchar(50) COLLATE SQL_Latin1_General_CP1_CI_AS );

Modifying a Column
When making a change on a column, you are also said to alter the table. To support this operation, SQL starts with the following formula: ALTER TABLE TableName When using this statement, the ALTER TABLE expression is required and it is followed by the name of the table.

Adding a New Column


After a table has already been created, you can still add a new column to it. To add a new column in SQL Server Management Studio, first right-click the table and click Design Table. To add a new column to the end of the table, click the first empty field under Column Name, type a name, and specify the other options. To insert a new column between two existing one, right-click the column that will succeed it and click Insert Column:

file:///C|/Documents%20and%20Settings/michael.musyoki/Desktop/SS/Lesson08.htm (13 of 16)11/27/2008 8:10:30 AM

MS SQL Server - Lesson 08: The Tables of a Database

This would create a new empty field. Type the desired name and specify the other options. In SQL, the basic formula to add a new column to an existing table is: ALTER TABLE TableName ADD ColumnName Properties The ColumnName factor is required. In fact, on the right side of the ADD keyword, define the column by its name and using all the options we reviewed for columns. Here is an example: ALTER TABLE StaffMembers ADD Address varchar(100) NULL GO When this code is executed, a new column name Address, of type varchar, with a limit of 100 characters, and that allow empty entry, will be added to a table named StaffMembers in the current database. You can also use sample code to add a new column to a table. First display an empty query window and display the Templates Explorer. Expand the Table node. Under Table, drag Add Column and drop it in the query window. Delete the undesired sections of code and keep only the part that deals with adding a column. Here is an example: --========================================================================== -- Add column template --- This template creates a table, then it adds a new column to the table. --========================================================================== USE <database, sysname, AdventureWorks> GO -- Add a new column to the table ALTER TABLE <schema_name, sysname, dbo>.<table_name, sysname, sample_table> ADD <new_column_name, sysname, column3> <new_column_datatype,, datetime> <new_column_nullability,, NULL> GO

Renaming a Column
If you find out that the name of a column is not appropriate, you can change it. To rename a column in the Object Explorer, right-click the table that the column belongs to and click Modify. In the design view, highlight the name of the desired column to put it into edit mode and edit it. In SQL, to change the name of a column, first open an empty query window. In a query window, execute sp_rename using the following formula:

file:///C|/Documents%20and%20Settings/michael.musyoki/Desktop/SS/Lesson08.htm (14 of 16)11/27/2008 8:10:30 AM

MS SQL Server - Lesson 08: The Tables of a Database

sp_rename 'TableName.ColumnName', 'NewColumnName', 'COLUMN' The sp_rename factor and the 'COLUMN' string are required. The TableName factor is the name of the table that the column belongs to. The ColumnName is the current name of the column. The NewColumnName is the desired name you want to give to the column. Here is an example: sp_rename 'StaffMembers.FullName', 'EmployeeName', 'COLUMN' GO When this code is executed, the interpreter will look for a column named FullName in the StaffMembers table of the current or selected database. If it finds that column in the table, then it renames it EmployeeName.

Deleting a Column
If you have an undesired column that you don't want anymore in a table, you can remove it. To visually delete a column, in the Object Explorer, expand the database, the Tables, and the Columns nodes. Right-click the undesired column and click Delete. The Delete Object dialog box would display. If you still want to delete the column, click OK. To change your mind, click Cancel. To delete a column using code, first open or access an empty query window, and use the following formula: ALTER TABLE TableName DROP COLUMN ColumnName On the right side of the ALTER TABLE expression, type the name of the table. On the right side of the DROP COLUMN expression, enter the name of the undesired column. Here is an example: ALTER TABLE StaffMembers DROP COLUMN CurrentResidence; GO When this code is executed, the interpreter will look for a column named CurrentResidence in a table StaffMembers of the current or selected database. If it finds that column, it will remove it from the table. Microsoft SQL Server can also generate sample code you can use to delete a column from a table. Before doing this, first display an empty query window and display the Templates Explorer. Expand the Table node. In the Table section, drag Drop Column and drop it in the query window. Delete the undesired sections of code and keep only the part that deals with adding a column. Here is an example: --============================================ -- Drop column template --- This template creates a table, then it -- drops one of the columns of the table. --============================================ USE <database, sysname, AdventureWorks> GO -- Drop a column from the table ALTER TABLE <schema_name, sysname, dbo>.<table_name, sysname, sample_table> DROP COLUMN <new_column_name, sysname, column3> GO

Practical Learning: Ending the Lesson


1. Close the query window without saving the file 2. In the Object Explorer, under the Databases node, right-click BCR and click Delete

file:///C|/Documents%20and%20Settings/michael.musyoki/Desktop/SS/Lesson08.htm (15 of 16)11/27/2008 8:10:30 AM

MS SQL Server - Lesson 08: The Tables of a Database

3. In the dialog box, click OK

Lesson Summary
Topics Reviewed
q

Tables Columns

Exercise: Utility Company


1. Access the UtilityCompany1 database 2. Visually create a table named Employees and that has the following columns: EmployeeNumber, FirstName, LastName, and Title 3. Create a table named Customers AccountNumber, DateAccountCreated, CustomerName, Address, City, State, and EmailAddress

Exercise: US States
1. Get your research papers on US regions and New England 2. On the piece of paper, complete the list with regions 3. Complete the list with all states 4. Connect to the server from the Command Prompt and access the UnitedStatesRegions1 database 5. Create a table named Regions with the columns Region and Description 6. Create a table named States with the columns Name, Code, Area, Population, and Capital 7. Exit the Command Prompt

Previous > >

Copyright 2007-2008 FunctionX, Inc.

Next

file:///C|/Documents%20and%20Settings/michael.musyoki/Desktop/SS/Lesson08.htm (16 of 16)11/27/2008 8:10:30 AM

Вам также может понравиться