Home

The Structure of a Database Table

 

A Review of Tables

 

Introduction

Tables are the foundation of organizing lists of items. This concept is valid regardless of the type of list. As a database application is primarily a list of things, any concept we reviewed for tables is also valid for a formal database application. This means that the SQL uses the same approach at organizing information.

As we did for the databases, there are various ways you create a table for a Microsoft SQL Server application and each techniques uses its own approach, we will learn. Before creating a table, you must specify what database it would belong to. You can one of either the Northwind or the pubs databases that ship with Microsoft SQL Server or you can use one of your own.

Practical Learning Practical Learning: Introducing Tables

  1. Start Notepad and type the following:
     
    Imports System
    Imports System.Data.SqlClient
    
    Module Exercise
    
        Public Sub Main()
            Dim strConnection As String = "CREATE DATABASE Countries"
            Dim conDatabase As SqlConnection = _
             New SqlConnection("Data Source=(local);Integrated Security=yes;")
            Dim cmdDatabase As SqlCommand = New SqlCommand(strConnection, conDatabase)
    
            conDatabase.Open()
    
            cmdDatabase.ExecuteNonQuery()
            conDatabase.Close()
    
        End Sub
    
    End Module
  2. To save the file, on the main menu, click File -> Save
  3. Locate your VBasic folder and display it in the Save In combo box
  4. Click the Create New Folder button. Type Countries2 and press Enter twice to display it in the Save In combo box
  5. Change the Save As Type to All Files
  6. Set the File Name to Exercise.vb
  7. Open the Command Prompt and change to the above Countries4 folder
  8. To compile the exercise, type vbc Exercise.vb and press Enter
  9. To execute the application, type Exercise and press Enter
  10. Return to Notepad
 

Table Creation With the SQL

The SQL statement used to create a new table uses the following formula

CREATE TABLE TableName

The CREATE and TABLE keywords must be used to let SQL know that you want to create a table. The TableName factor specifies the name of the new table. The TableName can use the rules and suggestions we reviewed for the database objects.

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. Therefore, the syntax of creating a column is:

ColumnName DataType Options

Table Creation Using ADO.NET

To programmatically create a table, you can follow the same formula rules of creating a table using SQL code. Once the statement is ready, you can pass it to a SqlCommand object. To execute the statement, you can call the SqlCommand.ExecuteNonQuery() method.

The Name of Table

When creating a table, you must name it. In your SQL code, when creating a table, you must name it table using the above formula of CREATE TABLE TableName.

The name of a table:

  • 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. In our lessons, the name of a table

  • Will start with a letter, in uppercase or lowercase. Examples are Employees, Accounts
  • If made of a combination of words, it will have each part start in uppercase. Examples are BookCategories, CustomersBankAccounts.

The Columns of a Table

 

The Name of a Column

Although a table is used to hold information, its data is divided in columns and you must create each column following specific rules. The primary characteristic you must provide for a column is its name. If you are creating a SQL statement, you can type the name of the first column after the opening parenthesis.

The name of a column should follow the same rules and suggestions we reviewed for the database objects.

 

The Types of Data a Column Can Carry

After specifying the name of a column, the interpreter would need to know the kind of information the column would hold. You must specify the data type that is necessary for a particular column. If you are creating a SQL statement, after typing the name of the column, you must type the appropriate name of the desired data type. Remember that SQL is not case-sensitive but while you can write the data type in any case, you should not overlook the case you use for the names of columns.

To support the data types used in a database, the .NET Framework provides the System.Data.SqlTypes namespace that provides a class for each SQL Server data type. The names of SQL data types are:

bit: The bit is the smallest data type. It is used for a field that would validate a piece of information as being true or false, On or Off, Yes or No, 1 or 0. This is also the data type you should select if a check box would be used to validate the value of this column. This means that it can be used where the C#' bool or the .NET Framework's System.Boolean data types would be applied. The .NET Framework database equivalent to this data type is the SqlBoolean class.

int: This is the same data type as the C#' int. It is a natural number that would be used if a column would hold numbers in the range of -2,147,483,648 to 2,147,483,647. This is also the same as the System.Int32 we reviewed for the DataTable objects when we studies DataSet tables. The .NET Framework database equivalent to this data type is the SqlInt32 class.

