61
Murach’s SQL Server 2008, C1 © 2008, Mike Murach & Associates, Inc. Slide 1 C hapter1 A n introduction to relationaldatabases and SQ L

Murach’s SQL Server 2008, C1© 2008, Mike Murach & Associates, Inc.Slide 1

Embed Size (px)

Citation preview

Page 1: Murach’s SQL Server 2008, C1© 2008, Mike Murach & Associates, Inc.Slide 1

Murach’s SQL Server 2008, C1 © 2008, Mike Murach & Associates, Inc. Slide 1

Chapter 1

An introduction torelational databases

and SQL

Page 2: Murach’s SQL Server 2008, C1© 2008, Mike Murach & Associates, Inc.Slide 1

Murach’s SQL Server 2008, C1 © 2008, Mike Murach & Associates, Inc. Slide 2

Objectives

Knowledge

Identify the three main hardware components of a client/server system.

Describe the way a client accesses the database on a server using these terms: application software, data access API, database management system, SQL query, and query results.

Describe the way a database is organized using these terms: tables, columns, rows, and cells.

Describe how the tables in a relational database are related using these terms: primary key and foreign key.

Identify the three types of relationships that can exist between two tables.

Describe the way the columns in a table are defined using these terms: data type, null value, default value, and identity column.

Page 3: Murach’s SQL Server 2008, C1© 2008, Mike Murach & Associates, Inc.Slide 1

Murach’s SQL Server 2008, C1 © 2008, Mike Murach & Associates, Inc. Slide 3

Objectives (continued) Describe the relationship between standard SQL and Microsoft

SQL Server’s Transact-SQL.

Describe the difference between DML statements and DDL statements.

Describe the difference between an action query and a SELECT query.

List three coding techniques that can make your SQL code easier to read and maintain.

Explain how views and stored procedures differ from SQL statements that are issued from an application program.

Describe the use of command and connection objects when .NET applications access a SQL Server database.

Page 4: Murach’s SQL Server 2008, C1© 2008, Mike Murach & Associates, Inc.Slide 1

Murach’s SQL Server 2008, C1 © 2008, Mike Murach & Associates, Inc. Slide 4

A simple client/server system

Client

Databaseserver

Network

Client

Client

Page 5: Murach’s SQL Server 2008, C1© 2008, Mike Murach & Associates, Inc.Slide 1

Murach’s SQL Server 2008, C1 © 2008, Mike Murach & Associates, Inc. Slide 5

The three hardware components of a client/server system The clients are the PCs, Macintoshes, or workstations of the

system.

The server is a computer that stores the files and databases of the system and provides services to the clients. When it stores databases, it’s often referred to as a database server.

The network consists of the cabling, communication lines, and other components that connect the clients and the servers of the system.

Page 6: Murach’s SQL Server 2008, C1© 2008, Mike Murach & Associates, Inc.Slide 1

Murach’s SQL Server 2008, C1 © 2008, Mike Murach & Associates, Inc. Slide 6

Client/server system implementations In a simple client/server system, the server is typically a high-

powered PC that communicates with the clients over a local area network (LAN).

The server can also be a midrange system, like an IBM iSeries or a Unix system, or it can be a mainframe system.

A client/server system can also consist of one or more PC-based systems, one or more midrange systems, and a mainframe system in dispersed geographical locations. This is commonly referred to as an enterprise system.

Individual systems and LANs can be connected and share data over larger private networks, such as a wide area network (WAN), or a public network like the Internet.

Page 7: Murach’s SQL Server 2008, C1© 2008, Mike Murach & Associates, Inc.Slide 1

Murach’s SQL Server 2008, C1 © 2008, Mike Murach & Associates, Inc. Slide 7

Client software, server software, and the SQLinterface

SQL queries

Results

Client Database serverApplication softwareData access API

Database management systemDatabase

Page 8: Murach’s SQL Server 2008, C1© 2008, Mike Murach & Associates, Inc.Slide 1

Murach’s SQL Server 2008, C1 © 2008, Mike Murach & Associates, Inc. Slide 8

Server software To store and manage databases, each server requires a database

management system (DBMS) like Microsoft SQL Server. The processing that’s done by the DBMS is typically referred to

as back-end processing, and the database server is referred to asthe back end.

Client software The application software does the work that the user wants to do. The data access API (application programming interface)

provides the interface between the application program and theDBMS.

The processing that’s done by the client software is typicallyreferred to as front-end processing, and the client is typicallyreferred to as the front end.

Page 9: Murach’s SQL Server 2008, C1© 2008, Mike Murach & Associates, Inc.Slide 1

Murach’s SQL Server 2008, C1 © 2008, Mike Murach & Associates, Inc. Slide 9

