• Tidak ada hasil yang ditemukan

Directory listing of http: uap.unnes.ac.id ebook biblebook Visual Basic 6 com & Library Books

N/A
N/A
Protected

Academic year: 2017

Membagikan "Directory listing of http: uap.unnes.ac.id ebook biblebook Visual Basic 6 com & Library Books"

Copied!
28
0
0

Teks penuh

(1)

SQL Statement

Primer

I

n this c hapter, I’m go ing to sho w yo u so me o f the key SQL statements that yo u will be using when yo u develo p yo ur applic atio ns. These statements will allo w yo u to c reate tables, views, and indexes. The rest o f the statements c an be used to add, remo ve, c hange, and retrieve ro ws fro m yo ur database.

Using SQL Statements

A detailed kno wledge o f SQL isn’t nec essary fo r mo st pro -grammers. Ho wever, it will be impo ssible to write a database pro gram witho ut kno wing a little bit abo ut the language. The statements I’m go ing to c o ver in this c hapter apply to all o f the database systems that will be disc ussed in this bo o k.

SQL for Dummies: If you really w ant to learn m ore about the SQL language, read the book SQL for Dum m ies, 3rd Edition, by Allen G. Taylor. This is a good introduction to the SQL language and covers all of the essential elem ents of the language. More advanced users should refer to the database vendor’s docum entation for their extensions to the SQL language.

SQL statements

The SQL language c o nsists o f a series o f statements that per-fo rm spec ific tasks (see Table 4-1). There are statements to c reate databases and tables, statements to add and delete ro ws in a table, and statements to retrieve ro ws fro m a table o r set o f tables. There are o ther statements that deal with data sec urity and data integrity. These statements are c o nstruc ted ac c o rding to a set o f c o mplex rules that vary slightly fro m o ne database system to ano ther. Ho wever, fo r mo st users, these differenc es aren’t all that impo rtant.

(2)

Table 4-1

Some Common SQL Statements

Statement Name Description

Create Index Builds an index on a set of colum ns on a table.

Create Table Builds an em pty table in a database.

Create View Builds a view.

Delete Rem oves row s from a table.

Drop Index Deletes an index from a database.

Drop Table Deletes a table from a database.

Drop View Rem oves a view from a database.

Insert Adds row s to a table.

Select Retrieves row s from a table.

Update Changes the data values of one or m ore colum ns in the table.

Data definition language statements

The Cre ate Table, Drop Table , Cre ate Vie w, Drop Vie w Cre ate Inde x, and Drop Inde x statements are kno wn as Data De finitio n Language ( DDL) statements, while the Inse rt, De le te, Update, and Se le ct statements are kno wn as Data Manipulatio n Language ( DML) statements. In mo st database systems to day, yo u rarely exec ute DDL statements when yo u want to c reate a database struc ture. Instead, yo u use a utility supplied with the database system that allo ws yo u to fill in all o f the info rma-tio n into a table, o r yo u use a wizard that will help yo u c reate yo ur table o r index.

This do esn’t mean that the DDL statements aren’t used. It merely means that yo u enter the info rmatio n in a different fashio n. The database utility usually inc ludes a feature that will allo w yo u to generate the SQL statements fro m the definitio ns yo u entered. Then yo u might use these SQL statements to c reate a c o py o f the database o n ano ther c o mputer o r inc lude them in yo ur applic atio n if yo u want yo ur users to be able to c reate the database struc tures o n the fly.

SQL data types

(3)

Table 4-2

Some Common SQL Data Types

SQL Data Type Visual Basic Data Type Description

Char String A fixed-length string of characters. Date Date A value containing a date and tim e

value. (Available w ith Oracle only.) Datetim e Date A value containing a date and tim e

value. (Available w ith SQL Server only.) Decim al Currency An exact num eric value of the specified

size.

Float Double A 64-bit floating-point num ber. Int Long A 32-bit integer.

Money Currency An exact num eric value. (Available w ith SQL Server only).

Num ber Currency An exact num eric value. (Available w ith Oracle only.)

Real Single A 32-bit floating-point num ber. Sm allint Integer A 16-bit integer.

Varchar String Variable-length character string.

These data types c an be lo o sely gro uped into fo ur main types: exac t numeric values, flo ating po int values, string values, and date values. Mo st database servers also o ffer many o ther data types to c ho o se fro m.

For m ore detailed inform ation about the data types available in a particular database, see Chapter 23, “Overview of SQL Server,” Chapter 26, “Overview of Oracle 8i,” or Chapter 29, “Overview of Microsoft Jet.”

