Home > Articles > Data > SQL Server

  • Print
  • + Share This

Using the Data Definition Language (DDL) to Create Databases and Objects

With the new features of Query Analyzer, getting the basic outline of the common database objects that you need to create is very easy. With a couple of mouse clicks and some fill-in-the-gaps programming, you can have a database created in only a couple of moments.

The important part of this process though is what to put in the gaps. Understanding how a CREATE DATABASE statement is built is just as important (if not more) than just entering the code.

In this section we will go through the CREATE DATABASE statement rather than use the templates that SQL Server 2000 provides.

First though we need to clarify a couple of points about SQL. As I said earlier, SQL is a standard language for manipulating data and databases. It is based on mathematical set theory. But two distinct parts exist to SQL—the Data Definition Language (DDL) and the Data Manipulation Language (DML).

DDL is used to create database objects and define how the data will look in the database. For example, through the DDL we can not only create databases, tables, views and so on, but we can also delete them (as in the previous example). It is easy to spot the DDL because the SQL statement usually begins with CREATE, ALTER, or DROP.

DML is used to manipulate the data within a database. For example, through the DML we cannot only insert new rows of data but we can also delete them (as in the previous example). It is easy to spot the DML because the SQL statement usually begins with SELECT, INSERT, UPDATE, or DELETE.

With this in mind, if you look at the Transact-SQL statement that we entered to delete our database, you will see that it is a mixture of DDL and DML. The DROP statement in line 4 is DDL and the SELECT statement in line 3 is DML.

We now have an idea of what DDL and DML are. Let us create our SQLSpyNet database (once again) with a Transact-SQL DDL statement and really get this show on the road!

The CREATE DATABASE statement is a complex beast and has many parameters that you can specify. Because of the limitations of this book (namely size!), we are only going to cover the options that are the most relevant to us. The code in Listing 3.2 will re-create our SQLSpyNet database for us.

Listing 3.2—Creating Our SQLSpyNet Database Through Transact-SQL Code

1:USE master
3a:ON PRIMARY (NAME = 'SQLSpyNet_Data',
3d:SIZE = 5MB,
3e:FILEGROWTH = 10%)
4: LOG ON (NAME = 'SQLSpyNet_Log',
4c:SIZE = 5MB,
4d:FILEGROWTH = 10%)

You will need to replace the x:\ with the path on which you would like to create the data file and transaction log.

Tip - To get the file path that your previous database used, copy the file paths that you saved earlier. If you didn't save them, you will need to enter them where the x:\ is.

After you have entered the file paths you can run the code. SQL Server 2000 will return at least two messages similar to the following:

1: The CREATE DATABASE process is allocating 5.00 MB on disk 'SQLSpyNet_Data'.
2: The CREATE DATABASE process is allocating 5.00 MB on disk 'SQLSpyNet_Log'.

Let's examine the code that you have entered.

  • Line 1 specifies to Query Analyzer that it switch to the master database.

  • Line 2 forces the execution of the code in line 1. Use the GO command whenever you would like code to be fired immediately instead of waiting until the whole block is executed. This is a unique feature of all versions of SQL Server. Some other RDBMSs use a semicolon (;) to execute a block of code immediately. Through different options we can change this, but we don't really need to unless using code from another RDBMS.

  • Line 3 is the actual DDL that creates the database. The only parameter required is the database name. We could create a database by only specifying a name. Unfortunately though, this does not allow us enough flexibility.

  • Line 3a specifies the filegroup (PRIMARY, the default) that will be used and the data filename. The bracket denotes the beginning of the data file parameters. The NAME = allows you to set the name that SQL Server 2000 will use to refer to the data file for this database.

  • Lines 3b and 3c specify the location of the data file.

  • Lines 3d and 3e specify the initial size of the data file and the size by which it grows. If you leave off the % sign, the file growth size will be in MBs (the default). The end bracket denotes the end of the data file parameters.

  • Line 4 specifies the transaction log parameters. The bracket denotes the beginning of the transaction log parameters. The NAME = allows you to set the name that SQL Server 2000 will use to refer to the transaction log for this database.

  • Lines 4a, 4b, 4c and 4d—These parameters are the same as they are for the data file (see previous).

  • Line 5 executes the previous Transact-SQL block from the last GO statement; that is, everything from CREATE DATABASE down.

If you now refresh your Databases folder in Enterprise Manager or Object Browser in Query Analyzer, you will see the SQLSpyNet database. Now I am sure a smart person like yourself found that easy, didn't you?

Just perform a quick check on your newly created database (by looking at the database properties, remember? If not look at "The Properties Tab," earlier in this chapter.), and make sure the options for the database fit our needs that we specified earlier. If you find any discrepancies, make the necessary changes.

As I mentioned earlier, we can specify many other parameters when creating a database through Transact-SQL code. We can specify that the database is for data loading only, the collation to be used, and the filegroups that the database will use. As you can see, developing a database through Transact-SQL code is very flexible but definitely a little harder than using the UI through Enterprise Manager.

We will now briefly look at tables and discuss some more database concepts.

Building Tables for Our Spies

Tables are the key to all databases. They enable us to store related information for retrieval at a later stage. Without tables we would not be able to store and retrieve the information that is so critical to our databases, so we wouldn't have a database!

A table will allow us to store a spy's name, address, date of birth, and so on, but we can also store the activities that our spies are involved in.

Tables can be related to each other, unrelated, or only used on a temporary basis. They are very flexible, and a well-designed table will help to ensure that information is stored accurately and concisely.