The SQL interface The application software communicates with the DBMS by sending

SQL queries through the data access API. When the DBMS receives a query, it provides a service like

returning the requested data (the query results) to the client. SQL stands for Structured Query Language, which is the standard

language for working with a relational database.

Client/server versus file-handling systems In a client/server system, the processing done by an application is

typically divided between the client and the server. In a file-handling system, all of the processing is done on the clients.

The clients may access data that’s stored in files on the server, butnone of the processing is done by the server.

Page 10: Murach’s SQL Server 2008, C1© 2008, Mike Murach & Associates, Inc.Slide 1

Murach’s SQL Server 2008, C1 © 2008, Mike Murach & Associates, Inc. Slide 10

A Windows-based system that uses an application server

ClientUser interface

Application serverBusiness components

SQL queries

Response Results

Database serverDBMS

Database

User request

Page 11: Murach’s SQL Server 2008, C1© 2008, Mike Murach & Associates, Inc.Slide 1

Murach’s SQL Server 2008, C1 © 2008, Mike Murach & Associates, Inc. Slide 11

A simple web-based system

ClientWeb browser

Database serverDBMS

Database

Web serverWeb applications

Web services

User request

Response

SQL queries

Results

Internet

User request

Response

Page 12: Murach’s SQL Server 2008, C1© 2008, Mike Murach & Associates, Inc.Slide 1

Murach’s SQL Server 2008, C1 © 2008, Mike Murach & Associates, Inc. Slide 12

Other client/server system architectures In addition to a database server and clients, a client/server system

can also include additional servers, such as application serversand web servers.

Application servers are typically used to store businesscomponents that do part of the application processing. Inparticular, these components are used to process database requestsfrom the client.

Web servers are typically used to store web applications and webservices. These are like standard applications and businesscomponents, but they’re designed to run on a web server.

In a web-based system, a web browser running on a client sends arequest to a web server over the Internet. Then, the web serverpasses any requests for data on to the database server.

Page 13: Murach’s SQL Server 2008, C1© 2008, Mike Murach & Associates, Inc.Slide 1

Murach’s SQL Server 2008, C1 © 2008, Mike Murach & Associates, Inc. Slide 13

The Vendors table in an Accounts Payable database

Page 14: Murach’s SQL Server 2008, C1© 2008, Mike Murach & Associates, Inc.Slide 1

Murach’s SQL Server 2008, C1 © 2008, Mike Murach & Associates, Inc. Slide 14

How a database table is organized A relational database consists of tables. Tables consist of rows

and columns, which can also be referred to as records and fields. A table is typically modeled after a real-world entity, such as an

invoice or a vendor. A column represents some attribute of the entity, such as the

amount of an invoice or a vendor’s address. A row contains a set of values for a single instance of the entity,

such as one invoice or one vendor. The intersection of a row and a column is sometimes called a cell.

A cell stores a single value. Most tables have a primary key that uniquely identifies each row

in the table. If a primary key consists of two or more columns, it’scalled a composite primary key.

Page 15: Murach’s SQL Server 2008, C1© 2008, Mike Murach & Associates, Inc.Slide 1

Murach’s SQL Server 2008, C1 © 2008, Mike Murach & Associates, Inc. Slide 15

How a database table is organized (continued) Some database management systems also let you define one or

more non-primary keys. Like a primary key, a non-primary keyuniquely identifies each row in the table.

In SQL Server, non-primary keys are called unique keys. A table can also be defined with one or more indexes. An index

provides an efficient way to access data from a table based on thevalues in specific columns.

An index is automatically created for a table’s primary and non-primary keys.

Page 16: Murach’s SQL Server 2008, C1© 2008, Mike Murach & Associates, Inc.Slide 1

Murach’s SQL Server 2008, C1 © 2008, Mike Murach & Associates, Inc. Slide 16

The relationship between the Vendors andInvoices tables in the database

Page 17: Murach’s SQL Server 2008, C1© 2008, Mike Murach & Associates, Inc.Slide 1

Murach’s SQL Server 2008, C1 © 2008, Mike Murach & Associates, Inc. Slide 17

How the tables in a relational database are related The tables in a relational database are related to each other through

their key columns. A foreign key identifies a primary key inanother table. A table may contain one or more foreign keys.

When you define a foreign key for a table in SQL Server, youcan’t add rows to the table with the foreign key unless there’s amatching primary key in the related table.

The relationships between the tables in a database correspond tothe relationships between the entities they represent. The mostcommon type of relationship is a one-to-many relationship.

A table can also have a one-to-one relationship or a many-to-manyrelationship with another table.

