Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
ASP .NET Database Programming Weekend Crash Course - J. Butler, T. Caudill.pdf
Скачиваний:
31
Добавлен:
24.05.2014
Размер:
3.32 Mб
Скачать

S E S S I O N

5

Using SQL: A Primer

Session Checklist

Understanding the usefulness of SQL

Writing SELECT, INSERT, UPDATE, and DELETE SQL commands

After you have built a database, whether it be SQL Server or Oracle or Access, a time will come when you need to do something with it, more than likely retrieve and modify data. When dealing with data in a database, it turns out that there are four

actions you will most frequently perform: create, retrieve, update, and delete. Collectively these activities are referred to as CRUD. If someone, probably a manager, asks you for a CRUD diagram they are simply asking for a diagram representing what commands or actions you execute against the data store.

In order to execute CRUD commands against a relational database, you need to use Structured Query Language or SQL (pronounced sequel). SQL, as a querying language, is composed of a series of statements and clauses, which, when combined, perform different actions. In this session, we will address the most common SQL commands, INSERT, DELETE, UPDATE, and SELECT, and their related clauses. In order to demonstrate the use of SQL, you will execute commands against the Music database discussed in the previous session. So, if you haven’t already done so, please create the Music database.

INSERT Statements

Now that you’ve designed and constructed a database, it’s time to use it or have someone else use it. To make a database useful, it needs to contain some data. The SQL command to add data to a database is INSERT. The basic INSERT statement adds one row at a time to a table. Variations of the basic INSERT statement enable you to add multiple rows by selecting data from another table or by executing a stored procedure. In all of these cases, you must

know something about the structure of the table into which you are inserting data. The following information is useful:
The number of columns in the tableThe data type of each column
The names of the columns
Constraints and column properties
Following is the syntax for a basic INSERT statement:
INSERT INTO tablename [(columnname, ...)] VALUES (constant, ...)
where tablename represents the name of the table into which you want to insert data, columnname represents the name of the column into which you insert a specific piece of data, and constant represents the data you want to insert.
For example, if you wanted to add a music type to the t_music_type table in the Music database, you would write the following statement:
INSERT INTO t_music_types (music_type_title) VALUES (‘Rock and Roll’)
In plain English, this translates into, “insert a record into the t_music_types table and set the music_type_title field equal to the string Rock and Roll.”
If you’ll recall, the t_music_types table contains two columns: (1) music_type_id and
(2) music_type_title. However, the previous INSERT statement only inserts data into the music_type_title column. That’s because the music_type_id column is an IDENTITY column, which means that whenever a new row is added to the table, a unique identity value is automatically inserted into the music_type_column column. When executing an INSERT command, you must provide a field name/expression pair for each column that has not been assigned a default value and does not allow NULL values.
Let’s try another insert statement:
INSERT INTO t_record_companies (record_company_title) VALUES (‘Atlantic Records’)
Now write an INSERT statement that’s a little more involved. You’re going to add a band to the t_bands table, which changes the number of columns of the t_bands table to four, two of which are foreign keys. The music_type_id column is a foreign key to the t_music_type_id field in the t_music_types table, and the record_company_id column is a foreign key to the record_company_id field in the t_record_companies table. This means that you must insert values into these two columns that have corresponding values in their foreign key column. Assume that in the t_record_companies table, “Atlantic Records” has a record_company_id value of 1. Assume the same thing for “Rock and Roll” in the t_music_types table. So the insert statement for the t_bands table should look like this:
INSERT INTO t_bands (band_title, music_type_id, record_company_id) VALUES (‘Hootie & The Blowfish’,1,1)
Notice that you enclosed the band_title value, but not the music_type_id and record_company_id values, in single quotes. This is why you need to know the data types

48

Saturday Morning

Session 5—Using SQL: A Primer

49