tinyint: This data type can be used for a column that would hold (very) small numbers that range from 0 to 255. It is equivalent to the .NET Framework's System.Byte database. Because C++ doesn't have a byte data type, the tinyint type can be used where a short or rather an unsigned short would be used. You should use this data type only when you know for sure that the values used on this column will be small. When in doubt, you should use int. The .NET Framework database equivalent to this data type is the SqlByte class.

smallint: The smallint data type follows the same rules and principles as the int data type except that it is used to store smaller numbers that would range between -32,768 and 32,767. This means it is equivalent to the C#' short integer or the .NET Framework's System.Int16 type. The .NET Framework database equivalent to this data type is the SqlInt16 class.

bigint: The bigint data type follows the same rules and principles as the int data type except that its field can hold numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. It is somehow equivalent to the C++' long integer but more accurately equivalent to the .NET Framework's System.Int64 data type. As such, you can apply this data type for a column that would hold (very) large numbers. The .NET Framework database equivalent to this data type is the SqlInt64 class.

binary: This data type is used for a column that would hold hexadecimal numbers. Examples of hexadecimal numbers are 0x7238, 0xFA36, or 0xAA48D. Use the binary data type if all entries under the column would have the exact same length (or quantity). If you anticipate that some entries would be different than others, then use the alternative varbinary data type. The varbinary also is used for hexadecimal numbers but allows dissimilar entries, as long as all entries are hexadecimals. The .NET Framework database equivalent to this data type is the SqlBinary class.

numeric and decimal: This data type is used on a column that will hold (either whole or) real numbers, numbers that include a decimal separator (the character used as the decimal separator as set in the Control Panel) between the digits. An example would be 12.125 or 44.80. If you anticipate such a number for a field, specify its data type as numeric or decimal (either decimal or numeric would produce the same effect in SQL Server). This data type is mostly equivalent to the C#' double or the .NET Framework's System.Double data type. The .NET Framework database equivalent to this data type is the SqlDecimal class.

float and real: A floating-point number is a fractional number, like the decimal and numeric types. Floating-point numbers can be used if you would allow the database engine to apply an approximation to the actual number that a field is supposed to carry. This is mostly equivalent to the C#' float or the .NET Framework's System.Single data type. As you may be aware when using float, this data type doesn't offer good precision. The .NET Framework database equivalent to this data type is the SqlDouble class.

money: As its name announces it, the money data type can be used on a column whose data would consist of currency values. A field with a money data type can hold positive or negative values from -922,337,203,685,477.5808 to +922,337,203,685,477.5807

The .NET Framework database equivalent to this data type is the SqlMoney class.

smallmoney: While the money data type can be used for a field that would hold large quantities of currency values, the smallmoney data type can be applied for a column whose value cannot be lower than -214,748.3648 nor higher than 214,748.3647

The .NET Framework database equivalent to this data type is the SqlMoney class.

char: A field of characters can consist of any kinds of alphabetical symbols in any combination, readable or not. If you want a column to hold a fixed number of characters, such as the book shelf numbers of a library, apply the char data type for such a column. This is equivalent to the C#' char type of the .NET Framework's System.Char data type except that the SQL's char type is suitable if all fields of a column would have the same length. The .NET Framework database equivalent to this data type is the SqlString class.

varchar: Like the string is in C# and most other languages, the varchar data type is the most common data type of SQL. It represents a string. This means that it can be used on any column whose values you cannot predict. In fact, it is the default data type of any column created in the New Table window of SQL Server Enterprise Manager or the dbo.Table1 window of Visual Studio .NET. Use this data type wherever you would use a String value. The maximum length of text that a field of varchar type can hold is equivalent to 8 kilobytes.  The .NET Framework database equivalent to this data type is the SqlString class.

text: The text data type can be applied to a field whose data would consist of ASCII characters. As opposed to a varchar type of field, a text type of field can hold text that is longer than 8 kilobytes. The .NET Framework database equivalent to this data type is the SqlString class.