Page 18: Murach’s SQL Server 2008, C1© 2008, Mike Murach & Associates, Inc.Slide 1

Murach’s SQL Server 2008, C1 © 2008, Mike Murach & Associates, Inc. Slide 18

The columns of the Invoices table

Page 19: Murach’s SQL Server 2008, C1© 2008, Mike Murach & Associates, Inc.Slide 1

Murach’s SQL Server 2008, C1 © 2008, Mike Murach & Associates, Inc. Slide 19

Common SQL Server data types

Type Description

bit A value of 1 or 0 for True or False.

int, bigint, smallint, tinyint Integer values of various sizes.

money, smallmoney Monetary values that are accurate to four decimal places.

decimal, numeric Decimal values that are accurate to the least significant digit.

float, real Floating-point values that contain an approximation of a decimal value.

datetime, smalldatetime Dates and times.

char, varchar A string of letters, symbols, and numbers in the ASCII character set.

nchar, nvarchar A string of letters, symbols, and numbers in the Unicode character set.

Page 20: Murach’s SQL Server 2008, C1© 2008, Mike Murach & Associates, Inc.Slide 1

Murach’s SQL Server 2008, C1 © 2008, Mike Murach & Associates, Inc. Slide 20

How the columns in a table are defined The data type that’s assigned to a column determines the type and

size of the information that can be stored in the column.

Each column definition indicates whether or not it can contain null values. A null value indicates that the value of the column is unknown.

A column can also be defined with a default value. Then, that value is used if another value isn’t provided when a row is added to the table.

A column can also be defined as an identity column. An identity column is a numeric column whose value is generated automatically when a row is added to the table.

Page 21: Murach’s SQL Server 2008, C1© 2008, Mike Murach & Associates, Inc.Slide 1

Murach’s SQL Server 2008, C1 © 2008, Mike Murach & Associates, Inc. Slide 21

A comparison of relational databases andconventional file systemsFeature File system Relational database

Definition Each program that usesthe file must define thefile and its record layout

Tables, rows, andcolumns are definedwithin the database andcan be accessed by name

Maintenance If the file definitionchanges, each programthat uses the file must bemodified

Programs can be usedwithout modificationwhen the definition of atable changes

Validitychecking

Each program thatupdates a file mustinclude code to check forvalid data

Can include checks forvalid data

Page 22: Murach’s SQL Server 2008, C1© 2008, Mike Murach & Associates, Inc.Slide 1

Murach’s SQL Server 2008, C1 © 2008, Mike Murach & Associates, Inc. Slide 22

A comparison of relational databases andconventional file systems (continued)

Feature File system Relational database

Relationships Each program mustprovide for and enforcerelationships betweenfiles

Can enforce relationshipsbetween tables usingforeign keys; ad hocrelationships can also beused

Data access Each I/O operationtargets a specific recordin a file based on itsrelative position in thefile or its key value

A program can use SQLto access selected data inone or more tables of adatabase

Page 23: Murach’s SQL Server 2008, C1© 2008, Mike Murach & Associates, Inc.Slide 1

Murach’s SQL Server 2008, C1 © 2008, Mike Murach & Associates, Inc. Slide 23

A comparison of relational databases andother database systems

FeatureHierarchicaldatabase

Networkdatabase

Relationaldatabase

Supportedrelationships

One-to-manyonly

One-to-many,one-to-one, andmany-to-many

One-to-many,one-to-one, andmany-to-many;ad hocrelationships canalso be used

Data access Programs mustinclude code tonavigate throughthe physicalstructure of thedatabase

Programs mustinclude code tonavigate throughthe physicalstructure of thedatabase

Programs canaccess datawithout knowingits physicalstructure

Page 24: Murach’s SQL Server 2008, C1© 2008, Mike Murach & Associates, Inc.Slide 1

Murach’s SQL Server 2008, C1 © 2008, Mike Murach & Associates, Inc. Slide 24

A comparison of relational databases and otherdatabase systems (continued)

FeatureHierarchicaldatabase

Networkdatabase

Relationaldatabase

Maintenance New andmodifiedrelationships canbe difficult toimplement inapplicationprograms

New andmodifiedrelationships canbe difficult toimplement inapplicationprograms

Programs can beused withoutmodificationwhen thedefinition of atable changes

Page 25: Murach’s SQL Server 2008, C1© 2008, Mike Murach & Associates, Inc.Slide 1

Murach’s SQL Server 2008, C1 © 2008, Mike Murach & Associates, Inc. Slide 25

How relational databases compare to otherdata models To work with any of the data models other than the relational

database model, you must know the physical structure of the dataand the relationships between the files or tables.

Because relationships are difficult to implement in a conventionalfile system, redundant data is often stored in these types of files.