Exact numeric data types

Exact nume ric data type srepresent numb ers b y using an exac t value. These data types generally fall into two sub c lasses: inte ge r value sand packe d de cimal value s. Integer values sto re their numb ers as a b inary value. This o ffers mo re effic ient sto rage fo r large numb ers than when yo u use a pac ked dec imal value.

M oney, money, money: If you need to perform calculations using currency values, you should alw ays use an exact num eric data type.

(4)

Pac ked dec imal values sto re numbers as a string o f numeric digits. Fo ur bits are used to represent a value fro m zero to nine. Mo st database servers will allo w yo u to determine the number o f digits yo u want when yo u spec ify the data type.

The advantage o f exac t numeric values is that when yo u perfo rm arithmetic with them, yo u never lo se ac c urac y. This isn’t true with flo ating po int values.

Floating point data types

Flo ating po int data type srepresent numbers by breaking them into two piec es: a mantissaand an e xpo ne nt.Flo ating po int numbers are expressed in terms o f a value time 10 to so me po wer. Fo r instanc e, the value 12,345 is written as 1.234×105and

o ften displayed o n the c o mputer as 1.2345E5, where E means 10 raised to this po ser. In this example, the mantissa is 1.2345 and the expo nent is 5.

Bec ause o f the way they are sto red, flo ating po int numbers are o nly ac c urate to so many dec imal plac es. This allo ws yo u to represent very large numbers with muc h less sto rage than what wo uld be required if yo u sto red every single digit. Generally, single value shave abo ut five dec imal plac es o f ac c urac y, while do uble value sare ac c urate to abo ut ten dec imal plac es.

M aybe, maybe not: You’ll probably never need to use a floating point data type in your database, because m ost people don’t appreciate adding 1,000,000.02 + 0.01 and getting 1,000,000 because the floating point value stored only 5 digits of inform ation in the m antissa.

String data types

String data type sho ld c harac ter info rmatio n. There are two different types o f c harac -ter strings: fixe d-le ngthand variable -le ngth.The fixed-length strings always reserve the same amo unt o f spac e in a table whether yo u sto re o ne c harac ter in the c o lumn o r fifty. Variable-length strings, o n the o ther hand, sto re o nly the c harac ters yo u have in the string, plus so me additio nal info rmatio n that ho lds the length o f the string.

In general, yo u sho uld c ho o se variable-length strings o ver fixed-length strings. This tends to save spac e in yo ur database, espec ially if the amo unt o f data yo u sto re in the c o lumn varies signific antly fro m o ne ro w to the next. Using variable-length strings also allo ws yo u to c reate yo ur strings with a larger maximum size. This is useful in situatio ns where yo u may have an unusually large value that yo u do n’t want to trunc ate, suc h as a perso n’s name.

Fixed-length strings are go o d when the size o f eac h value remains relatively c o n-stant, as with a two -c harac ter abbreviatio n fo r a state o r a pro duc t identifier c o de. This is espec ially true fo r small strings where the extra o verhead to keep trac k o f the true length o f the string o c c upies mo re spac e then the string itself.

(5)

Date data types

Date data type sare almo st always unique to a partic ular database system. Even tho ugh there isn’t muc h c o mpatibility amo ng the database vendo rs’ implementa-tio ns, the alternatives are wo rse. Yo u c o uld allo c ate an eight-c harac ter string and use the first fo ur c harac ters fo r the year, the next two fo r the mo nth, and the last two fo r the year. Yo u c o uld also use an integer value to trac k the number o f days sinc e 1900 o r sinc e the day yo ur o rganizatio n was c reated.

Bo th o f these metho ds have a drawbac k: the lac k o f integrated suppo rt fo r the values by the database server. If yo u sto re yo ur date values as a c harac ter string instead o f a date data type, when yo u use an interac tive query to o l, all yo u’ll see is the raw, unfo r-matted value. When using these values with Visual Basic , yo u’ll have to manually c o n-vert yo ur values to and fro m a Datevariable in o rder to take advantage o f the wide range o f date and time func tio ns already inc luded in Visual Basic . In the lo ng run, using the supplied date data types fro m the database server is a muc h better idea.

Testing SQL statements

One o f the advantages o f SQL is that the same language c an be used interac tively o r embedded in yo ur applic atio n. This means that yo u c an c o de and test yo ur SQL statements using an interac tive query to o l and then add them to yo ur pro gram. While the query to o ls differ depending o n the database system yo u’re using, they all do the same thing. Yo u enter yo ur statement and c lic k o n a butto n to exec ute it. The results will then be displayed o n yo ur c o mputer.