nchar, nvarchar, and ntext: These three types follow the same rules as the char, varchar, and text respectively, except that they can be applied to columns that would hold international characters, that is, characters of languages other than US English. This is done following the rules of Unicode formats. The .NET Framework database equivalent to these data types is the SqlString class.

datetime: As its name suggests, a datetime data type is used for a column whose data would consist of date and/or time values. The entries must be valid date or time values but SQL Server allows a lot of flexibility, even to display a date in a non-traditional format. The date value of a datetime field can be comprised between January 1st, 1753 and December 31, 9999. This data type is equivalent to the .NET Framework's DateTime data type. The .NET Framework database equivalent to this data type is the SqlDateTime class.

smalldatetime: The smalldatetime is an alternative to the datetime data type. It follows the same rules and principles as the datetime data type except that a date value must be comprised between January 1st, 1900 and June 6, 2079. This data type is equivalent to the .NET Framework's DateTime data type except that this one's date ranges are smaller. Whenever in doubt, use the datetime type (or the varchar). The .NET Framework database equivalent to this data type is the SqlDateTime class.

The Length of Data

One way you can tune your database is to control the amount of text entered in a column's 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.

Most columns use a default length. The only type you should think of changing the length of data is if the column is character (char) or string-based (varchar): You should not touch the others.

To specify the length of a column, if you are using the New Table window from SQL Server Enterprise, or the dbo.Table1 window from Microsoft Visual Studio .NET, you can enter the desired number in the Length box that corresponds to the column.

If you are creating a SQL statement, after typing the name of the type, type the opening parenthesis, followed by the desired number, followed by the closing parenthesis.

The rules of Length columns are:

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. 

Practical Learning Practical Learning: Creating a Table

  1. To create a new table, change the Notepad file as follows:
     
    Imports System
    Imports System.Data.SqlClient
    
    Module Exercise
    
        Public Sub Main()
            Dim strCreate As String = "CREATE TABLE Continents(" & _
                     "ContinentName varchar(100)," & _
                     "Area bigint," & _
                                    "Population bigint)"
    
            Dim conDatabase As SqlConnection = New _
    SqlConnection("Data Source=(local);Database='Countries';Integrated Security=yes;")
            Dim cmdDatabase As SqlCommand = New SqlCommand(strCreate, conDatabase)
    
            conDatabase.Open()
    
            cmdDatabase.ExecuteNonQuery()
            conDatabase.Close()
    
        End Sub
    
    End Module
  2. Save the file and return to the Command Prompt
  3. At the Command Prompt, compile the file and execute it
  4. Return to Notepad
  5. To create another table, change the file as follows:
     
    Imports System
    Imports System.Data.SqlClient
    
    Module Exercise
    
        Public Sub Main()
            Dim strCreate As String = "CREATE TABLE Countries (" & _
                         "CountryName varchar(120)," & _
                         "Continent int," & _
                         "Area bigint," & _
                         "Population bigint," & _
                         "Capital varchar(80)," & _
                         "Code char(2))"
    
            Dim conDatabase As SqlConnection = New _
    SqlConnection("Data Source=(local);Database='Countries';Integrated Security=yes;")
            Dim cmdDatabase As SqlCommand = New SqlCommand(strCreate, conDatabase)
    
            conDatabase.Open()
    
            cmdDatabase.ExecuteNonQuery()
            conDatabase.Close()
    
        End Sub
    
    End Module
  6. Save the file and return to the Command Prompt
  7. At the Command Prompt, compile the file and execute it
  8. Return to Notepad

Table Maintenance

 

Renaming a Table