The hierarchical database model provides only for one-to-manyrelationships, called parent/child relationships.

The network database model can accommodate any type ofrelationship.

Relational databases are less efficient than the other data modelsbecause they require more system resources. However, theirflexibility and ease of use typically outweighs this inefficiency.

Page 26: Murach’s SQL Server 2008, C1© 2008, Mike Murach & Associates, Inc.Slide 1

Murach’s SQL Server 2008, C1 © 2008, Mike Murach & Associates, Inc. Slide 26

Important events in the history of SQLYear Event

1970 Dr. E. F. Codd developed the relational database model.

1978 IBM developed the predecessor to SQL, called StructuredEnglish Query Language (SEQUEL). This language was usedon a database system called System/R, but neither the systemnor the query language was ever released.

1979 Relational Software, Inc. (later renamed Oracle) released thefirst relational DBMS, Oracle.

1982 IBM released their first relational database system, SQL/DS(SQL/Data System).

1985 IBM released DB2 (Database 2).

1987 Microsoft released SQL Server.

Page 27: Murach’s SQL Server 2008, C1© 2008, Mike Murach & Associates, Inc.Slide 1

Murach’s SQL Server 2008, C1 © 2008, Mike Murach & Associates, Inc. Slide 27

Important events in the history of SQL (continued)

Year Event

1989 The American National Standards Institute (ANSI) published the first set of standards for a database query language, called ANSI/ISO SQL-89, or SQL1.

1992 ANSI published standards (ANSI/ISO SQL-92, or SQL2) that were more stringent than SQL1 and incorporated many new features. These standards introduced levels of compliance that indicated the extent to which a dialect met the standards.

1999 ANSI published SQL3 (ANSI/ISO SQL-99). These standards incorporated new features, including support for objects. Levels of compliance were replaced by a core specification along with specifications for nine additional packages.

2003 ANSI published SQL4 (ANSI/ISO SQL:2003). These standards introduced XML-related features, standardized sequences, and identity columns.

Page 28: Murach’s SQL Server 2008, C1© 2008, Mike Murach & Associates, Inc.Slide 1

Murach’s SQL Server 2008, C1 © 2008, Mike Murach & Associates, Inc. Slide 28

The ANSI SQL standards SQL-92 initially provided for three levels of compliance, or levels of

conformance: entry, intermediate, and full. A transitional level was later added between the entry and intermediate levels because the jump between those levels was too great.

SQL:1999 includes a core specification that defines the essential elements for compliance, plus nine packages. Each package is designed to serve a specific market niche.

Although SQL is a standard language, each vendor has its own SQL dialect, or variant, that may include extensions to the standards. SQL Server’s SQL dialect is called Transact-SQL.

Page 29: Murach’s SQL Server 2008, C1© 2008, Mike Murach & Associates, Inc.Slide 1

Murach’s SQL Server 2008, C1 © 2008, Mike Murach & Associates, Inc. Slide 29

How knowing “standard SQL” helps you The most basic SQL statements are the same for all SQL

dialects.

Once you have learned one SQL dialect, you can easily learn other dialects.

How knowing “standard SQL” does not help you Any non-trivial application will require modification when

moved from one SQL database to another.

Page 30: Murach’s SQL Server 2008, C1© 2008, Mike Murach & Associates, Inc.Slide 1

Murach’s SQL Server 2008, C1 © 2008, Mike Murach & Associates, Inc. Slide 30

Features of Oracle, DB2, and SQL Server

Category Oracle IBM Microsoft

Released 1979 1985 1987 Current version

Oracle 11g DB2 9 SQL Server 2008

Platforms Unix OS/390 Windows

OS/390, z/OS, and AIX Unix Windows

Windows

Strengths Reliable Reliable Easy to use Typical system

Medium to very large Network-based Mission-critical Enterprise-wide

Large to very large Centralized architecture Mission-critical Enterprise-wide

Small to medium Network-based

Page 31: Murach’s SQL Server 2008, C1© 2008, Mike Murach & Associates, Inc.Slide 1

Murach’s SQL Server 2008, C1 © 2008, Mike Murach & Associates, Inc. Slide 31

A comparison of Oracle, DB2, and SQL Server Oracle is typically used for large, mission-critical, systems that run

on one or more Unix servers.

DB2 is typically used for large, mission-critical systems that run on legacy IBM mainframe systems using the z/OS or OS/390 operating system.

SQL Server is typically used for small- to medium-sized systems that run on one or more Windows servers.

Page 32: Murach’s SQL Server 2008, C1© 2008, Mike Murach & Associates, Inc.Slide 1

Murach’s SQL Server 2008, C1 © 2008, Mike Murach & Associates, Inc. Slide 32