Fo r the examples in this c hapter, I’m go ing to use the SQL Server database and the Query Analyzer to o l to run the queries against the bo o k’s sample database. Ho wever, o nc e yo u c reate and lo ad the sample database in yo ur database system o f c ho ic e, yo u will be able to use the c o rrespo nding query to o l to run the same examples.

The Select statement

Of the statements in the SQL language, the Se le ct statement is the mo st c o mmo nly used. Its purpo se is to identify the ro ws yo u want to retrieve fro m the database.

Here is the syntax fo r this statement:

Select [<selectoption>]<selectexpression> [,<selectexpression>]...

From <tableref> [, <tableref>] ... [Where <expression>]

(6)

where

<selectoption> ::= All | Distinct | Top <number>

<selectexpression> ::= * | <selectitem> [ [As] <alias> ] <selectitem> ::= <column> | <table>.<column> |

<function> ( [Distinct]<expression> ) | <expression> <function> ::= Count | Max | Min | Sum

and

<alias> is an alternate name of a column or table. <expression> is a valid expression.

<number> is a valid number.

The Se le ctstatement is the mo st c o mplic ated statement in SQL. The abo ve syntax represents o nly a small part o f the full Se le ctstatement syntax. Ho wever, yo u will rarely need anything beyo nd these c lauses when building yo ur applic atio n. A Se le ct

statement is c o mpo sed o f a series o f c lauses, suc h as From, Whe re, and so o n. Only the Fromc lause is required. I’m go ing to disc uss ho w the basic Selec t statement wo rks, and then disc uss eac h o f the c lauses that wo rk with it.

Simple Select statements

To use a Se le ct statement, all yo u need to do is identify the table and the c o lumns yo u want to retrieve fro m the database. Immediately fo llo wing the Se le ctkeywo rd is the list o f c o lumns yo u want to retrieve, and the Fromc lause spec ifies the name o f the table yo u want to ac c ess.

Retrieving all columns

The fo llo wing statement retrieves all o f the c o lumns fro m the Custo mers table in the sample database yo u’ll find in the CD-ROM:

Select *

From Customers

(7)

Figure 4-1: Running a sim ple query to retrieve all colum ns from the Custom er table

(8)

Selecting a subset of a table

Returning an entire table is no t terribly useful in an applic atio n pro gram. Typic ally, yo u will want to retrieve o nly a single ro w o r a handful o f ro ws that are related to so me o ther value. This is where the Whe rec lause c o mes into play. The Whe re

c lause allo ws yo u to spec ify a searc h expressio n that identifies the set o f ro ws yo u want to return.

Where oh where is my favorite clause: If the Selectstatem ent is the m ost com -m only used state-m ent in the SQL language, the Where clause is the m ost com m only used clause. It is used in a num ber of other statem ents, including the Deleteand Updatestatem ents.

Using simple search expressions

The tric k to using a Whe re c lause is to c reate a searc h expressio n that will o nly return the ro w o r ro ws yo u want. Fo r instanc e, let’s assume that yo u want all o f the info rmatio n abo ut a c usto mer 431. The info rmatio n is sto red in the Custo mers table. Thus, the searc h expressio n CustomerId = 431wo uld retrieve all o f this info rmatio n. Sinc e Custo merId c o lumn is the primary key fo r the Custo mers table, o nly a single ro w will be returned by the fo llo wing Se le ctstatement ( see Figure 4-3) :

Select *

From Customers

Where CustomerId = 431

Searching for expressions with all the wrong operators: SQL supports all of the sam e operators that Visual Basic includes (= , < , > , < = , > = , < > , Not, And, and Or) to m ake it easy to build an expression. SQL also supports a few other operators, such as In(discussed in Nested Queries below ) and Like,w hich is used to m atch a specified pattern, and w hich m ay include w ild card characters. Of course, paren-theses m ay also be used to ensure that the expression is evaluated properly.

Only tho se ro ws c o ntaining a Custo merId value o f 431 will be returned. Sinc e Custo merId is the primary key o f this table, yo u kno w that eac h value o f Custo merId is unique, so at mo st, o ne ro w will be returned. No te that if yo u spec ify a value fo r Custo merId that isn’t in the table, no ro ws will be returned.

(9)

Figure 4-3: Selecting inform ation about Custom erId 431

(10)

M ore complex search expressions

