Sei sulla pagina 1di 34

Designing and Creating a Database Part 2

http://www.LearnNowOnline.com

Learn More @ http://www.learnnowonline.com


Copyright by Application Developers Training Company

Objectives
Learn basic relational database design principles Create a SQL Server database based on sound design principles Build tables using the SQL Server Management Studio designers Learn about SQL Server data types Create constraints, triggers, and indexes Create a database diagram and define relationships to enforce referential integrity
Learn More @ http://www.learnnowonline.com
Copyright by Application Developers Training Company

Agenda
Relational Database Design Principles Implementing Database Design

Learn More @ http://www.learnnowonline.com


Copyright by Application Developers Training Company

Database Storage
Pages
The minimum unit of storage: 8 KB Maximum size of a row
Except long values: text, ntext, image, varchar(max), nvarchar(max),

varbinary(max) 8060 bytes, after deducting space for overhead

Extents
8 pages per Extent New objects at first stored in spare pages in existing extents

Learn More @ http://www.learnnowonline.com


Copyright by Application Developers Training Company

Database Storage
Files
.MDF, .NDF, .LDF

The transaction log ensures data integrity

Filegroups
Can locate data or indexes in additional files and on

separate devices (disks) Databases have two file names


Logical file name Physical file name
Learn More @ http://www.learnnowonline.com
Copyright by Application Developers Training Company

Data Integrity
The Transaction Log

Automatically created with a database Records all activity in a database Data pages are loaded into a buffer cache Any updates are made to the copy in the buffer A log record is created in a log cache Checkpoint process saves the log record to disk Only then is the data saved to disk
Learn More @ http://www.learnnowonline.com
Copyright by Application Developers Training Company

SQL Server uses write-ahead strategy


1. 2. 3. 4. 5.

Recovery Models
Simple
Log is truncated at checkpoint Recovery to the point of the last full or differential backup

Full
All operations are fully logged Recovery to any point in time

Bulk-logged
Faster bulk-logged operations (indexing, bulk load) Recovery limited to logged transactions after the last

backup
Learn More @ http://www.learnnowonline.com
Copyright by Application Developers Training Company

Creating Databases
Use Management Studio or Transact-SQL
SSMS uses T-SQL behind the scenes Almost all SSMS actions follow this pattern Most of the time you can access that code

Learn More @ http://www.learnnowonline.com


Copyright by Application Developers Training Company

Rules for SQL Server Identifiers


All object names must meet these requirements Length: 1 128 characters First character: letter, @, #, _ (no numbers)
@ only for local variables and parameters in T-SQL # only for local temporary objects (temp tables) ## for global temporary tables (span connections)

Additional characters: letters, numbers, #, $, _ Use square brackets or double quotes if identifier has spaces or other special characters No use of reserved keywords as identifiers
Learn More @ http://www.learnnowonline.com
Copyright by Application Developers Training Company

Modifying Database Options


Once you create the database, can set additional options

Learn More @ http://www.learnnowonline.com


Copyright by Application Developers Training Company

Creating Tables
New database doesnt contain tables Table names must be unique
General format:

server.database.schema_name.object_name Usually can simplify schema_name.object_name

Most work is creating the columns Can also define constraints


Learn More @ http://www.learnnowonline.com
Copyright by Application Developers Training Company

Schemas
Before SQL Server 2005, schema names based on user names
Except for dbo Close tie was inconvenient

Now conforms to SQL standard

Use any valid identifier for schema names


Can assign same schema to multiple users

Assign permissions to schema


Learn More @ http://www.learnnowonline.com
Copyright by Application Developers Training Company

SQL Server Data Types


Character-based data types
Non-Unicode char fixed length, up to 8,000 varchar variable length, can set max text long values, up to 2 billion bytes varchar(max) long values, up to 2 billion bytes Unicode equivalents nchar fixed length, up to 4,000 nvarchar variable length, can set max ntext long Unicode values nvarchar(max) long Unicode values
Learn More @ http://www.learnnowonline.com
Copyright by Application Developers Training Company

SQL Server Data Types


Numeric data types
Whole Numbers bit 1 or 0, one bit of storage tinyint 0 to 255, one byte smallint +/- 32 K, two bytes int +/- 2 billion, four bytes bigint +/- 9 quintillion, 8 bytes

Learn More @ http://www.learnnowonline.com


Copyright by Application Developers Training Company

SQL Server Data Types


Numeric data types
Fractional Numbers real floating point, 4 bytes float floating point, 8 bytes decimal/numeric scaled integer storage varies (5 to 17 bytes) precision: total number of digits (maximum of 38) scale: digits to the right of decimal each combination is a different type
Learn More @ http://www.learnnowonline.com
Copyright by Application Developers Training Company

SQL Server Data Types


Numeric data types
Fractional Numbers money scaled integer, 8 bytes +/- 900 trillion 4 digits to the right of the decimal smallmoney scaled integer, 4 bytes +/- 200 thousand 4 digits to the right of the decimal

Learn More @ http://www.learnnowonline.com


Copyright by Application Developers Training Company

SQL Server Data Types