SQL statements used to work with data (DML)Statement Description

SELECT Retrieves data from one or more tables.

INSERT Adds one or more new rows to a table.

UPDATE Changes one or more existing rows in a table.

DELETE Deletes one or more existing rows from a table.

Page 33: Murach’s SQL Server 2008, C1© 2008, Mike Murach & Associates, Inc.Slide 1

Murach’s SQL Server 2008, C1 © 2008, Mike Murach & Associates, Inc. Slide 33

SQL statements used to work with databaseobjects (DDL)

Statement Description

CREATE DATABASE Creates a new database.

CREATE TABLE Creates a new table in a database.

CREATE INDEX Creates a new index for a table.

ALTER TABLE Changes the structure of an existing table.

DROP DATABASE Deletes an existing database.

DROP TABLE Deletes an existing table.

DROP INDEX Deletes an existing index.

Page 34: Murach’s SQL Server 2008, C1© 2008, Mike Murach & Associates, Inc.Slide 1

Murach’s SQL Server 2008, C1 © 2008, Mike Murach & Associates, Inc. Slide 34

Two types of SQL statements The SQL statements can be divided into two categories: the data

manipulation language (DML) and the data definition language(DDL).

The DML statements let you work with the data in the database. The DDL statements let you work with the objects in the

database. SQL programmers typically work with the DML statements,

while database administrators (DBAs) use the DDL statements.

Page 35: Murach’s SQL Server 2008, C1© 2008, Mike Murach & Associates, Inc.Slide 1

Murach’s SQL Server 2008, C1 © 2008, Mike Murach & Associates, Inc. Slide 35

A statement that creates a new databaseCREATE DATABASE AP

A statement that creates a new tableCREATE TABLE Invoices(InvoiceID INT NOT NULL IDENTITY PRIMARY KEY,VendorID INT NOT NULL REFERENCES Vendors(VendorID),InvoiceNumber VARCHAR(50) NOT NULL,InvoiceDate SMALLDATETIME NOT NULL,InvoiceTotal MONEY NOT NULL,PaymentTotal MONEY NOT NULL DEFAULT 0,CreditTotal MONEY NOT NULL DEFAULT 0,TermsID INT NOT NULL REFERENCES Terms(TermsID),InvoiceDueDate SMALLDATETIME NOT NULL,PaymentDate SMALLDATETIME NULL)

Page 36: Murach’s SQL Server 2008, C1© 2008, Mike Murach & Associates, Inc.Slide 1

Murach’s SQL Server 2008, C1 © 2008, Mike Murach & Associates, Inc. Slide 36

A statement that adds a new column to the tableALTER TABLE InvoicesADD BalanceDue MONEY NOT NULL

A statement that deletes the new columnALTER TABLE InvoicesDROP COLUMN BalanceDue

A statement that creates an index on the tableCREATE INDEX IX_Invoices_VendorID ON Invoices (VendorID)

Page 37: Murach’s SQL Server 2008, C1© 2008, Mike Murach & Associates, Inc.Slide 1

Murach’s SQL Server 2008, C1 © 2008, Mike Murach & Associates, Inc. Slide 37

How to query a single table You use the SELECT statement to retrieve selected columns and

rows from a base table. The result of a SELECT statement is a result table, or result set. A result set can include calculated values that are calculated

from columns in the table. The execution of a SELECT statement is commonly referred to

as a query.

Page 38: Murach’s SQL Server 2008, C1© 2008, Mike Murach & Associates, Inc.Slide 1

Murach’s SQL Server 2008, C1 © 2008, Mike Murach & Associates, Inc. Slide 38

The Invoices base table

Page 39: Murach’s SQL Server 2008, C1© 2008, Mike Murach & Associates, Inc.Slide 1

Murach’s SQL Server 2008, C1 © 2008, Mike Murach & Associates, Inc. Slide 39

A SELECT statement that retrieves and sorts selected columns and rows from the Invoices table

SELECT InvoiceNumber, InvoiceDate, InvoiceTotal, PaymentTotal, CreditTotal, InvoiceTotal – PaymentTotal – CreditTotal AS BalanceDue FROM Invoices WHERE InvoiceTotal – PaymentTotal – CreditTotal > 0 ORDER BY InvoiceDate

The result set defined by the SELECT statement

Page 40: Murach’s SQL Server 2008, C1© 2008, Mike Murach & Associates, Inc.Slide 1

Murach’s SQL Server 2008, C1 © 2008, Mike Murach & Associates, Inc. Slide 40

A SELECT statement that joins data from the Vendors and Invoices tables