Searc h expressio ns c an be as c o mplic ated as yo u want. Yo u c an use And, Or,and

Not to c o mpile multiple simple expressio ns to gether to narro w the searc h. The fo l-lo wing Se le ctstatement returns all o f the c usto mers who were added to the database sinc e 1999 and who also live in Califo rnia ( see Figure 4-5) :

Select *

From Customers

Where State = “CA” And DateAdded >= “1-January-1999”

Figure 4-5: Retrieving all the custom ers living in California w ho w ere added since 1999

Waiting for it to end:Alw ays try to include at least one colum n in your search expression that is part of an index. Otherw ise, the database server w ill have to search through every row in the table to find the row s you w ant. While searching the w hole table can be fairly quick for sm all tables, it can take a long tim e for large tables.

(11)

Sorting results

By default, the Se le ct statement do esn’t return ro ws in any partic ular o rder. In many c ases this isn’t a pro blem, but if yo u want to display these ro ws to the user, yo u might find it benefic ial to so rt them befo re they’re displayed with the Orde r By

c lause.

Orde r Byfo llo ws the Whe rec lause and inc ludes the list o f c o lumns that yo u want to use to so rt the results. If yo u fo llo w a c o lumn name with the key Asco r De sc, that partic ular c o lumn will be so rted in asc ending o r desc ending o rder, respec -tively. If yo u do n’t spec ify either keywo rd, the data will be so rted in asc ending o rder. In the statement belo w, I’m go ing to retrieve all o f the c usto mers who live in No rth Caro lina and so rt them by their name ( see Figure 4-6) :

Select *

From Customers

Where State = “NC”

Order By Name

(12)

No te that sinc e the data in the Name field is sto red first name then last name, the results are so rted by the perso n’s first name.

For m ore inform ation about foreign keys and keys in general, refer to Chapter 2, “Indexes and Keys.”

Using multiple tables

The Se le ctstatement allo ws yo u to c o mbine info rmatio n fro m multiple tables into a single “virtual table.” This “virtual table” c an’t be updated, but it makes it easier when yo u need to c o llec t info rmatio n yo u want to display in yo ur applic atio n.

Join operations: The technical term for com bining the row s and colum ns in tw o or m ore tables is know n as a join operation.

The wrong way to use two tables

The Se le ct statement allo ws yo u to spec ify a list o f tables in the Fromc lause. Ho wever, the results are pro bably no t what yo u wo uld expec t. Co nsider the fo llo w-ing tables. Eac h table has three ro ws, with two c o lumns in eac h ro w. Eac h letter represents a spec ific value in a partic ular c o lumn.

Table A: {{A, I}, {B, J}, {C, K}} Table B: {{X, I}, {Y, J}, {Z, K}}

If yo u spec ify two tables in the From c lause, the Se le ctperfo rm wo uld lo o k like this and yo u’ll get the fo llo wing result:

Select *

The right way to use two tables

Generally when you want to use two tables, it is because the two tables are related to each other. This means that the tables have one or more columns in common. These columns could be part of a foreign key relationship. Suppose that Table A and

(13)

Table B have the Column2 in common, which is the second column

in each table. Then the following Select statement would allow

you to join the two tables together based on the rows that have a common value in their second column:

Select *

From A, B

Where A.Column2 = B.Column2

This Se le ctstatement wo uld then generate the fo llo wing result:

{{A, I, X, I}, {B, J, Y, J}, {C, K, Z, K}}

No te that even tho ugh Co lumn2 values are identic al, they are repeated twic e bec ause the ro ws were appended to eac h o ther. Also , if yo u lo o k bac k at the previ-o us set previ-o f results, yprevi-o u will find these three rprevi-o ws buried. The Whe re c lause merely filtered o ut the ro ws where the values in Co lumn2 didn’t matc h.

Equijoins: A join that uses the Whereclause to m atch colum n values in different tables is know n as an equijoin,w hich is short for equality join.

Resolving column names

In the abo ve example, I had two tables with the same c o lumn name. In o rder to kno w whic h c o lumn is asso c iated with whic h table, it is nec essary to qualify the c o lumn name by using the table name, as sho wn in the example belo w:

Select LastName, StateName

From Customers, States

Where Customers.State = States.State

To make life easier, yo u may want to use table aliase s,whic h allo w yo u to define an alternate name fo r yo ur table. The table aliases are spec ified in the Fromc lause by fo l-lo wing the table name with the alternate name yo u want to use fo r the table. Perso nally, I prefer to use sho rt o ne- o r two -c harac ter abbreviatio ns fo r table aliases, but yo u c an c ho o se whatever size name yo u want. Using table aliases, I c an rewrite the previo us query as fo llo ws:

Select LastName, StateName

From Customers C, States S

Where C.State = S.State

No te that using table aliases c an sho rten the expressio n in the Whe rec lause. While this do esn’t save muc h in this partic ular example, it c an make a big differenc e in a very c o mplex Whe rec lause.

(14)

Nested queries

Of all the things yo u c an do with the Se le ctstatement, ne ste d que rie sare the mo st c o mplex. In a nested query, yo u use a sec o nd ( o r third o r fo urth) Se le ctstatement nested inside yo ur main statement. Typic ally, nested queries are used to return a set o f values that c an be used with the Ino perato r.

While this is fairly easy to write, imagine the pro blems yo u might have if yo u had a list o f 15 o r 20 different values to find. An alternative to writing a bunc h o f different c lauses is the In o perato r. The Ino perato r allo ws yo u to c o mpare a c o lumn against the Ino perato r. Co nsider the fo llo wing query, whic h answers the questio n, “Whic h c usto mers are in the same ZIP c o de as any o f the c usto mers that have been added

While this query is so mewhat c o ntrived, it gives yo u an alternate way to c reate a set o f values. Yo u may also think that this query is similar to the o ne listed belo w, but it isn’t:

Select Name, Zip

From Customers

(15)

Figure 4-7: Finding custom ers in m ultiple states

The two queries c o uld o nly be identic al if eac h ZIP c o de had o nly o ne c usto mer.

Complex to write, complex to debug: Nested queries often take a w hile to debug. The syntax errors w ill drive you nuts. I suggest that you avoid using them unless you can’t do the query any other w ay. Unfortunately, there are som e ques-tions that you m ight w ant to ask that can only be answ ered using nested queries.

Using functions

Yo u c an also inc lude vario us func tio ns in yo ur Se le ctstatement. Fo r instanc e, the fo llo wing Se le ctstatement c o unts the number o f Custo mers who live in the state o f Maryland ( see Figure 4-8) :

Select Count(CustomerId)

From Customers

Where State = “MD”

(16)

Figure 4-8: Counting the custom ers from Maryland

Other func tio ns that yo u c an use inc lude Min, Max,and Ave rage, whic h will c o m-pute the minimum, maximum, o r average o f a partic ular value ac ro ss all o f the ro ws selec ted fro m the database.

Not in my program, you don’t: You probably aren’t going to use functions in your application program . How ever, using functions in an interactive query program m ay help you decide if your program is w orking. You can use the Countfunction to determ ine the num ber of row s that you just added to your table, or you can use it to count the num ber of row s your program updated. Som etim es, just a quick check can help you identify if you actually processed all of the row s you thought you had.

Inserting Rows into a Table

The SQL Inse rtstatement is used to add o ne o r mo re ro ws to a table. Here is the syntax fo r this statement:

Insert [Into] <table> [(<column> [, <column>} ...])] [ Values

(<value> [,<value>]...) |

As <selectstatement> ]

(17)

where

<table> is the name of where you want to insert new rows. <column> is the name of a column in the table.

<value> is a value that you wish to insert into a column. <selectstatement> is a valid Select statement.

The Inse rtstatement adds a ro w into the spec ified table. Yo u c an spec ify a list o f c o lumns fo r whic h yo u will assign the values o r use the list o f c o lumns spec ified when the table was c reated. Yo u c an either explic itly spec ify the list o f values in the

Valuec lause o r use the As keywo rd to spec ify a Se le ctstatement that will retrieve fro m ano ther table. Like the Valuec lause, the c o lumns retrieved in the Se le ct state-ment must matc h up with the c o lumns spec ified after the table name.

Testing with copied data: When you are testing code that deletes or updates data in a table, it is often useful to create a tem porary table w ith a copy of your test data and use that table for your testing. This allow s you to easily refresh your data after your program deletes the w rong inform ation. Using the Insertstatem ent w ith the Asclause m akes this very easy to do.

A simple Insert statement

Here’s a very simple Inse rtstatement:

Insert Into Customers

(CustomerId, Name, Street, City, State, Zip, Phone, EmailAddress, DateAdded, DateUpdated, MailingList, Comments)

(18)

Figure 4-9: Adding a single row to the Custom ers table