Date data types
datetime 8 bytes 4 bytes: days before or after 1/1/1900 (range: 1/1/1753-12/31/9999) 4 bytes: milliseconds after midnight (rounded to .000, .003, .007 sec.) smalldatetime 4 bytes 2 bytes: days after 1/1/1900 (range: 1/1/1900-6/6/2079) 2 bytes: minutes after midnight
Learn More @ http://www.learnnowonline.com
Copyright by Application Developers Training Company

SQL Server Data Types


Date data types
date 3 bytes
Range: 0001-01-01 to 9999-12-31

time 3 to 5 bytes
Range: 00:00:00.0000000 to 23:59:59.9999999 Precision up to 100 nanoseconds

datetime2 6 to 8 bytes
Range and precision of date and time types No time zone or daylight savings time information

datetimeoffset 8 to 10 bytes
datetime2 with time zone information

YYYY-MM-DDThh:mm:ss[.nnnnnnn][{+|-}hh:mm] YYYY-MM-DDThh:mm:ss[.nnnnnnn]Z
Learn More @ http://www.learnnowonline.com
Copyright by Application Developers Training Company

SQL Server Data Types


Binary data types
binary up to 8000 bytes, fixed length varbinary variable length image long values, up to 2 billion bytes

varbinary(max) long values, up to 2 billion bytes

Learn More @ http://www.learnnowonline.com


Copyright by Application Developers Training Company

SQL Server Data Types


Identifier data types
The identity property Not really a separate data type Can be set for: tinyint, smallint, int, bigint, decimal, or numeric Configure seed and increment values

Learn More @ http://www.learnnowonline.com


Copyright by Application Developers Training Company

SQL Server Data Types


Identifier data types
uniqueidentifier a 16-byte GUID

{40700425-0080-11d2-851f-00c04fc21759}
Used by SQL Server for replication newid() function as default generates random IDs newsequentialid() better for indexing

timestamp/rowversion 8-byte unique binary


Updated automatically when row is modified Unrelated to time

Used to track data changes (compare old and current values to see

if row has changed)


Learn More @ http://www.learnnowonline.com
Copyright by Application Developers Training Company

SQL Server Data Types


The sql_variant data type
Introduced in SQL Server 2000 Can hold any other type of value, except text, ntext, image, *(max), xml, and

timestamp Useful for name/value pairs where the data type for the values may vary More overhead than any other data types
Stores meta data as well as data:base data type,

maximum size, scale, precision, and collation


Learn More @ http://www.learnnowonline.com
Copyright by Application Developers Training Company

SQL Server Data Types


Variable-only data types (not used in tables)
table Temporary storage of a result set Local scope Used like any table, e.g., in FROM clause No indexing or transactions Primarily used for results from table-valued user-defined functions Cursor Used for variables or output parameters Reference to a cursor
Learn More @ http://www.learnnowonline.com
Copyright by Application Developers Training Company

SQL Server Data Types


xml data type
Up to 2 Gigabytes Available for table columns or for variables Can reference an XML schema collection (typed

xml) Special methods for querying and modifying xml Special indexes store individual xml nodes and paths to the nodes from the root T-SQL supports a subset of the emerging XQuery standard for querying xml data
Learn More @ http://www.learnnowonline.com
Copyright by Application Developers Training Company

SQL Server Data Types


System SQLCLR types
Geometry and Geography for spatial data HierarchyID for hierarchical data

Learn More @ http://www.learnnowonline.com


Copyright by Application Developers Training Company

SQL Server Data Types


User-Defined Types
Composed of standard types with saved settings Or based on .NET assemblies

Learn More @ http://www.learnnowonline.com


Copyright by Application Developers Training Company

Computed Columns
Let you create a column that automatically updates values
Based on expression that you define Can include references to other columns

Learn More @ http://www.learnnowonline.com


Copyright by Application Developers Training Company

Creating Constraints
Can restrict data that users enter in columns
Set restrictions, or constraints Can place on columns as part of creating tables
Or add them later

Types

Primary key Foreign key Not Null Default Check Unique


Learn More @ http://www.learnnowonline.com
Copyright by Application Developers Training Company

Default Constraints
Enables a value to be entered automatically into a new row
When no other data is explicitly entered in that

column Define one default constraint per column

Learn More @ http://www.learnnowonline.com


Copyright by Application Developers Training Company

Check Constraints
Checks the data before saving record
If incoming data violates constraint, record isnt

saved If value of constraint expression is False, constraint is violated If null, will save data

Learn More @ http://www.learnnowonline.com


Copyright by Application Developers Training Company

Triggers
Available on INSERT, UPDATE, DELETE Access to special views: deleted, inserted Can access and alter values in other tables Uses:
Business rules, Audit trails, roll back Originally used for referential integrity

Caution: Maintenance and perf headaches Instead, use stored procedures for data modification if possible
Learn More @ http://www.learnnowonline.com
Copyright by Application Developers Training Company

Creating Indexes
Indexes let users query data efficiently
SQL Server can use a shortcut to find data Instead of scanning entire table

Learn More @ http://www.learnnowonline.com


Copyright by Application Developers Training Company

Using Database Diagrams


Uses
Define foreign key constrains Get high-level structure view of database Perform other design tasks

Learn More @ http://www.learnnowonline.com


Copyright by Application Developers Training Company

Questions?
http://www.LearnNowOnline.com

Learn More @ http://www.learnnowonline.com


Copyright by Application Developers Training Company

Potrebbero piacerti anche