Three main types of tables are used within SQL Server 2000:

  • User-defined tables—Developers who want to store user-defined information (such as a spy's details) within a table create these. They are easily identifiable in SQL Server 2000 Enterprise Manager because their type is defined as User. Within the Object Browser in Query Analyzer, they are listed in a separate folder named User, under the main Tables folder.

  • System tables—These are used by the internal workings of SQL Server 2000 to manage the database objects. They are characteristically identifiable by the "sys" naming convention; for example, sysobjects. This table contains a list of database objects within a database.

  • Temporary tables—As the name suggests, these tables are created only on a temporary basis. They are characterized by the hash (#) symbol in front of their names. Different types of temporary tables have different levels of scope.

This gives you a brief overview of the tables that are available in SQL Server 2000. We will work with them more as we develop the SQL Spy Net application further.

But why have tables? Tables are modeled on real-world objects (people, spies, bad guys) and events (activities). We have already seen this with the ERD we partially designed earlier, in Chapter 1.

But tables that are not related provide us with few benefits. We might as well have a data file on a single PC! Defining a relationship between our tables is the key to having an effective and informative data store.

We can implement relationships between tables that model the relationships in a real-world scenario. For example, a spy can battle a bad guy to prevent world domination. We can then model and implement this relationship in our database to represent what happens when a spy battles a bad guy.

Note - Of course, all this spy business might not seem too practical when you're ready to work with a real-world client, unless you're working for military intelligence! But, everything we discuss here applies to business relationships such as salespeople to customers, customer address information, and dates and items in sales data, for example. But then, you'll have the rest of your career to create good ol' boring sales records, so enjoy the fun while you can. I'll let you decide who the "bad guys" are in your world.

Relationships also help us enforce integrity of our data. After we define a relationship, through primary and foreign keys, we can specify that in the table that has the foreign key (the child), it can only contain a row of data if a value exists in the parent table (we will prove this after we have built our tables).

This prevents us from entering a spy in our Spy table without them first existing in the Person table.

Revisiting the Analysis of the SQL Spy Net Application

So far in our application development we have decided to implement the Spy table and the BadGuy table as subtypes of a person table. We have also implemented the Activity table as an associative table between the Spy and BadGuy tables.

Well what about the rest of the application? Because as I stated earlier, this book is about SQL Server 2000 not analyzing requirements, I will give you the rest of the ERD without boring you too much about the details. However, I will endeavor to explain the ERD, as shown in Figure 3.15, so you have an overview of the application.

Figure 3.15
Final ERD of the SQLSpyNet database.

As you can see, the ERD for the whole application is relatively simple. It contains only a few tables. We have defined the spies and the bad guys to be subtypes of the person entity.

As discussed earlier (in Chapter 1), this allows us the greatest flexibility for adding to our application. If we need an employee entity, creating an employee subtype is a simple process of creating an employee subtype.

The important factor to note is how the bad guys and the spies relate to each other. A spy is only given an assignment if a bad guy is wrecking havoc on the world, so this is their relationship.

In a lifetime, a spy can be involved in foiling one or more bad guy's plans, and a bad guy can be involved in one or more dastardly deeds. So we have a many-to-many relationship.

Because this cannot be implemented in a relational database, we need an associative entity. So we introduce the Activity entity. This keeps track of the bad guys that a spy has fought, as well as the plans that they have foiled.

The ActivityType entity allows us to enter a list of evil plans that the bad guys hatch. These plans could include (and most probably will) taking over the world! They could wreck havoc and generally cause a disturbance among the citizens.

The Address entity is only used to track the addresses of a person. Because it is possible for a person to have more than one address, we have broken it out into another table, thus reducing repeating rows in our person table and enabling our data model (ERD) to conform to 1NF.

1NF is First Normal Form, which is the first level of normalization (see the Excursion "1NF, 2NF, 3NF, 4!"). Basically, a table must not contain a list of values in any single column (that is, a comma-delimited list of values), and there must be no repeating groups.

1NF, 2NF, 3NF, 4!

Normalization is derived from the study of relational theory and was developed by E.F. Codd, the father of relational theory. It is the process of arranging tables and data within our database to reduce dependencies and inefficient structures as much as possible.

Normalization is linear in nature (each rule is applied after another rule is complete) and is used to define the best database structure that you can possibly achieve.

Six normal forms, or stages, are defined in the process of normalization. As mentioned, the rules of normalization are linear; therefore, the second rule depends on the first rule, the third rule depends on the second, and so on.

3NF is the level that most developers take their database applications to when normalizing their databases. Why? Most developers find that that third normal is sufficient to meet the requirements of the application and ensure data consistency.

Note - By removing repeating rows from our Person table, we have ensured that our table now conforms to First Normal Form (1NF).

As I referred to earlier, defining a data model is not the same for everybody, and having said this, this model will not suit some people. They might look at the model and decide that it has limitations, which it does. So I will now describe to you the limitations that are in place in the model.

  • A spy can work on only one assignment at a time. This means that we cannot schedule a spy to be fighting two or more bad guys (probably a good thing!). Likewise, a bad guy cannot be executing more than one plan at one time.

  • A person can have many addresses, but an address can belong to only one person. This means that communal sharing of housing is not recognized. To implement this we need to introduce either another entity (the correct way) or allowing repeating rows of information in the address table (naughty, naughty, naughty).

  • We can—and this is relatively serious, if we do not develop our business rules correctly—end up with the scenario of a person belonging to the spies group as well as the bad-guys group! To prevent this we implement domain constraints. These will prevent the incorrect values from being entered into either table.

Domain constraints enables us to limit the values that a column in a table will accept. We can specify a pool of allowable values for a given column. For example, if a value falls between the range of 1–10, then it can be entered, otherwise it will be rejected. As you may can imagine, this is a very powerful tool of database development.

That about wraps it up for the ERD for our application except, of course, for the actual column names within our tables, but we will create these as we develop the tables.

  • + Share This
  • 🔖 Save To Your Account

Related Resources

There are currently no related titles. Please check back later.