SQL Server
Trang 1T-SQL for Data Definition
Vu Tuyet Trinh
trinhvt-fit@mail.hut.edu.vn
Hanoi University of Technology
1
Trang 2Overview of Transact-SQL
Based on AINSI SQL 92 standard
Composing of three categories
Data Manipulation Language (DML)
Data Definition Language (DDL)
Data Control Language (DCL)
Having some Microsoft specific extensions
Beyond relational data
net framework integration
Trang 4Overview of Database Objects
Trang 7Creating a New Database
Factors to consider
Default: Sysadmin, dbcreator
Creator becomes the owner
Maximum of 32,767 per server
Follow naming rules
Trang 8Creating a New Database
Some arguments:
The name of the database
The size of the database
The files where the database will reside
CREATE DATABASE Sample ON
PRIMARY ( NAME=SampleData, FILENAME='c:\Program Files\ \ \Data\Sample.mdf', SIZE=10MB,
MAXSIZE=15MB, FILEGROWTH=20%) LOG ON
( NAME=SampleLog, FILENAME= 'c:\Program Files\ \ \Data\Sample.ldf', SIZE=3MB,
MAXSIZE=5MB, FILEGROWTH=1MB) COLLATE SQL_Latin1_General_Cp1_CI_AS
CREATE DATABASE Sample ON
PRIMARY ( NAME=SampleData, FILENAME='c:\Program Files\ \ \Data\Sample.mdf', SIZE=10MB,
MAXSIZE=15MB, FILEGROWTH=20%) LOG ON
( NAME=SampleLog, FILENAME= 'c:\Program Files\ \ \Data\Sample.ldf', SIZE=3MB,
MAXSIZE=5MB, FILEGROWTH=1MB) COLLATE SQL_Latin1_General_Cp1_CI_AS
Trang 9Setting & Viewing Database Options
Set Database Options By Using:
SQL Server Management Studio
ALTER DATABASE statement
Database Option Categories
Trang 10Retrieving Database Information
Determining database properties by using the
(‘pubs’,’useraccess’)
Using system stored procedures to display
information about databases and its parameters
Trang 11Attaching an Existing Database
Trang 12Creating a Snapshot Database
Trang 13Managing Databases
Managing Data and Log File Growth
Monitoring and Expanding a Transaction Log
Shrinking a Database or File
Dropping a Database
Trang 14Managing Data and Log File Growth
ALTER DATABASE Sample MODIFY FILE ( NAME = 'SampleLog', SIZE = 15MB)
GO
ALTER DATABASE Sample ADD FILE
(NAME = SampleData2, FILENAME='c:\Program Files\ \ \
Data\Sample2.ndf', SIZE=15MB,
MAXSIZE=20MB) GO
ALTER DATABASE Sample MODIFY FILE ( NAME = 'SampleLog', SIZE = 15MB)
GO
ALTER DATABASE Sample ADD FILE
(NAME = SampleData2, FILENAME='c:\Program Files\ \ \
Data\Sample2.ndf', SIZE=15MB,
MAXSIZE=20MB) GO
Using Automatic File Growth
Expanding Database Files
Adding Secondary Database Files
Trang 15Monitoring and Expanding a Transaction Log
Monitoring the log
Monitoring situations that produce extensive log activity
Mass loading of data into indexed table
Large transactions
Performing logged text or image operations
Expanding the log when necessary
Trang 16Shrinking a Database or File
Shrinking an Entire Database
Shrinking a Data File in the Database
Shrinking a Database Automatically
Set autoshrink database option to true
DBCC SHRINKDATABASE (Sample, 25)
DBCC SHRINKFILE (Sample_Data, 10)
Trang 17Dropping a Database
DROP DATABASE Northwind, pubs
Methods of Dropping a Database
SQL Server Enterprise Manager
DROP DATABASE statement
Restrictions on Dropping a Database
While it is being restored
When a user is connected to it
When publishing as part of replication
If it is a system database
Trang 20 char, varchar, text
Unicode character string
nchar, nvarchar, ntext
Binary character string
binary, varbinary, image
Others
sql_variant, timestamp, xml…
Trang 21User-defined Data Type
Extending the SQL type system as
alias data types that consist of a single SQL Server system data type or
structure of multiple data types having behaviors (CLR Type)
Trang 23 Allowing relationships among data elements within a table
Representing a position in a hierarchy
Storing values that represent nodes in a hierarchy tree
Implemented as a CLR UDT
Trang 24CREATE TABLE employee
( EmployeeID int NOT NULL,
EmpName varchar(20) NOT NULL,
Title varchar(20) NULL,
Salary decimal(18, 2) NOT NULL,
hireDate datetimeoffset(0) NOT NULL,
OrgNode HIERARCHYID NOT NULL )
Methods for creating and operating on hierarchy nodes
GetAncestorGetRoot
IsDescendantParse
GetDescendantGetLevel
ReparentTostring
Trang 25Spatial Data Types
Storing geographic locations and shapes such as landmarks, roads, building, …
Based on vector model specified in Known Text (WKT) or Known Binary (WKB) format (recommended by Open Geospatial Consortium)
Trang 26Geography & Geometry Data Type
Trang 27Performing Spatial Operations
Both types provide static and instance methods
Calculate distances, find intersections, etc
Trang 28XML Data Type
Used to store XML documents or fragments of XML
Possibility to register XML schemas and store schema
information within the database
Automatic validation of XML documents
Automatic shredding of the XML data to support efficient querying and updating of the content
Searching and updating via an implementation of XQuery and DML
Trang 29 Declaration is (mostly) like other data types
Table: CREATE TABLE T(MyXml XML)
Variable: DECLARE @MyXml XML
Usage is (mostly) like other data types
Query: SELECT MyXml from T
Variable: SET @MyXml = ‘<size>12</size>’
Some of the limitations:
Does not support converting to text or ntext.
Cannot be compared or sorted So, no GROUP BY, PRIMARY KEY, etc.
Cannot be used as a parameter to any scalar, built-in functions other than ISNULL, COALESCE, and DATALENGTH.
Stored semantically The order of attributes and insignificant white
spaces are not preserved
Trang 30Creating XML Data
Converting Strings
Most common way to create XML
E.g SET @MyXml = ‘<size>12</size>’
Bulk Loading using OPENROWSET
Easiest way to load XML from a file
FOR XML clause in SELECT
Easiest way to convert from table data
Trang 31XML Schema Collections
A schema is a description of a type of XML document (e.g order)
Schema collections validate XML vs schema (XSD)
Creating
CREATE XML SCHEMA COLLECTION <xsd>
Can use either a string or xml variable for xsd
Managing can be tricky
ALTER ADD for new schemas, elements
DROP to delete them Can’t have any dependencies.
Some of the limitations
Lax validation, xsd:include, xsd:key, xsd:keyref not supported.
Time zone always normalized to GMT.
Very large schemas will cause errors due to stack limits
Trang 32XML Data Type Methods
XML Data Type is the only type that supports operations
Query() – returns XML from XQuery expression
Value() – returns SQL type from XQuery
Exist() – bool if XQuery exists
Modify() – changes XML using XQuery
Nodes() – shreds XML into relational data; think of it as a table valued split
Trang 33Storing Document & Multimedia
• Low cost per GB
• Streaming Performance
• Complex application development &
deployment
• Integration with structured data
• File size limitations
• Highest cost per GB
• Lower cost per GB at scale
• Scalability &
Expandability
• Complex application development &
deployment
• Separate data management
• Enterprise-scales only
Example • Windows File Servers
• NetApp NetFiler • EMC Centera
• Fujitsu Nearline • SQL Server
VARBINARY(MAX)
Use File Servers
Use File Servers
DB
Application
BLOBs
Dedicated BLOB Store
Dedicated BLOB Store
DB
Application
BLOBs
Store BLOBs in Database
Store BLOBs in Database
DB
Application
BLOBs
Trang 34BLOB Storage in SQL Server
Remote BLOB Storage SQL BLOB FILESTREAM Storage
Use File Servers
Use File Servers
DB
Application
BLOB
Dedicated BLOB Store
Dedicated BLOB Store
D B
D B
Store BLOBs
in DB + File System
Application
BLOB
DB
Trang 35FILESTREAM Data Type
Storage Attribute on VARBINARY(MAX)
Unstructured data stored directly in the file
Size limit is the file system volume size
SQL Server Security Stack
Store BLOBs in DB + File System
Store BLOBs in DB + File System
Application
BLOB
DB
Trang 36BLOB Storage Vision
File Stores / BLOB Stores
SQL BLOBs Remote BLOB
Store API FILESTREAM
Streaming
Performance Depends on
external store external store Depends on
Link Level Consistency
Data Level
Consistency
Integrated Management
Non-local Windows
Interop with External
Trang 37Creating Tables
Determining column & data type
Determining column nullability
Defining column default values
Trang 38CREATE TABLE dbo.Categories
nvarchar(15) ntext
image
int IDENTITY (1,1)
nvarchar(15) ntext
image
NOT NULL, NOT NULL, NULL,
NULL)
NOT NULL, NOT NULL, NULL,
NULL)
Trang 39Modifying Table Definition
ALTER TABLE table_name
{[ALTER COLUMN column_name
|DROP
{[ CONSTRAINT ] constraint_name | COLUMN column }
]}
Trang 40ALTER TABLE CategoriesNew
DROP COLUMN Sales_date
ALTER TABLE CategoriesNew
DROP COLUMN Sales_date
DROP
Customer_name Sales_amount Sales_date Customer ID Commission
Trang 42Views
Trang 44Summary
Data definition language
Creating and managing database object
Create, Use, Alter, Drop,
SQL Server database objects
database, table, view, index, …
Simplifying the management of more complicated data
Trang 45Microsoft