SELECT VendorName, InvoiceNumber, InvoiceDate, InvoiceTotal FROM Vendors INNER JOIN Invoices ON Vendors.VendorID = Invoices.VendorID WHERE InvoiceTotal >= 500 ORDER BY VendorName, InvoiceTotal DESC

Page 41: Murach’s SQL Server 2008, C1© 2008, Mike Murach & Associates, Inc.Slide 1

Murach’s SQL Server 2008, C1 © 2008, Mike Murach & Associates, Inc. Slide 41

The result set defined by the SELECT statement

Page 42: Murach’s SQL Server 2008, C1© 2008, Mike Murach & Associates, Inc.Slide 1

Murach’s SQL Server 2008, C1 © 2008, Mike Murach & Associates, Inc. Slide 42

How to join data from two or more tables A join lets you combine data from two or more tables into a

single result set.

The most common type of join is an inner join. This type of join returns rows from both tables only if their related columns match.

An outer join returns rows from one table in the join even if the other table doesn’t contain a matching row.

Page 43: Murach’s SQL Server 2008, C1© 2008, Mike Murach & Associates, Inc.Slide 1

Murach’s SQL Server 2008, C1 © 2008, Mike Murach & Associates, Inc. Slide 43

How to add, update, and delete data in a table You use the INSERT statement to add rows to a table.

You use the UPDATE statement to change the values in one or more rows of a table based on the condition you specify.

You use the DELETE statement to delete one or more rows from a table based on the condition you specify.

The execution of an INSERT, UPDATE, or DELETE statement is often referred to as an action query.

Page 44: Murach’s SQL Server 2008, C1© 2008, Mike Murach & Associates, Inc.Slide 1

Murach’s SQL Server 2008, C1 © 2008, Mike Murach & Associates, Inc. Slide 44

A statement that adds a row to the Invoices table INSERT INTO Invoices (VendorID, InvoiceNumber, InvoiceDate, InvoiceTotal, TermsID, InvoiceDueDate) VALUES (12, '3289175', '7/18/2008', 165, 3, '8/17/2008')

A statement that changes the value of the CreditTotal column for a selected row

UPDATE Invoices SET CreditTotal = 35.89 WHERE InvoiceNumber = '367447'

A statement that changes the values in the InvoiceDueDate column for all invoices with the specified TermsID

UPDATE Invoices SET InvoiceDueDate = InvoiceDueDate + 30 WHERE TermsID = 4

Page 45: Murach’s SQL Server 2008, C1© 2008, Mike Murach & Associates, Inc.Slide 1

Murach’s SQL Server 2008, C1 © 2008, Mike Murach & Associates, Inc. Slide 45

A statement that deletes a selected invoice from the Invoices table

DELETE FROM Invoices WHERE InvoiceNumber = '4-342-8069'

A statement that deletes all paid invoices DELETE FROM Invoices WHERE InvoiceTotal – PaymentTotal – CreditTotal = 0

Page 46: Murach’s SQL Server 2008, C1© 2008, Mike Murach & Associates, Inc.Slide 1

Murach’s SQL Server 2008, C1 © 2008, Mike Murach & Associates, Inc. Slide 46

A SELECT statement that’s difficult to read select invoicenumber, invoicedate, invoicetotal, invoicetotal – paymenttotal – credittotal as balancedue from invoices where invoicetotal – paymenttotal – credittotal > 0 order by invoicedate

A SELECT statement with a readable style Select InvoiceNumber, InvoiceDate, InvoiceTotal, InvoiceTotal – PaymentTotal – CreditTotal As BalanceDue From Invoices Where InvoiceTotal – PaymentTotal – CreditTotal > 0 Order By InvoiceDate

Note

Line breaks, white space, indentation, and capitalization have no effect on the operation of a statement.

Page 47: Murach’s SQL Server 2008, C1© 2008, Mike Murach & Associates, Inc.Slide 1

Murach’s SQL Server 2008, C1 © 2008, Mike Murach & Associates, Inc. Slide 47

A SELECT statement with a block comment /* Author: Bryan Syverson Date: 8/22/08 */ SELECT InvoiceNumber, InvoiceDate, InvoiceTotal, InvoiceTotal – PaymentTotal – CreditTotal AS BalanceDue FROM Invoices

A SELECT statement with a single-line comment SELECT InvoiceNumber, InvoiceDate, InvoiceTotal, InvoiceTotal – PaymentTotal – CreditTotal AS BalanceDue -- The 4th column calculates the invoice balance due FROM Invoices

Note

Comments can be used to document portions of code or to clarify what the coding does. They aren’t executed by the system.

Page 48: Murach’s SQL Server 2008, C1© 2008, Mike Murach & Associates, Inc.Slide 1