If you have a table whose name is not appropriate, you can change its name. Before renaming a table, make sure this is what you want to do and make sure you can take care of it in your code. If you rename a table, Microsoft SQL Server would take care of updating it. To rename a table with code, Transact-SQL provides sp_rename. (Notice that the name starts with sp_. This is called a stored procedure. We will learn how to create them. For now, we can use them exactly as you have learned to use functions in C#: You don't need to know how they work but you can trust that they work and do what they are supposed to do).

To rename a table, use the following call:

EXEC sp_rename 'ExistingName', 'NewName'

The EXEC sp_rename expression is required. The ExistingName factor is the name of the table you want to rename. The NewName factor is the name you want the table to have after renaming it.

To rename a table at the MSDE prompt, make sure you are in the appropriate database first. Then use the above formula. Here is an example:

USE CarRentalDB
GO
EXEC sp_rename 'CarsFrom1996To2000', 'CarsToRetire'
GO

To rename a table in a C# code, pass the sp_rename code as string to a SqlCommand object and call the SqlCommand.ExecuteNonQuery() method.

 

Deleting a Table

If you have a table you don't need in your database, you can delete it. Before performing this operation, you should make sure you are familiar with the role of the table. For example, when you create a database in Microsoft SQL Server, the database system creates some tables necessary for internal use. You should not make any attempt to delete any of these tables. In fact, you should try to delete only a table you know you have created and you don't need anymore. If you work in a team environment and you find a table that may have been created by someone else, you should enquire before deleting it.

The SQL code used to delete a table uses the following formula:

DROP TABLE TableName

The DROP TABLE expression is required and it is followed by the name of the table as TableName. Here is an example:

DROP TABLE FriendsOfMine
GO

If you are working from C# code, create a DROP TABLE TableName expression and pass it to a SqlCommand object before calling the SqlCommand.ExecuteNonQuery() method.

It is extremely important to know that, when working with the DROP TABLE TableName statement, you would not receive any warning.

 

Columns Maintenance

 

Adding a Column

After creating a table or when using any existing table, you may find out that a column is missing. You can add a new column to a table if necessary.

To add a new column to an existing table, the formula to use is:

ALTER TABLE TableName ADD NewColumnName DataType Options

When using this statement, the ALTER TABLE expression and the ADD keyword are required. You must specify the name of the table that the new column will belong to. This is done using the TableName factor in our formula. Specify the name of the new column in the NewColumnName placeholder of our formula. On the right side of the NewColumnName placeholder, specify the options in the same way we described for columns.

If you are working from a C# code, create an ALTER TABLE expression and pass it to a SqlCommand object before executing it. Here is an example:

Imports System
Imports System.Data.SqlClient

Module Exercise

    Public Sub Main()
        Dim conDatabase As SqlConnection = _
  New SqlConnection("Data Source=(local);Database='Countries';Integrated Security=yes;")
        Dim cmdDatabase As SqlCommand = _
         New SqlCommand("ALTER TABLE Countries ADD TypeOfGovernment varchar(100)", _
          conDatabase)
        conDatabase.Open()

        cmdDatabase.ExecuteNonQuery()
        conDatabase.Close()

    End Sub

End Module
 

Renaming a Column

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

The code to rename a column uses the following formula:

EXEC sp_rename 'ExistingName', 'NewName', 'COLUMN'

The EXEC sp_rename expression and 'COLUMN' are required. The ExistingName factor is the name of the column you want to rename. The NewName factor is the name that will replace the existing name.

To rename a column at the MSDE prompt, you can use code as follows:

USE CarRentalDB
GO
EXEC sp_rename 'CarsToRetire.AC', 'HasAirCondition'
GO

To rename a table in a C# code, pass the sp_rename code as string to a SqlCommand object and call the SqlCommand.ExecuteNonQuery() method. Here is an example:

Imports System
Imports System.Data.SqlClient

Module Exercise

    Public Sub Main()
        Dim strConnection As String = "sp_rename 'Countries.Code', 'InternetCode', 'COLUMN'"
        Dim conDatabase As SqlConnection = New _
         SqlConnection("Data Source=(local);Database='Countries';Integrated Security=yes;")
        Dim cmdDatabase As SqlCommand = New SqlCommand(strConnection, conDatabase)

        conDatabase.Open()

        cmdDatabase.ExecuteNonQuery()
        conDatabase.Close()

    End Sub

End Module

Deleting a Column

If you have a column you don't need, you can remove that column from the table.

The formula to delete a column is:

ALTER TABLE TableName DROP COLUMN ColumnName

In this formula, the ALTER TABLE and the DROP COLUMN expressions are required. The TableName factor is the name of the table that owns the column. The ColumnName factor is the name of the column to be deleted.

To programmatically remove a column, create an ALTER TABLE statement using the above formula, pass the statement as string to a SqlCommand object before executing it.

 

Previous Copyright © 2005-2016, FunctionX Next