The Inse rtstatement listed belo w is identic al to the previo us o ne, but it assumes that the o rder o f the c o lumns as defined in the database is the same as the o rder o f the data in the Valuec lause.

Insert Into Customers

Values (99999, “Christopher J. Freeze”, “1234 Main Street”, “Beltsville”, “MD”, 20705, “(800) 555-5555”,

“CFreeze@JustPC.net”, “1-January-2000”, “1-January-2000”, 1, “”)

To run once is good, to run twice is bad: Running this statem ent m ore than once w ill cause an error. Since the Custom erId field is the prim ary key for the table and each row m ust have a unique value, attem pting to add another row w ith the sam e value w ill cause an error.

(19)

Deleting Rows from a Table

The De le testatement is used to remo ve o ne o r mo re ro ws fro m a table. Here is the syntax fo r this statement:

Delete From <table> [Where <expression>]

where

<table> is the name of the database table from which you want to delete the rows.

<expression> is an expression that is used to determine which rows to delete.

The De le te statement is the o ppo site o f the Inse rtstatement. It is used to remo ve ro ws fro m a table. The De le te statement uses the Whe re c lause fro m the Se le ct

statement to identify whic h ro ws sho uld be deleted.

Deleting rows: When deleting a specific row from a table, use the prim ary key in the Whereclause to identify the specific row you w ant to delete.

A Sample Delete Statement

The fo llo wing De le te statement will delete the ro w I just added ( see Figure 4-10) :

Delete From Customers

Where CustomerId = 99999

Yo u c o de the Whe re c lause the same way yo u wo uld the Se le ctstatement. In this c ase, I o nly want to delete the o ne ro w, so I need to c o de the Whe re c lause to selec t the spec ific ro w I want to delete.

The De le te statement c an also be very dangero us. The fo llo wing statement will delete all o f the ro ws in the Custo mers table:

Delete From Customers

No te that the o nly differenc e between this statement and the previo us o ne is the missing Whe re c lause.

(20)

Figure 4-10: Deleting a single row from the Custom ers table

Don’t delete everything: It is very easy to delete everything from a table. For that reason, you should exercise extrem e caution w henever you use the Delete state-m ent. Alw ays use the Whereclause w hen using the Deletestatem ent. Failure to do so w ill delete all of the row s in your table. Unless you are deleting data as part of a transaction (see Chapter 16, “Transactions” for m ore inform ation), you can’t recover any deleted records.

Updating Rows in a Table

The Updatestatement allo ws yo u to c hange values in o ne o r mo re c o lumns in o ne o r mo re ro ws. Here is the syntax fo r this statement:

Update <table>

Set <column> = <value> [, <column> = <value>] ...

Where <expression>

where

<table> is the name of the table you want to update. <column> is a column name in the table you want to update.

(21)

<value> is an expression containing the new value for the column.

<expression> is true for the rows you want to update in the table.

The Updatestatement allo ws yo u to c hange any value in any ro w in a table. Like the

De le testatement, yo u need to inc lude a Whe rec lause to iso late the effec ts o f this statement o nly to the ro ws yo u want to update. Otherwise, yo u wo uld apply the c hange to all o f the ro ws in the table.

A Sample Update Statement

The fo llo wing Updatestatement will searc h fo r all ro ws that have a Null value fo r DateUpdated in the Custo mers table and replac e the value with a valid date ( see Figure 4-11) .

Update Customers

Set DateUpdated = “1-January-1997”

Where DateUpdated Is Null

(22)

The Create Table Statement

The Cre ate Tablestatement is used to build a new table in yo ur database.

There’s more to this statement than meets the eye:Nearly all database vendors have added m any vendor-specific extensions to the Create Tablestatem ent that I’ll cover in m ore detail w hen I focus on the specific database system s in Chapters 23, 26, and 29.

Here is the syntax fo r this statement:

Create Table <tablename> (<columndef> [, <columndef>]...)

where

<columndef> ::= <columnname> <datatype> [Null | Not Null ]

and

<tablename> is the name of your table.

<columnname> is the name of a column in your table. <datatype> is a valid data type.

The Cre ate Tablestatement allo ws yo u to define the c o llec tio n o f c o lumns that make up a table. The table must no t already exist in yo ur database, o r yo u’ll get an erro r message when yo u try to c reate it.

Eac h c o lumn must be assigned a valid data type. Table 4-2 earlier in this c hapter lists so me o f the c o mmo n data types available fo r a relatio nal database.

For m ore detailed inform ation about the data types available in a particular database, see Chapter 23, “Overview of SQL Server,” Chapter 26, “Overview of Oracle 8i,” or Chapter 29, “Overview of Microsoft Jet.”