Murach’s SQL Server 2008, C1 © 2008, Mike Murach & Associates, Inc. Slide 48

How to code a comment To code a block comment, type /* at the start of the block and */ at

the end. To code a single-line comment, type -- followed by the comment.

SQL coding recommendations Start each new clause on a new line. Break long clauses into multiple lines and indent continued lines. Capitalize the first letter of each keyword and each word in

column and table names. Use comments only for portions of code that are difficult to

understand. Then, make sure that the comments are correct andup-to-date.

Page 49: Murach’s SQL Server 2008, C1© 2008, Mike Murach & Associates, Inc.Slide 1

Murach’s SQL Server 2008, C1 © 2008, Mike Murach & Associates, Inc. Slide 49

A CREATE VIEW statement for a view namedVendorsMin

CREATE VIEW VendorsMin AS SELECT VendorName, VendorState, VendorPhone FROM Vendors

The virtual table that’s represented by the view

Page 50: Murach’s SQL Server 2008, C1© 2008, Mike Murach & Associates, Inc.Slide 1

Murach’s SQL Server 2008, C1 © 2008, Mike Murach & Associates, Inc. Slide 50

A SELECT statement that uses the VendorsMinview

SELECT * FROM VendorsMinWHERE VendorState = 'CA'ORDER BY VendorName

The result set that’s returned by the SELECTstatement

Page 51: Murach’s SQL Server 2008, C1© 2008, Mike Murach & Associates, Inc.Slide 1

Murach’s SQL Server 2008, C1 © 2008, Mike Murach & Associates, Inc. Slide 51

How to work with views A view consists of a SELECT statement that’s stored with the

database. A view behaves like a virtual table. Since you can code a view

name anywhere you’d code a table name, a view is sometimescalled a viewed table.

Views can be used to restrict the data that a user is allowed toaccess or to present data in a form that’s easy for the user tounderstand.

Because views are stored as part of the database, they can bemanaged independently of the applications that use them.

Page 52: Murach’s SQL Server 2008, C1© 2008, Mike Murach & Associates, Inc.Slide 1

Murach’s SQL Server 2008, C1 © 2008, Mike Murach & Associates, Inc. Slide 52

A CREATE PROCEDURE statement for a procedure named spVendorsByState

CREATE PROCEDURE spVendorsByState @State char(2) AS SELECT VendorName, VendorState, VendorPhone FROM Vendors WHERE VendorState = @State ORDER BY VendorName

A statement that executes the stored procedure EXEC spVendorsByState 'CA'

The result set

Page 53: Murach’s SQL Server 2008, C1© 2008, Mike Murach & Associates, Inc.Slide 1

Murach’s SQL Server 2008, C1 © 2008, Mike Murach & Associates, Inc. Slide 53

How to use stored procedures, triggers, and user-defined functions A stored procedure is one or more SQL statements that have been

compiled and stored with the database. It can be started by application code on the client.

A stored procedure can also include control-of-flow language, which lets you perform conditional processing.

Stored procedures can improve database performance because the SQL statements in each procedure are only compiled and optimized the first time they’re executed.

A trigger is a special type of procedure that’s executed when rows are inserted, updated, or deleted from a table. Triggers are typically used to check the validity of the data in a row.

A user-defined function (UDF) is a special type of procedure that can return a value or a table.

Page 54: Murach’s SQL Server 2008, C1© 2008, Mike Murach & Associates, Inc.Slide 1

Murach’s SQL Server 2008, C1 © 2008, Mike Murach & Associates, Inc. Slide 54

Common options for accessing SQL Server data

OLE DB

ADOJDBC

Java driver

SQL Server

ADO.NET

.NET application Java application Visual Basic 6 application

Page 55: Murach’s SQL Server 2008, C1© 2008, Mike Murach & Associates, Inc.Slide 1

Murach’s SQL Server 2008, C1 © 2008, Mike Murach & Associates, Inc. Slide 55

Common data access models To work with the data in a SQL Server database, an application

uses a data access model.

For a Visual Basic .NET application, that model is typically ADO.NET. For a Java application, that model is typically JDBC (Java Database Connectivity). And for a Visual Basic 6 application, that model is typically ADO (ActiveX Data Objects).

Each data access model defines a set of objects you can use to connect to and work with a SQL Server database.

Some of the data access models require additional software, called drivers, to communicate with SQL Server. For example, ADO requires an OLE DB driver, and JDBC requires a Java driver.

ADO.NET, which is Microsoft’s newest data access model, includes its own driver so it can communicate directly with SQL Server.

Page 56: Murach’s SQL Server 2008, C1© 2008, Mike Murach & Associates, Inc.Slide 1

