Professional Documents
Culture Documents
Vu Tuyet Trinh
trinhvt-fit@mail.hut.edu.vn
Hanoi University of Technology
1
Overview of Transact-SQL
Microsoft
Data Definition Language
Create
used to create databases and their objects.
Use
allows you to specify the database you wish to work with within
your DBMS.
Alter
used to modify the definition of it without deleting it
Drop
used to remove entire database objects
Microsoft
Overview of Database Objects
Microsoft
Outline
Microsoft
Databases in SQL Server
Database
Storing data and other database objects
Database Snapshot
Maintain historical data for report
generation
SQL Server
Safeguard data against administrative Enterprise Edition
error
Microsoft
Creating a New Database
Factors to consider
Default: Sysadmin, dbcreator
Creator becomes the owner
Maximum of 32,767 per server
Follow naming rules
Microsoft
Creating a New Database
Some arguments:
The name of the database
The size of the database
The files where the database will reside
CREATE
CREATE DATABASE
DATABASE Sample
Sample
ON
ON
PRIMARY
PRIMARY (( NAME=SampleData,
NAME=SampleData,
FILENAME='c:\Program
FILENAME='c:\Program Files\..\..\Data\Sample.mdf',
Files\..\..\Data\Sample.mdf',
SIZE=10MB,
SIZE=10MB,
MAXSIZE=15MB,
MAXSIZE=15MB,
FILEGROWTH=20%)
FILEGROWTH=20%)
LOG
LOG ONON
(( NAME=SampleLog,
NAME=SampleLog,
FILENAME=
FILENAME= 'c:\Program
'c:\Program Files\..\..\Data\Sample.ldf',
Files\..\..\Data\Sample.ldf',
SIZE=3MB,
SIZE=3MB,
MAXSIZE=5MB,
MAXSIZE=5MB,
FILEGROWTH=1MB)
FILEGROWTH=1MB)
Microsoft
COLLATE
COLLATE SQL_Latin1_General_Cp1_CI_AS
SQL_Latin1_General_Cp1_CI_AS
Setting & Viewing Database Options
Microsoft
Retrieving Database Information
Determining database properties by using the
DATABASEPROPERTYEX Function
SELECT DATABASEPROPERTYEX
(‘pubs’,’useraccess’)
SELECT DATABASEPROPERTYEX (‘pubs’,’recovery’)
Microsoft
Attaching an Existing Database
Microsoft
Creating a Snapshot Database
Microsoft
Managing Databases
Microsoft
Managing Data and Log File Growth
Using Automatic File Growth
Expanding Database Files
Adding Secondary Database Files
ALTER
ALTER DATABASE
DATABASE Sample
Sample
MODIFY
MODIFY FILE
FILE (( NAME
NAME == 'SampleLog',
'SampleLog',
SIZE
SIZE == 15MB)
15MB)
GO
GO
ALTER
ALTER DATABASE
DATABASE Sample
Sample
ADD
ADD FILE
FILE
(NAME
(NAME == SampleData2,
SampleData2,
FILENAME='c:\Program
FILENAME='c:\Program Files\..\..\
Files\..\..\
Data\Sample2.ndf',
Data\Sample2.ndf',
SIZE=15MB,
SIZE=15MB,
Microsoft
MAXSIZE=20MB)
MAXSIZE=20MB)
GO
GO
Monitoring and Expanding a Transaction Log
Microsoft
Shrinking a Database or File
Shrinking an Entire Database
DBCC
DBCC SHRINKDATABASE
SHRINKDATABASE (Sample,
(Sample, 25)
25)
DBCC
DBCC SHRINKFILE
SHRINKFILE (Sample_Data,
(Sample_Data, 10)
10)
Shrinking a Database Automatically
Set autoshrink database option to true
Microsoft
Dropping a Database
Methods of Dropping a Database
SQL Server Enterprise Manager
DROP DATABASE statement
DROP
DROP DATABASE
DATABASE Northwind,
Northwind, pubs
pubs
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
Microsoft
Outline
Microsoft
Data Types
Relational data
User-defined Data
CLR types
Spatial data
Filestreams
XML
Microsoft
System Data Types
Exact numeric
bit, tinyint, smallint, int, bigint, numeric, decimal, smallmoney, money
Approximate numeric
float, Real
Date & Time
datetime, smalldatetime
Character string
char, varchar, text
Unicode character string
nchar, nvarchar, ntext
Binary character string
binary, varbinary, image
Others
sql_variant, timestamp, xml…..
Microsoft
User-defined Data Type
Microsoft
New Date & Time Data Types
DATE
Date only type
TIME
Time only type
DATETIMEOFFSET
Time zone aware datetime type
DATETIME2
Datetime type w/large fractional seconds and year range than
the existing DATETIME type
Microsoft
HierarchyID Data Type
Microsoft
HierarchyID Data Type
/
Microsoft
Geography & Geometry Data Type
Microsoft
Performing Spatial Operations
SELECT StreetName
FROM Streets
WHERE Streets.StreetGeo.STIntersects(@ms) = 1
Microsoft
XML Data Type
Used to store XML documents or fragments of XML
Microsoft
Using XML Data Type
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.
Microsoft
Creating 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
Microsoft
XML 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
Microsoft
XML Data Type Methods
Microsoft
Storing Document & Multimedia
Use File Servers Dedicated BLOB Store BLOBs in
Store Database
Application Application Application
DB DB DB
Microsoft
BLOB Storage in SQL Server
Use File Servers
Application
BLOB
Store BLOBs in
DB Store BLOBs in
Database
DB + File System
Application
Application
Dedicated BLOB BLOB
BLOB
Store
Application
BLOB
DB DB
DB
Microsoft
FILESTREAM Data Type
Store BLOBs in DB +
Storage Attribute on VARBINARY(MAX) File System
Unstructured data stored directly in the file
system (requires NTFS)
Application
Dual Programming Model
TSQL (Same as SQL BLOB)
Win32 Streaming APIs with T-SQL BLOB
transactional semantics
Data Consistency
Integrated Manageability
Back Up / Restore
Administration
DB
Size limit is the file system volume size
SQL Server Security Stack
Microsoft
BLOB Storage Vision
File Stores / SQL BLOBs Remote BLOB
FILESTREAM
BLOB Stores Store API
Data Level
Consistency
Integrated
Management
Non-local Windows
File Servers
n/a Post-2008
Microsoft
Example
CREATE
CREATE TABLE
TABLE dbo.Categories
dbo.Categories
(CategoryID
(CategoryID int
int IDENTITY
IDENTITY
(1,1)
(1,1) NOT
NOT NULL,
NULL,
CategoryName nvarchar(15) NOT
CategoryName nvarchar(15) NOT NULL,
NULL,
Description
Description ntext
ntext NULL,
NULL,
Picture
Picture image
image NULL)
NULL)
Microsoft
Modifying Table Definition
ALTER TABLE table_name
{[ALTER COLUMN column_name
{DROP DEFAULT
|SET DEFAULT constant_expression
|IDENTITY [(seed,increment)]}
|ADD
{< column_definition >|< table_constraint>}
[ ,...n ]
|DROP
{[ CONSTRAINT ] constraint_name
| COLUMN column }
]}
Microsoft
Example
ADD ALTER
ALTER TABLE
TABLE CategoriesNew
CategoriesNew
ADD
ADD Commission
Commission money
money null
null
Customer_name
Customer_name Sales_amount
Sales_amount Sales_date
Sales_date Customer
CustomerIDID Commission
Commission
DROP
ALTER
ALTER TABLE
TABLE CategoriesNew
CategoriesNew
DROP
DROP COLUMN
COLUMN Sales_date
Sales_date
Microsoft
Outline
Microsoft
Views
What is a view?
Creatinga virtual collection of records from existing tables
Being used for security and/or performance issues
Creating view
CREATE/ALTER/DROP RULE …
CREATE/ALTER/DROP PROCEDURE …
CREATE/ALTER/DROP FUNCTION …
CREATE/ALTER/DROP TRIGGER …
CREATE/ALTER/DROP USER …
…
For further detail information, see [Microsoft SQL Server Books Online ]
Microsoft
Summary
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
Relational data
User-defined Data
CLR types
Spatial data
Filestreams
XML
Microsoft 44
Microsoft