Gone with the table: To rem ove a table from your database, use the Drop Table < tablenam e> SQL statem ent. This statem ent w ill also delete any indexes associ-ated w ith the table. Just be certain that you really w ant to delete the table, since it can’t be undeleted.

The fo llo wing SQL statement c reates the Custo mers table fo r SQL Server:

Create Table Customers (CustomerId Int Not Null,

Name Varchar(64), Street Varchar(64), City Varchar(64), State Char(2), Zip Int, Phone Varchar(32),

Tip Cross-Reference

(23)

EMailAddress Varchar(128), DateAdded Datetime, DateUpdated Datetime, MailingList Bit,

Comments Varchar(256))

No te that I dec lare the value Custo merId as Not Null, sinc e this c o lumn is the primary key fo r this table.

The Create Index Statement

The Cre ate Inde xstatement is used to add an index to a table in yo ur database.

Choose carefully, my child: Picking the right set of indexes can be difficult. You should use an index on the prim ary key of a table, especially if you plan to retrieve row s based on the prim ary key. How ever, adding any other indexes can severely im pact your database’s perform ance, since each tim e you add a row to the database, the database server has to update all of the indexes. The m ore indexes you have, the longer it w ill take to update your data.

Here is the syntax fo r this statement:

Create [Unique] Index <indexname> On <tablename> (<columnname> [, <columnname>]...)

where

<indexname> is the name of your index. <tablename> is the name of your table.

<columnname> is the name of a column in your table.

The Cre ate Inde xstatement adds an index to yo ur table using the spec ified c o lumns. Using an index c an impro ve the perfo rmanc e o f queries that use tho se c o lumns at the c o st o f additio nal wo rk the database server must do eac h time any o f the values in the spec ified c o lumns are c hanged.

Inc luding the keywo rd Uniquemeans that the set o f values inc luded in the index will be unique in the table. This is a useful feature if yo u need to ensure that yo u do n’t have two o r mo re ro ws with the same value in the indexed c o lumns.

Index be gone: To rem ove an index from your table, use the Drop Index < index-nam e> SQL statem ent.

(24)

A Sample Create Index Statement

The fo llo wing SQL statement c reates a Uniqueindex o n the Custo merId field o f the Custo mers table:

Create Unique Index CustomerIndex

On Customers (CustomerId)

This ensures that eac h value o f Custo merId in the table will be unique and also that queries using the Custo merId c o lumn in the Whe rec lause will run faster.

The Create View Statement

The Cre ate Vie wstatement c reates a virtual table that c an be used like any o ther table in yo ur database. Here is the syntax fo r this statement:

Create View <viewname> [(<columnname> [, <columnname>]...)]

As <selectstatement>

where

<viewname> is the name of your view.

<columnname> is the name of a column in your view.

<selectstatment> is valid select statement that returns the information in your view.

For m ore inform ation about view s, refer to “View s” in Chapter 2.

The virtual table that the Cre ate Vie wstatement defines in yo ur database is indis-tinguishable fro m a regular table fo r any o peratio ns invo lving a Se le ctstatement. The virtual table c an o ften be updated, depending o n ho w the view was c reated.

In o rder to update a view, the Se le ctstatement must o nly referenc e a single table kno wn as the base table , and it must no t return any c alc ulated values using func -tio ns and/ o r mathematic al fo rmulas. Also , any c o lumns no t explic itly inc luded in the view must be able to ac c ept Nullvalues. When yo u try to add a ro w to a view, any c o lumns in the base table that are no t part o f the view will be set to Null.

Bye-bye view: To rem ove a view from your table, use the Drop View < view nam e> SQL statem ent.

The fo llo wing SQL statement c reates a view that c o nsists o f the c usto mer’s name and the Custo merId c o lumn:

(25)

Figure 4-12 sho ws the results o f using aSelectstatement against the view. This view c an be updated, sinc e the c o lumns that are no t inc luded will ac c ept Nullvalues. This tec hnique is kno wn as ve rtical partitio ning, sinc e o nly so me o f the c o lumns are made available to the user.

Figure 4-12: Preventing som eone from seeing custom er inform ation beyond the custom er’s nam e and Custom erId

Yo u c an also use a Whe re c lause to retrieve o nly so me o f the ro ws in a table. This tec hnique is kno wn as ho riz o ntal partitio ning. Ho rizo ntal partitio ning is useful if yo u need to c reate a view where o nly so me o f the ro ws in the table are retrieved. The fo llo wing SQL statement c reates a view c o ntaining o nly the c usto mers fo und in Maryland ( see Figure 4-13) :