of the columns into which you are inserting data. If the column into which you are inserting is of a numeric data type, you do not enclose the value in single quotes, however if you are inserting character data, you need to enclose the value in single quotes. Try running this statement:

INSERT INTO t_bands (band_title, music_type_id, record_company_id) VALUES (‘Toad The Wet Sprocket’,’1’,’1’)

You should get an error when executing this command because you are attempting to insert character data into columns that expect numeric data. Here’s the correct INSERT statement:

INSERT INTO t_bands (band_title, music_type_id, record_company_id) VALUES (‘Toad The Wet Sprocket’,1,1)

DELETE Statements

The DELETE command removes a row or multiple rows from a table. Following is the syntax for a basic DELETE statement:

DELETE FROM tablename [WHERE where expression]

Executing a DELETE statement that does not contain a WHERE clause removes all the records from a table. This is generally not what you want to do, so be careful when executing DELETE statements. Here’s an example:

DELETE FROM t_albums

This previous statement will delete all records from the t_albums table.

The WHERE clause is used to narrow the scope of our DELETE statement by specifying criteria that identify the records to delete. Here’s an example:

DELETE FROM t_albums WHERE band_id = 1

Assuming Hootie & The Blowfish have a band_id of 1 in the t_bands table, all of Hootie’s albums will be removed from the t_albums table.

The WHERE clause can consist of one expression as demonstrated with the previous DELETE statement or a series of expressions separated by Boolean operators. The Boolean operators most commonly used are AND, OR, and NOT. When using these operators together, precedence rules determine the order in which they’re evaluated. When the WHERE clause consists of statements enclosed in parentheses, the expressions in parentheses are examine first. After the expressions in parentheses are evaluated, the following rules apply:

NOT is evaluated before AND. NOT can only occur after AND. OR NOT isn’t allowed.

AND is evaluated before OR.

Let’s try it out . . .

DELETE FROM t_bands WHERE band_title = ‘Hootie & The Blowfish’ AND record_company_id = 100

50

Saturday Morning

The previous statement will delete all rows from the t_bands table where the value in the band_title column is equal to Hootie & The Blowfish and the value in the record_ company_id field is 100. Based on the data we inserted earlier, no record should be deleted from the t_bands table. There is a record that where band_title equals Hootie & The Blowfish, but that record has record_company_id value of 1. Let’s try an OR . . .

DELETE FROM t_bands WHERE band_title = ‘Toad The Wet Sprocket OR record_company_id = 100

This statement will delete all rows from t_bands table where the value in the band_title column is equal to Toad The Wet Sprocket or the value in the record_company_id field is

100. So based on our sample data, one row should be deleted from the t_bands table because there is one row that contains Toad The Wet Sprocket in the band_title column, but no rows contain a record_company_id value of 100.

A WHERE clause can also contain something called a predicate. A predicate is a expression that makes a factual assertion about a column value. Some common examples of predicates are CONTAINS, LIKE, and NULL. CONTAINS returns true if the value in the specified table contains a specified value. LIKE returns true if the specified column’s data matches a specified string pattern.

Note

A string pattern can contain wildcard characters such as the percent sign (%), which matches one or more characters, and the underscore (_), which matches one character.

NULL determines whether a column contains data. Let’s try it out:

DELETE FROM t_bands WHERE CONTAINS (band_title,’Toad’)

This statement means, “delete all rows from t_bands where band_title contains Toad.” Let’s try another:

DELETE FROM t_bands WHERE band_title LIKE ‘Toad%’

Note

In SQL Server, the % is referred to as a wildcard character. The % wildcard character matches any string of zero or more characters. So placing % in our previous delete statement instructed SQL Server to delete all records in the t_bands table where the value in the band_title column begins with “Toad.”

UPDATE Statements

The UPDATE statement enables you to change the data within existing rows. Following is the syntax for a simple UPDATE statement:

UPDATE tablename SET columnname = contstant [AND columnname = constant ...] [WHERE where-expression]