You are on page 1of 45

T-SQL for Data Definition

Vu Tuyet Trinh
trinhvt-fit@mail.hut.edu.vn
Hanoi University of Technology

1
Overview 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

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

 Data Definition Language


 Managing Databases
 Data Types
 Managing Tables
 Managing other SQL Server Objects

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

 Safeguard data against user 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

 Set Database Options By Using:


 SQL Server Management Studio
 ALTER DATABASE statement
 Database Option Categories
 Auto options
 Cursor options
 Recovery options
 SQL options
 State options

Microsoft
Retrieving Database Information
 Determining database properties by using the
DATABASEPROPERTYEX Function
 SELECT DATABASEPROPERTYEX
(‘pubs’,’useraccess’)
 SELECT DATABASEPROPERTYEX (‘pubs’,’recovery’)

 Using system stored procedures to display


information about databases and its parameters
 sp_helpdb
 sp_helpdb database_name
 sp_spaceused [objname]

Microsoft
Attaching an Existing Database

Microsoft
Creating a Snapshot Database

Microsoft
Managing Databases

 Managing Data and Log File Growth


 Monitoring and Expanding a Transaction Log
 Shrinking a Database or File
 Dropping a Database

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

 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

Microsoft
Shrinking a Database or File
 Shrinking an Entire Database
DBCC
DBCC SHRINKDATABASE
SHRINKDATABASE (Sample,
(Sample, 25)
25)

 Shrinking a Data File in the Database

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

 Data Definition Language


 Managing Databases
 Data Types
 Managing Tables
 Managing other SQL Server Objects

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

 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)

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

 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

Microsoft
HierarchyID Data Type
/

 Example /1/ /2/ /3/


CREATE TABLE employee
( EmployeeID int NOT NULL,
EmpName varchar(20) NOT NULL, /2/1 /3/1/
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
GetAncestor GetDescendant
GetRoot GetLevel
IsDescendant Reparent
Microsoft Parse Tostring
Spatial Data Types
 Storing geographic locations and shapes such as landmarks, roads,
building, …
 Based on vector model specified in Well-Known Text (WKT) or Well-
Known Binary (WKB) format (recommended by Open Geospatial
Consortium)

Microsoft
Geography & Geometry Data Type

Microsoft
Performing Spatial Operations

 Both types provide static and instance methods


 Calculate distances, find intersections, etc.

Find streets that intersect the Microsoft campus

SELECT StreetName
FROM Streets
WHERE Streets.StreetGeo.STIntersects(@ms) = 1

Microsoft
XML 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 XML-


DML

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

 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

Microsoft
Storing Document & Multimedia
Use File Servers Dedicated BLOB Store BLOBs in
Store Database
Application Application Application

BLOBs BLOBs BLOBs

DB DB DB

• Low cost per GB • Lower cost per GB at scale • Integrated management


Advantages
• Streaming Performance • Scalability & Expandability • Data-level consistency

• Complex application • Complex application • Poor data streaming support


Challenges development & deployment development & deployment • File size limitations
• Integration with structured data • Separate data management • Highest cost per GB
• Enterprise-scales only
• Windows File Servers • EMC Centera • SQL Server
Example • NetApp NetFiler • Fujitsu Nearline VARBINARY(MAX)

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

Remote BLOB Storage SQL BLOB FILESTREAM Storage

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

Streaming Depends on Depends on


Performance external store external store

Link Level Consistency

Data Level
Consistency

Integrated
Management

Non-local Windows
File Servers
n/a Post-2008

Interop with External


BLOB Stores
n/a
Microsoft
Creating Tables

 Determining column & data type


 Determining column nullability
 Defining column default values

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

 Data Definition Language


 Managing Databases
 Data Types
 Managing Tables
 Managing other SQL Server Objects

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 VIEW [schema_name.]view_name


[(column[,...n])]
[ WITH <view_attribute> [ ,...n ] ]
AS
select_statement
[ WITH CHECK OPTION ] [ ; ]
<view_attribute>::={[ENCRYPTION]
 Removing view
[SCHEMABINDING]
[ VIEW_METADATA ]}

DROP VIEW { view_name } [ ,...n ]


Microsoft
Others CREATE/ALTER/DROP… command

 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

You might also like