Create View MdCustomers As Select *

From Customers

Where State = “MD”

(26)

Figure 4-13: Restricting the view to only the custom ers from Maryland

Thoughts on Using SQL to Speed

Your Development Process

The Create Table,Create View, and Create Indexstatem ents are know n as Data Definition Language (DDL) statem ents, w hile the Insert,Delete,Update, and Select statem ents are know n as Data Manipulation Language (DM L) statem ents. In m ost database system s today, you rarely execute DDL statem ents w hen you w ant to create a database structure. Instead, you use a utility supplied w ith the database system that allow s you to fill in all of the inform ation into a table or use a w izard that w ill help you create your table or index.

(27)

Summary

In this c hapter yo u learned:

✦abo ut the SQL statements and data types.

✦ho w to use the Se le ctstatement to retrieve info rmatio n fro m yo ur database.

✦ho w to use the Inse rt, De le te ,and Updatestatements to manipulate the data in yo ur database.

✦ho w to use the Cre ate Tablestatement to c reate a new table.

Sim ply using an interactive query tool to retrieve inform ation from your database w ill help you understand if your program is w orking properly or not. You can use the Select state-m ent to return row s frostate-m a table and you can verify that they w ere updated properly. When used w ith the Countfunction, you can find out if your program processed the correct num -ber of row s.

The Insert and Create Tablestatem ents can be used together to create test copies of a table, w ith w hich you can test updating and deleting row s repeatedly until you are satisfied that your program is running correctly.

Most database vendors supply a rich environm ent for executing SQL statem ents. Using this environm ent, it is possible to w rite m ulti-statem ent SQL program s called stored procedures that perform fairly com plex operations. Since these stored procedures run totally on the database server, they m ay run significantly faster than executing them one statem ent at a tim e from your local com puter. This is an im portant concept to keep in m ind w hen devel-oping a database application, and one that I’ll explore in m ore depth w hen I talk about the stored procedures.

Also, keep in m ind that m any OLE DB providers translate the activities you perform into SQL statem ents that are sent to the database server for execution. This happens even if you don’t explicitly include SQL statem ents in your program . So, in cases w here every cycle counts, you m ight consider coding the SQL statem ents yourself rather than letting the provider do the w ork.

(28)

✦ho w to use the Cre ate Inde xto allo w the database to find spec ific ro ws in yo ur table mo re quic kly.

✦ho w to use the Cre ate Vie wstatement to c reate a virtual table that c an be used just like a real table, but who se c o ntents are dynamic ally c reated fro m o ther tables in the database.

Gambar

Figure 4-1: Running a sim ple query to retrieve all colum ns from  the Custom er table
Figure 4-3: Selecting inform ation about Custom erId 431
Figure 4-5: Retrieving all the custom ers living in California w ho w ere added since
Figure 4-6: Sorting row s retrieved from  a table
+7

Referensi

Dokumen terkait

Adapun tujuan diadakannya indeks saham syariah sebagaiman Jakarta Islamic Index yang melibatkan 30 saham terpilih, yaitu sebagai tolak ukur untuk mengukur kinerja

You can download and install the soft file of this incredible book Time Mends (Timber Wolves, Book 2) By Tammy Blackwell currently and in the link offered.. Yeah, different with

Indonesia merupakan negara dengan orang muslim terbesar didunia, akan tetapi setiap ormas muslim sendiri tentunya berbeda dalam memutuskan suatu masalah baru yang muncul

54 Tahun 2010 tentang Pengadaan Barang/Jasa Pemerintah serta menindaklanjuti proses seleksi untuk Paket Pekerjaan Pengadaan Meubelair (985 Unit) , bersama ini kami

Additionally, Aaron developed a wide variety of exercises and stretches specific for posture and alignment based on the personal needs and desires of the many clients he has served

n salinannya sebagaimana tertuang dalam lam proses pembuktian kualifikasi

Uang merupakan uang milik masyarakat atau uang beredar di masyarakat (di luar Bank Sentral seperti Bank Indonesia dan perbankan atau semua bank), yang terdiri dari :.. Uang Kertas

Puji syukur kami panjatkan kepada Tuhan Yang Maha Esa atas limpahan rahmat dan hidayah-Nya sehingga Prosiding Seminar Nasional MIPA Universitas Negeri Yogyakarta