Murach’s SQL Server 2008, C1 © 2008, Mike Murach & Associates, Inc. Slide 56

Basic ADO.NET objects in a.NET application

.NET application

Data table

Dataset

Dataadapter

ConnectionCommand

SQL Server

Page 57: Murach’s SQL Server 2008, C1© 2008, Mike Murach & Associates, Inc.Slide 1

Murach’s SQL Server 2008, C1 © 2008, Mike Murach & Associates, Inc. Slide 57

How to use ADO.NET from a .NET application The data used by a .NET application can be stored in a data table

within a dataset. A dataset can contain multiple data tables.

To retrieve data from a database and store it in a data table: (1) a data adapter issues a SELECT statement that’s stored in a command; (2) the command uses a connection to connect to the database and retrieve the data; (3) the data is passed back to the data adapter, which stores the data in the dataset.

To update the data in a database based on the data in a data table, the data adapter issues an INSERT, UPDATE, or DELETE statement that’s stored in a command. Then, the command uses a connection to connect to and update the database.

After the database data is retrieved or updated, the connection is closed and the resources used by the connection are released. This is referred to as the disconnected data architecture.

Page 58: Murach’s SQL Server 2008, C1© 2008, Mike Murach & Associates, Inc.Slide 1

Murach’s SQL Server 2008, C1 © 2008, Mike Murach & Associates, Inc. Slide 58

Visual Basic code that uses ADO.NET to retrieve data from a SQL Server database ' Create the Connection, DataAdapter, Command, ' and DataSet objects Dim connAP As New SqlClient.SqlConnection() Dim daVendors As New SqlClient.SqlDataAdapter() Dim cmdVendorsSelect As New SqlClient.SqlCommand() Dim dsAP As New DataSet() ' Set the connection string for the Connection object connAP.ConnectionString = _ "Data Source=localhost\SqlExpress;" _ & "Initial Catalog=AP;Integrated Security=True" ' Set the Connection object used by the Command object cmdVendorsSelect.Connection = connAP ' Set the SELECT statement for the Command object cmdVendorsSelect.CommandText = "SELECT VendorID, " _ & "VendorName, VendorAddress1, VendorAddress2, " _ & "VendorCity, VendorState, VendorZipCode " _ & "FROM Vendors ORDER BY VendorName"

Page 59: Murach’s SQL Server 2008, C1© 2008, Mike Murach & Associates, Inc.Slide 1

Murach’s SQL Server 2008, C1 © 2008, Mike Murach & Associates, Inc. Slide 59

Visual Basic code that uses ADO.NET to retrieve data from a SQL Server database (continued) ' Set the Command object for the DataAdapter daVendors.SelectCommand = cmdVendorsSelect ' Open the connection to the database connAP.Open() ' Retrieve the data specified by the SELECT statement ' and load it into the Vendors table that is stored in the ' DataSet object daVendors.Fill(dsAP, "Vendors") ' Close the connection to the database connAP.Close()

Page 60: Murach’s SQL Server 2008, C1© 2008, Mike Murach & Associates, Inc.Slide 1

Murach’s SQL Server 2008, C1 © 2008, Mike Murach & Associates, Inc. Slide 60

C# code that uses ADO.NET to retrieve data from a SQL Server database // Create the Connection, DataAdapter, Command, and DataSet // objects SqlConnection connAP = new SqlConnection(); SqlDataAdapter daVendors = new SqlDataAdapter(); SqlCommand cmdVendorsSelect = new SqlCommand(); DataSet dsAP = new DataSet(); // Set the connection string for the Connection object connAP.ConnectionString = "Data Source=localhost\\SqlExpress;" + "Initial Catalog=AP;Integrated Security=True"; // Set the Connection object used by the Command object cmdVendorsSelect.Connection = connAP; // Set the SELECT statement for the Command object cmdVendorsSelect.CommandText = "SELECT VendorID, " + "VendorName, VendorAddress1, VendorAddress2, " + "VendorCity, VendorState, VendorZipCode " + "FROM Vendors ORDER BY VendorName";

Page 61: Murach’s SQL Server 2008, C1© 2008, Mike Murach & Associates, Inc.Slide 1

Murach’s SQL Server 2008, C1 © 2008, Mike Murach & Associates, Inc. Slide 61

C# code that uses ADO.NET to retrieve data from a SQL Server database (continued) // Set the Command object for the DataAdapter daVendors.SelectCommand = cmdVendorsSelect; // Open the connection to the database connAP.Open(); // Retrieve the data specified by the SELECT statement // and load it into the Vendors table that is stored in the // DataSet object daVendors.Fill(dsAP, "Vendors"); // Close the connection to the database connAP.Close();