You are on page 1of 50

SQL-SERVER DATABASE TRAINING DOCUMENTATION

Version No.1.0
15th Feb 2010

Last Edited:

S. Rishma & S. Saravana Kumar Page 1 of 50


Table of contents

1.0 Introduction........................................................................................................................................................................6
2.0 SQL.....................................................................................................................................................................................6
2.1 Different roles of SQL.................................................................................................................................. 6
3.0 Features..............................................................................................................................................................................7
3.1 Enterprise Data Management...................................................................................................................... 7
3.2 Developer Productivity................................................................................................................................. 8
3.3 Business Intelligence................................................................................................................................... 8
4.0 Data types...........................................................................................................................................................................9
5.0 Database............................................................................................................................................................................11
5.1 SQL Server System Databases................................................................................................................. 11
6.0 Tables................................................................................................................................................................................13
6.1 Keys and Constraints................................................................................................................................. 13
6.2 Relationship between the tables................................................................................................................ 14
6.2.1 Types of Relationships..........................................................................................................14
6.3 Table Creation........................................................................................................................................... 16
7.0 Clauses..............................................................................................................................................................................18
7.1 Select......................................................................................................................................................... 18
7.2 Distinct....................................................................................................................................................... 18
7.3 Into............................................................................................................................................................. 18
7.4 Where........................................................................................................................................................ 18
7.5 Group By.................................................................................................................................................... 18
7.6 Having........................................................................................................................................................ 19
7.7 Order By.................................................................................................................................................... 19
8.0 Joins..................................................................................................................................................................................20
8.1 Types of joins............................................................................................................................................. 20
9.0 Views.................................................................................................................................................................................24
10.0 Triggers...........................................................................................................................................................................26

Last Edited:

S. Rishma & S. Saravana Kumar Page 2 of 50


10.1 The need and the usage.......................................................................................................................... 26
10.2 Types of trigger events............................................................................................................................ 26
11.0 Cursors............................................................................................................................................................................27
11.1 Types of cursors...................................................................................................................................... 28
11.2 Drawbacks of Cursors.............................................................................................................................. 28
12.0 CASE Statements...........................................................................................................................................................29
13.0 Temporary tables...........................................................................................................................................................30
14.0 Table variables...............................................................................................................................................................31
14.1 Disadvantages of table variable over temporary table.............................................................................32
15.0 Stored Procedure...........................................................................................................................................................32
15.1 Benefits of Stored Procedure:.................................................................................................................. 34
16.0 Functions........................................................................................................................................................................34
16.1 User Defined Functions........................................................................................................................... 34
16.2 Split function............................................................................................................................................ 35
17.0 Locking in SQL server..................................................................................................................................................36
18.0 Index................................................................................................................................................................................36
18.1 Types....................................................................................................................................................... 36
18.2 Index Architecture.................................................................................................................................... 37
18.3 Index implementations............................................................................................................................. 37
18.4 Index Optimization Tips........................................................................................................................... 38
19.0 Query Optimization Tips..............................................................................................................................................39
20.0 Execution Plan...............................................................................................................................................................39
20.1 Graphical Plan......................................................................................................................................... 40
20.1.1 Table Scan...........................................................................................................................40
20.1.3 Clustered Index Scan...........................................................................................................41
20.1.4 Non-clustered Index Scan....................................................................................................41
20.1.5 Index Seek...........................................................................................................................41
20.1.6 Clustered Index Seek...........................................................................................................41
20.2 Plan Interpretation................................................................................................................................... 42
20.2.1 ToolTips...............................................................................................................................42
21.0 SQL Server security model...........................................................................................................................................42
21.1 Create Login............................................................................................................................................ 43
Last Edited:

S. Rishma & S. Saravana Kumar Page 3 of 50


21.2 Create Users............................................................................................................................................ 45
21.3 Roles........................................................................................................................................................ 46
22.0 SQL Syntax.....................................................................................................................................................................46
23.0 Conclusion......................................................................................................................................................................49
23.1 Attachments............................................................................................................................................. 49

SQL PRACTICE Query-Rishma.rar SQL PRACTICE Query-Saravanakumar.rar


.......................................49
23.2 Reference Links....................................................................................................................................... 50

Last Edited:

S. Rishma & S. Saravana Kumar Page 4 of 50


1.0 Introduction
This document throws light on various interesting sections like features of SQL Server, the SQL
concepts, basic concepts of database, table structure, how data can be effectively stored and retrieved from
a database table and provides tips to optimize the SQL queries in applications.

It is prepared on the basis of conceptual knowledge rather than theoretical knowledge. It will provide a
clear view of handling, creating and maintaining databases in the applications.

Microsoft SQL Server is a full-featured relational database management system (RDBMS) that offers a
variety of administrative tools to ease the burdens of database development, maintenance and
administration. In this article, some of the important topics have been covered about SQL Server like
features and Execution Plan.

And it provides plenty of tables and diagrams for visual interpretation and example coding have been
zipped and attached for reference at the end of this document.

2.0 SQL
Structured Query Language (SQL) is a standard language for accessing and manipulating databases.
The SQL language is sub-divided into several language elements, including

 Clauses which are in some cases optional, constituent components of statements and queries.
 Expressions which can produce either scalar values or tables consisting of columns
and rows of data.
 Predicates which specify conditions that can be evaluated to SQL three-valued logic (3VL)
Boolean truth values and which are used to limit the effects of statements and queries, or to
change program flow.
 Queries which retrieve data based on specific criteria.
 Statements which may have a persistent effect on schemas and data, or which may control
transactions, program flow, connections, sessions, or diagnostics.

SQL statements also include the semicolon (";") statement terminator. Though not required on
every platform, it is defined as a standard part of the SQL grammar.

2.1 Different roles of SQL

 SQL is an interactive query language. Users type SQL commands into an interactive SQL
program to retrieve data and display it on the screen, providing a convenient, easy-to-use tool
for ad hoc database queries.
 SQL is a database programming language. Programmers embed SQL commands into their
application programs to access the data in a database. Both user written programs and

Last Edited:

S. Rishma & S. Saravana Kumar Page 5 of 50


database utility programs (such as report writers and data entry tools) use this technique for
database access.
 SQL is a database administration language. The database administrator responsible for
managing a minicomputer or mainframe database uses SQL to define the database structure
and control access to the stored data.
 SQL is a client/server language. Personal computer programs use SQL to communicate over
a network with database servers that store shared data. This client/server architecture has
become very popular for enterprise-class applications.
 SQL is an Internet data access language. Internet web servers that interact with corporate
data and Internet applications servers all use SQL as a standard language for accessing
corporate databases.
 SQL is a distributed database language. Distributed database management systems use
SQL to help distribute data across many connected computer systems. The DBMS software on
each system uses SQL to communicate with the other systems, sending requests for data
access.
 SQL is a database gateway language. In a computer network with a mix of different DBMS
products, SQL is often used in a gateway that allows one brand of DBMS to communicate with
another brand.

3.0 Features
Various features of SQL Server 2005 are enterprise data management, developer productivity and
business intelligence which are discussed as follows.

3.1 Enterprise Data Management

 High Availability
Failover clustering and database mirroring technology in SQL Server 2005 enables enterprises
to deliver highly reliable, available applications to employees, customers, and partners.
 Management Tools
SQL Server 2005 introduces an integrated suite of management tools and management
application programming interfaces (APIs) to provide ease of use, manageability, and support
for operating large-scale SQL Server deployments.
 Security Enhancements
SQL Server 2005 has been designed to help provide the highest level of security for enterprise
data through features such as database encryption, more secure default settings, password
policy enforcement, granular permissions control, and an enhanced security model.
 Scalability
Scalability advancements in SQL Server 2005 include table partitioning, replication
enhancements, and 64-bit support.

Last Edited:

S. Rishma & S. Saravana Kumar Page 6 of 50


3.2 Developer Productivity

 Common Language Runtime (CLR) Integration


SQL Server 2005 introduces the capability to develop database objects using any Microsoft
.NET language.
 Deep XML Integration
SQL Server 2005 delivers a new XML data type, enabling the storage of XML fragments or
documents in SQL Server databases.
 Transact-SQL Enhancements
New query types and the capability to use error handling in transactions provide developers
with more flexibility and control in SQL Server query development.

 SQL Server 2005 Compact Edition


Full integration of SQL Server 2005 Compact Edition with SQL Server 2005 and Visual Studio
2005 provides a platform for developers to rapidly build applications that extend enterprise data
management capabilities to mobile devices.

3.3 Business Intelligence

 Analysis Services
Analysis Services provides a unified and integrated view of all your business data as the
foundation for all of your traditional reporting, OLAP analysis, Key Performance Indicator (KPI)
scorecards and data mining.
 Integration Services
SQL Server Integration Services (SSIS) is a next generation data integration platform that can
integrate data from any source. SSIS provides a scalable and extensible platform that
empowers development teams to build, manage, and deploy integration solutions to meet
unique integration needs.

 Reporting Services
SQL Server Reporting Services is a comprehensive, server-based reporting solution designed
to help you author, manage, and deliver both paper-based and interactive Web-based reports.
 Data Mining
SQL Server 2005 Analysis Services (SSAS) provides tools for data mining with which you can
identify rules and patterns in your data, so that you can determine why things happen and
predict what will happen in the future giving you powerful insight that will help your company
make better business decisions.

Last Edited:

S. Rishma & S. Saravana Kumar Page 7 of 50


4.0 Data types
In this session we learnt about the various data types available in SQL server 2005 and discussed
about some real time usage of the data types.

We also learnt the importance of choosing correct data type for storing a particular type of data.

The following are various data types available in the SQL server 2005.

NUMBER OF
DATA TYPE COMMENTS
BYTES

tinyint 1  

smallint 2  
Integer
int 4  

bigint 8  

decimal[p[,s]] 5-17  
Exact numeric
numeric[p[,s]] 5-17  

Appropriate float[(n)[ 8  

numeric real 4  

smallmoney 4  
Monetary
money 8  

smalldatetime 4  
Date and time
datetime 8  

Characters char[(n)] 0-8000 non-Unicode

varchar[(n)] 0-8000 non-Unicode

non-Unicode, 16 bytes pointer on row,


varchar(max) 0-2 GB
,preferred over text data type

text 0-2 GB non-Unicode, 16 bytes pointer or in row,

Last Edited:

S. Rishma & S. Saravana Kumar Page 8 of 50


obsolete, varchar(max) preferred

nchar[(n)] 0-8000 max 4000 Unicode characters

nvarchar[(n)] 0-8000 max 4000 Unicode characters

16 bytes pointer or in row, ,preferred over ntext


nvarchar(max) 0-2 GB
data type

16 bytes pointer, obsolete, nvarchar(max)


ntext 0-2 GB
preferred

binary[(n)] 0-8000  

varbinary[(n)] 0-8000  
Binary
16 bytes pointer or in row, ,preferred over
varbinary(max) 0-2 GB
image data type

16 bytes pointer, obsolete, varbinary(max)


Image image 0-2 GB
preferred

Global identifier uniqueidentifier 16  

XML xml 0-2GB 16 bytes pointer

bit 1 1 byte for every 8 bit columns

cursor 0-8  

timestamp 8 one column per table


Special
sysname 256  

table -  

sql_variant 0-8016  

Table 4.1. Data types in SQL Server

Last Edited:

S. Rishma & S. Saravana Kumar Page 9 of 50


5.0 Database
A database is an integrated collection of logically-related records or files consolidated into a common
pool that provides data for one or more multiple uses.

5.1 SQL Server System Databases

System Database Purpose Functionality

Master Core system database to manage The first database in the SQL
the SQL Server instance. In SQL Server Server startup process
2005, the Master database is the logical In SQL Server 2005, needs to
repository for the system objects residing reside in the same directory as the
in the sys schema. In SQL Server 2000 Resource database
and previous editions of SQL Server, the
Master database physically stored all of
the system objects.
Resource The Resource database is Introduced in SQL Server 2005
responsible for physically storing all of to help manage the upgrade and
the SQL Server 2005 system objects. rollback of system objects.
This database has been created to
improve the upgrade and rollback of SQL Prior to SQL Server 2005 the
Server system objects with the ability to system related data was stored in
overwrite only this database. the master database.

Read-only database that is not


accessible via the SQL Server
2005 tool set.

The database ID for the


Resource database is 32767.

The Resource database does


not have an entry in
master.sys.databases.

TempDB Temporary database to store Each time a SQL Server


temporary tables (#temptable or ## instance is rebooted, the TempDB
temptable), table variables, cursors, work database is reset to its original
tables, row versioning, create or rebuild state
indexes sorted in TempDB, etc. Each
time the SQL Server instance is restarted
all objects in this database are destroyed,
so permanent objects cannot be created
Last Edited:

S. Rishma & S. Saravana Kumar Page 10 of 50


in this database.

Model Template database for all user User defined tables, stored
defined databases procedures, user defined data
types, etc can be created in the
Model database and will exist in all
future user defined databases.

The database configurations


such as the recovery model for the
Model database are applied to
future user defined databases.

MSDB Primary database to manage the Provides some of the


SQL Server Agent configurations configurations for the SQL Server
Agent service.

For the SQL Server 2005


Express edition installations, even
though the SQL Server Agent
service does not exist, the
instance still has the MSDB
database.
Distribution Primary data to support SQL Server
replication
ReportServer Primary database for Reporting
Services to store the meta data and
object definitions
ReportServerTempDB Temporary storage for Reporting
Services

Table 5-1. Types of Databases


5.2 Database Creation
 The syntax for creating a database is given as follows.
Syntax
Create Database <database name>

 To create tables inside the database.


Use Database

Last Edited:

S. Rishma & S. Saravana Kumar Page 11 of 50


6.0 Tables
A table is a set of data elements that are organized using vertical columns and horizontally
rows. A table has a specified number of columns, but can have any number of rows.

6.1 Keys and Constraints

A key is a way of identifying a record in a database table. We can use keys to build
relationships between tables because a key refers to a whole record.
A key can be defined on a single column if that’s enough to identify the record, or it can be
defined on more than one column if not. The sections that follow introduce the three kinds of keys you
can use in a database.

Some of the keys available in SQL server are


a. Primary key: Allows each row in a table to be uniquely identified and Ensure that no
duplicate rows exist and no null values are entered.
b. Unique key: It is used to prevent the duplication of key values within the rows of a table and
allow null values.
c. Foreign key: A foreign key is a column or combination of columns that is used to establish
and enforce a link between the data in two tables
d. Composite keys: Sometimes it requires more than one attribute to uniquely identify an
entity. A primary key that made up of more than one attribute is known as a composite key
Constraints are used to limit the type of data that can go into a table. They are
associated with create or alter statements.
Constraints Enforcement
NOT NULL Column to not accept null
values
UNIQUE Uniquely identifies each
record
PRIMARY KEY Uniquely identifies each
record and cannot have
null value
FOREIGN KEY Foreign key in one table
points to a primary key in
another table.

Last Edited:

S. Rishma & S. Saravana Kumar Page 12 of 50


It is mainly used for
creating relationship
between tables
CHECK Limit the value range that
can be placed in a
column
DEFAULT Insert a default value into
a column
Table 6-1 Constraints and Enforcement

6.2 Relationship between the tables

A relationship in a SQL Server database is a logical link between two tables. It is impossible to
have a physical link. When defining a logical relationship, we’re informing SQL Server that we’ll be
linking a primary key from the master table to a foreign key in another table. So already there is a need
for two keys: one on each table.

6.2.1 Types of Relationships


There are three relationships available between the tables and are discussed as follows

One-To-One Relationships
A one-to-one relationship is created if both of the related columns are primary keys or have
unique constraints.
Example:
To illustrate the one-to-one relationship, imagine that in our example bank database there is a
table that holds PIN numbers for ATM cards, keeping them completely separate from the
remainder of the customer records (see Figure 3-1). In most cases, there would be one PIN
number record for each customer record, but there may be exceptions—for instance, a high
interest deposit account may not have a card, and therefore there would be no associated PIN
number record.

Last Edited:

S. Rishma & S. Saravana Kumar Page 13 of 50


Fig 6.2.1. One-To-One Relationships

One-To-Many Relationships   
A one-to-many relationship is the most common type of relationship. In this type of relationship,
a row in table A can have many matching rows in table B, but a row in table B can have only one
matching row in table A.
Example:
Using our banking example, say we have a customer master record along with any number of
associated transaction records. The number of these transaction records could range from
none, which corresponds to when a customer is new to the bank and hasn’t made a deposit or
performed a transaction, to one or more, which corresponds to when there has been an initial
deposit in an account, and then further deposits or withdrawal transactions after that.

Fig 6.2.2. One-To-Many Relationships


Last Edited:

S. Rishma & S. Saravana Kumar Page 14 of 50


Many-To-Many Relationships    
In a many-to-many relationship, a row in table A can have many matching rows in table B, and
vice versa.
Example:
An example of a many-to-many relationship might be where a company has several depots for
dispatching goods, seen as the master table, which then dispatch goods to many stores, seen
as the child, The depots could be located and organized so that different depots could all
supply the same store, and they could be arranged in groups of produce, frozen, perishables,
and bonded. In order for a store to be supplied with a full complement of goods, it would need
to be supplied by a number of different depots, which would typically be in different locations.

Fig 6.2.3. Many-To-Many Relationships

6.3 Table Creation

The following example shows the table creation and the relationship diagram for student mark
list.
Queries:
create table CourseDetail ( CourseID INTEGER PRIMARY KEY NOT NULL,
CourseName VARCHAR(20))

create table GradeDetail ( GradeID INTEGER PRIMARY KEY NOT NULL,


GradeName VARCHAR(20))

create table StudentDetail ( StudentID INTEGER PRIMARY KEY NOT NULL,


StudentName VARCHAR(20),
Address VARCHAR(50),
CourseID INTEGER FOREIGN KEY
REFERENCES CourseDetail(CourseID))
Last Edited:

S. Rishma & S. Saravana Kumar Page 15 of 50


create table MarkDetail ( StudentID INTEGER FOREIGN KEY
REFERENCES StudentDetail(StudentID),
Mark INTEGER,
GradeID INTEGER FOREIGN KEY
REFERENCES GradeDetail(GradeID) )
Relationship Diagram:

Fig 6.3.1. Relationship Diagram

7.0 Clauses

7.1 Select

The SELECT statement is used to select data from a database. The result is stored in a result
table, called the result-set.

Syntax:
SELECT column_name(s)
FROM table_name

Last Edited:

S. Rishma & S. Saravana Kumar Page 16 of 50


7.2 Distinct

In a table, some of the columns may contain duplicate values. This is not a problem, however,
sometimes you will want to list only the different (distinct) values in a table. The DISTINCT keyword can
be used to return only distinct (different) values.

Syntax:
SELECT DISTINCT column_name(s)
FROM table_name

7.3 Into

The SELECT INTO statement selects data from one table and inserts it into a different table.
The SELECT INTO statement is most often used to create backup copies of tables.

Syntax:
SELECT * INTO new_table_name [IN externaldatabase]
FROM old_tablename

7.4 Where

The WHERE clause is used to extract only those records that fulfill a specified criterion.

Syntax:
SELECT column_name(s)
FROM table_name
WHERE column_name operator value

7.5 Group By

SQL- Group By clause, deals with aggregate functions on the column names of a table. It
consolidates and calculates column values into a single record value. GROUP BY requires a list of table
columns on which to run the calculations. We can also use the GROUP BY statement on more than one
column. It will return unique values. Hence it inherits the behavior of “SELECT DISTINCT “command.

Syntax:
SELECT
column_name, aggregate_function (column_name)
FROM table_name
WHERE condition
GROUP BY column_name

Last Edited:

S. Rishma & S. Saravana Kumar Page 17 of 50


7.6 Having

The HAVING clause was added to SQL because the WHERE keyword could not be used with
aggregate functions.

Syntax:
SELECT
column_name,
Aggregate function (column_name)
FROM
table_name
WHERE
column_name operator value
GROUP BY
column_name
HAVING
aggregate_function (column_name) operator value

7.7 Order By

The ORDER BY keyword is used to sort the result-set by a specified column. The ORDER BY
keyword sorts the records in ascending order by default. If you want to sort the records in a descending
order, you can use the DESC keyword.

Syntax:
SELECT
column_name(s)
FROM
table_name
ORDER BY
column_name(s) ASC|DESC

8.0 Joins
SQL joins are used to retrieve data from two or more tables, based on a relationship between certain
columns in the tables.

8.1 Types of joins

A. INNER JOIN
B. LEFT OUTER JOIN
C. RIGHT OUTER JOIN

Last Edited:

S. Rishma & S. Saravana Kumar Page 18 of 50


D. FULL JOIN
E. CROSS JOIN
To explain the types of join we can have the following tables as examples

Table 8-1. StudentDetail

Table 8-2. CourseDetail

A. INNER JOIN: Return rows when there is at least one match in both tables
Example:

SELECT
S.StudentName,
C.CourseName
FROM
StudentDetail S
JOIN CourseDetail c
ON
S.CourseID = C.CourseID
Last Edited:

S. Rishma & S. Saravana Kumar Page 19 of 50


Output table:

B. LEFT OUTER JOIN: Return all rows from the left table, even if there are no matches in the right table
Example:
SELECT
S.StudentName,
C.CourseName
FROM
StudentDetail S
left JOIN
CourseDetail c
ON
S.CourseID = C.CourseID
Output table:

Last Edited:

S. Rishma & S. Saravana Kumar Page 20 of 50


C. RIGHT OUTER JOIN: Return all rows from the right table, even if there are no matches in the left table
Example:
SELECT
S.StudentName,
C.CourseName
FROM
StudentDetail S
RIGHT JOIN
CourseDetail c
ON
S.CourseID = C.CourseID

Output table:

D. FULL JOIN: Return rows when there is a match in one of the tables
Last Edited:

S. Rishma & S. Saravana Kumar Page 21 of 50


Example:
SELECT
S.StudentName,C.CourseName
FROM
StudentDetail S
Full Outer Join
CourseDetail c
ON
S.CourseID = C.CourseID

Output table:

E. CROSS JOIN: Return the Cartesian product of the rows of two tables
Example:
SELECT
S.StudentName,
C.CourseName
FROM
StudentDetail S
Cross Join
CourseDetail c

Last Edited:

S. Rishma & S. Saravana Kumar Page 22 of 50


Output table:

9.0 Views

SQL VIEWS are data objects, and like SQL Tables, they can be queried, updated, and
dropped.

 Views are virtual tables containing columns and rows but the data is generated dynamically
from SQL tables and hence physically it doesn’t exist inside the view itself.
 It always gives updated data.
 A view serves as a security mechanism. This ensures that users are able to retrieve and modify
only the data seen by them. Users cannot see or access the remaining data in the underlying
tables.
 Complex queries can be stored in the form as a view, and data from the view can be extracted
using simple queries.
 Database contains only the definition of the view table, without its definition.
 Database creates ABSTRACTION using views.
 Nested views reduce the complexity of normalization.
 Views are dynamic SQL query .Changes in the base table will be reflected in the subsequent
invocation of views.
 Views can also be removed by using the DROP VIEW command.

Syntax:

CREATE VIEW view_name


AS
Last Edited:

S. Rishma & S. Saravana Kumar Page 23 of 50


SELECT * FROM TABLE_NAME

(Or)

CREATE VIEW view_name


[(column_name[,column_name]….)]
[WITH ENCRYPTION]
AS select_statement [WITH CHECK OPTION]

Sample code:

CREATE VIEW virtualInventory


AS
SELECT * FROM Inventory;

Views ensure the security of data by restricting access to the following data:
 Specific rows of the tables.
 Specific columns of the tables.
 Specific rows and columns of the tables.
 Rows fetched by using joins.
 Statistical summary of data in a given tables.
 Subsets of another view or a subset of views and tables.

Some common examples of views are:


 A subset of rows or columns of a base table.
 A union of two or more tables.
 A join of two or more tables.
 A statistical summary of base tables.
 A subset of another view, or some combination of views and base table.

The restrictions imposed on views are as follows:


 A view can be created only in the current database.
 The name of a view must follow the rules for identifiers and must not be the same as
that of the base table.
 A view can be created only if there is a SELECT permission on its base table.
 A SELECT INTO statement cannot be used in view declaration statement.
Last Edited:

S. Rishma & S. Saravana Kumar Page 24 of 50


 A trigger or an index cannot be defined on a view.
 The CREATE VIEW statement cannot be combined with other SQL statements in
single batch.
 Order By clause cannot be implemented in CREATE VIEW query.

Types of views:

 Read-only
We cannot update the read-only views.
 Updatable-view
We can make changes in the views like update , delete, insert etc;

10.0 Triggers
A trigger is procedural code that is automatically executed in response to certain events on a
particular table or view in a database

10.1 The need and the usage

Triggers are commonly used to:


a) Prevent changes (e.g. Prevent an invoice from being changed after it's been mailed
out)
b) Log changes (e.g. Keep a copy of the old data)
c) Audit changes (e.g. Keep a log of the users and roles involved in changes)
d) Enhance changes (e.g. Ensure that every change to a record is time-stamped by the
server's clock, not the client's)
e) Enforce business rules (e.g. Require that every invoice have at least one line item)
f) Execute business rules (e.g. Notify a manager every time an employee's bank account
number changes)
g) Replicate data (e.g. Store a record of every change, to be shipped to another database
later)
h) Enhance performance (e.g. Update the account balance after every detail transaction,
for faster queries)

10.2 Types of trigger events

There are typically three triggering events that cause data triggers to 'fire':

a) INSERT event (as a new record is being inserted into the database).
b) UPDATE event (as a record is being changed).

Last Edited:

S. Rishma & S. Saravana Kumar Page 25 of 50


c) DELETE event (as a record is being deleted).

Trigger Syntax

CREATE TRIGGER
trigger_name
ON
{table | view }
{{
{ FOR | AFTER | INSTEAD OF } { [ INSERT ] [ , ] [ UPDATE ] [ , ] [ DELETE ] }

[ WITH APPEND ]
AS
[ { IF UPDATE ( column )
[ { AND | OR } UPDATE ( column ) ] [ ...n ]
| IF ( COLUMNS_UPDATED ( ) { bitwise_operator } updated_bitmask )
{ comparison_operator } column_bitmask [ ...n ]
}]
sql_statement [ ...n ]
}}

11.0 Cursors

Cursors are simply defined as “It’s an iterator over the collection of rows in the recordset”.

Using cursors, the client can get, put, and delete database records. Database programmers
use cursors for processing individual rows returned by the database system for a query.

Syntax:
DECLARE cursor_name CURSOR FOR SELECT ... FROM...
 It declares a cursor with a name for the table to be accessed.

OPEN cursor_name
 Open statement places the cursor before first row in the resultset.

FETCH cursor_name INTO...


 Position cursors on a specific row in the result set with the FETCH statement. A fetch
operation transfers the data of the row into the application.

CLOSE cursor_name
Last Edited:

S. Rishma & S. Saravana Kumar Page 26 of 50


 It closes the cursor after completion of the recursive process.

11.1 Types of cursors

Scrollable

 Scrollable cursors can move in either direction.


 It can position the cursor anywhere in the result set using the FETCH SQL
statement.
 The keyword SCROLL must be specified when declaring the cursor. The default
is NO SCROLL.
 The target position for a scrollable cursor can be specified relative to the current
cursor position or absolute from the beginning of the result set.

Syntax:

DECLARE
cursor_name sensitivity SCROLL CURSOR
FOR
SELECT...
FROM
FETCH [NEXT | PRIOR | FIRST | LAST] FROM cursor_name|
FETCH ABSOLUTE n FROM cursor_name|
FETCH RELATIVE n FROM cursor_name

Non-Scrollable (forward-only)

 Here, we can FETCH each row at most once and the cursor automatically moves
to the immediately following row.
 With-Hold cursors
 Cursors will be closed automatically once the transaction is over i.e. when a
commit or rollback occurs. This property of a cursor can be changed by declared
it using the WITH HOLD clause.
 Holdable cursor is open for commit and closed for rollback

DECLARE cursor_name CURSOR WITH HOLD FOR SELECT ... FROM...

11.2 Drawbacks of Cursors

Last Edited:

S. Rishma & S. Saravana Kumar Page 27 of 50


 Fetching a row from the cursor may result in a network round trip each time.
 Repeated network round trips can severely impact the speed of the operation using the
cursor.
 Cursors allocate resources on the server, for instance locks, temporary storage etc.
 If a cursor is not properly closed, the resources will not be freed until the SQL session
(connection) itself is closed. This wasting of resources on the server can not only lead
to performance degradations but also to failures.

12.0 CASE Statements


SQL CASE is a very unique conditional statement providing if/then/else logic for any ordinary
SQL command, such as SELECT or UPDATE.

It provides the ability to manipulate the presentation of the data without actually updating or
changing the base table.

It masks the actual values present in a table to end users without altering the data in base
table. And provides the necessary information needed by the particular end users.

Syntax:

Select
column_name, ‘new_column_name’=CASE
WHEN (Condition)
THEN
“msg to display / any computation”
ELSE
Some other output
END

Sample code:

Select
Product, ‘Status’=CASE
WHEN
Quantity>0
THEN
“In-stock”
ELSE
“Out-of-stock”
END
From
dbo.inventory

Explanation:

Last Edited:

S. Rishma & S. Saravana Kumar Page 28 of 50


 This query displays the product and status of the quantity of product whether its in-
stock or out-of-stock by checking a condition quantity>0, instead of displaying the
actual amount of quantity.
 It provides an online catalog to allow users to check the status of items without
disclosing the actual amount of inventory the store currently has in stock.

13.0 Temporary tables

 Temporary tables are used to store and process intermediate results by using the same
selection, update, and join capabilities of SQL Server tables. However, using temporary
tables can adversely affect system performance
 There are two types of temporary tables: global and local.
 Temp tables can be created locally (#TableName) or globally (##TableName)
 SQL server appends a unique number at the end ‘temporary table’ object to identify it ,
in order to avoid confusion when two users create the same temporary table name.
 It works pretty quickly. It is cached in memory.
 We should drop the temporary table explicitly.
 We should recompile the stored procedures again and again, if we use temporary
tables inside it. It avoids recompilations, always we need to create temporary table and
create indexed for that.
 Temp tables allow for multiple indexes to be created
 Temp tables can be used throughout multiple batches.
 Temp tables can be used to hold the output of a stored procedure

Syntax:

CREATE TABLE
#table_name [column_name [n] datatype...]
INSERT INTO
#tablevariable_name
SELECT * FROM table_name [where (condition)]
(SQL query statements: update or delete, drop)

Sample Code:

CREATE TABLE
#Yaks
(
YakID int,
YakName char (30)
)

INSERT INTO
#TibetanYaks (YakID, YakName)
SELECT
Last Edited:

S. Rishma & S. Saravana Kumar Page 29 of 50


YakID, YakName
FROM
dbo.Yaks
WHERE YakType = 'Tibetan'

14.0 Table variables


 It is a datatype. Unlike other datatype, table variables cannot be used as input and
output parameters. Its scope is Stored Procedure; User defined functions, and batches.
 It provides great performance when compared to temp tables.
 It is used instead of temporary tables, when the resultset is less than 100 rows. Hence
if resultset is small, table variable is best choice.
 We can insert, delete, and update records into table variable.
 It has restricted scope, hence it brings performance optimization.
 In table variable, all constraints are used like unique, not null, check, default, primary
key and unique key. Hence it produces the appropriate resultset.
 No need of recompilation of stored procedure while using table variables.
 During transactions, it produces less locking and logging overhead.
 No need to drop the table variable explicitly. It will be closed, once the application is
closed.

Syntax:

DECLARE @tablevariable_name TABLE


{
[Column name (n) datatype]
}
INSERT INTO @tablevariable_name
SELECT * FROM table_name [where (condition)]
(SQL query statements: update or delete)

Sample code:
DECLARE @TibetanYaks TABLE
(YakID int,
YakName char (30)
)
INSERT INTO
@TibetanYaks (YakID, YakName)
SELECT
YakID, YakName
FROM
dbo.Yaks
WHERE
YakType = 'Tibetan'

Last Edited:

S. Rishma & S. Saravana Kumar Page 30 of 50


Temporary Table Table Variable

Temporary tables are stored in tempdb Table variables are stored in memory with a
database. table like outlook.

Access time is lesser when compared to Since it is partially stored in memory, the access
table variable. time for a table variable can be faster than the
time it takes to access a temporary table.
For stored procedures, temp table is the
best choice. For small resultsets, table variable is the best
choice.
It’s good to drop explicitly.
No need to drop explicitly.

Table 14-1. Difference between Temporary table & Table variable

14.1 Disadvantages of table variable over temporary table

 Since it cannot be passed as parameter from one stored procedure to another, there
temporary tables are used.
 We cannot create non- clustered index.
 SQL Server does not maintain statistics on table variable.
 Table variable cannot be altered.
 It won’t participate in transaction rollbacks.
 It can’t use dynamic SQL, unless it is declared dynamically.
 While table sharing, nested stored procedures table variables cannot be used.
 It cannot be used for large resultsets, while needs indexes for query optimization.

15.0 Stored Procedure

Last Edited:

S. Rishma & S. Saravana Kumar Page 31 of 50


 A stored procedure is one or more SQL statements that have been compiled and
stored with database. A stored procedure can be started by application code on the
client.
 Stored procedure can improve database performance because the SQL statements in
each procedure are only compiled and optimized the first time they are executed. In
contrast SQL statements that are sent from a client to the server have to be compiled
and optimized every time they are executed.
 In addition to SELECT statement, a stored procedure can contain other SQL
statements such as INSERT, UPDATE, and DELETE. It also contains control-of-flow
language.

Syntax:

CREATE PROCEDURE procedure_name [ ; number ]     


[ { @parameter data_type } ]
AS sql_statement [...n]

Sample Code:

CREATE PROCEDURE sp_GetInventory


@location varchar (10)
AS
SELECT
Product, Quantity
FROM
Inventory
WHERE
Warehouse = @location

Here, this stored procedure replaces the SELECT query,

SELECT
Product, Quantity
FROM
Inventory
WHERE
Warehouse = 'FL'

Where the query has to be compiled and executed every time and the warehouse
manager should have knowledge about the sql queries and appropriate permissions to
access the table information.

Where as in SP, the procedure is precompiled. Hence it can be executed easily by only
specifying the location name.

EXECUTE sp_GetInventory 'FL'


Last Edited:

S. Rishma & S. Saravana Kumar Page 32 of 50


EXECUTE sp_GetInventory 'NY'

15.1 Benefits of Stored Procedure:

 Precompiled execution.
 Reduced client/server traffic.
 Efficient reuse of code and programming abstraction.
 Enhanced security controls.

16.0 Functions

A function is mainly used in the case where it must return a value. A function can be created
and called in SQL Queries. There are some pre-defined functions available in MS SQL server,
they are

 AVG() - Returns the average value


 COUNT() - Returns the number of rows
 FIRST() - Returns the first value
 LAST() - Returns the last value
 MAX() - Returns the largest value
 MIN() - Returns the smallest value
 SUM() - Returns the sum
 UCASE() - Converts a field to upper case
 LCASE() - Converts a field to lower case
 MID() - Extract characters from a text field
 LEN() - Returns the length of a text field
 ROUND() - Rounds a numeric field to the number of decimals specified
 NOW() - Returns the current system date and time
 FORMAT() - Formats how a field is to be displayed

16.1 User Defined Functions

We can create our own functions using CREATE FUNCTION statements. The syntax
for creating a function is

Syntax
CREATE FUNCTION
Last Edited:

S. Rishma & S. Saravana Kumar Page 33 of 50


[owner_name.] function_name

( [ { @parameter_name [AS] scalar_parameter_data_type [ = default ] } [ ,...n ] ] )


RETURNS
scalar_return_data_type
[WITH < function_option> [[,] ...n] ]
[AS]
BEGIN
function_body
RETURN scalar_expression
END

16.2 Split function

Split function is a user defined function it accept a string containing a stream of words
separated by “,” and display it as individual rows in a table.

Code
CREATE FUNCTION splitFunction
(@List nvarchar(2000))
RETURNS
@RtnValue table ( Value nvarchar(100))
AS
BEGIN
While (Charindex(',',@List)>0)
Begin
Insert Into @RtnValue (value)
Select
Value = ltrim(rtrim(Substring(@List,1,Charindex(',',@List)-1)))
Set
@List = Substring(@List,Charindex(',',@List)+len(','),len(@List))
End
Insert Into @RtnValue (Value)
Select Value = ltrim(rtrim(@List))
Return
END

Executing the following query


SELECT *
FROM dbo.splitFunction('Sara,Gopi,Rishma,Madhan,Anbu')
The output is

Last Edited:

S. Rishma & S. Saravana Kumar Page 34 of 50


17.0 Locking in SQL server

There are two types of locks in SQL server

 Read Lock - The locked data is reserved for read by the current session. Other
sessions can read the locked data. But they can not write (update) the locked data. A
read lock is also called a shared lock.
 Write Lock - The locked data is reserved for write by the current session. Other
sessions can not read and write the locked data. A write lock is also called an exclusive
lock.

There are three levels of locks:

 Table Lock - The lock is set at the table level. All rows in the locked table are locked.
 Row Lock - The lock is set at the row level. Some rows of a table are locked. But other
rows are not locked.
 Column Lock - The lock is set at the column level. Some columns of a row are locked.
But other columns are not locked.

18.0 Index
Index is mainly used for speed up the storage or retrieval time for a data from or to a particular row of a
table in a database.

18.1 Types

Bitmap index
A bitmap index is a special kind of index that stores the bulk of its data as bit arrays (bitmaps)
and answers most queries by performing bitwise logical operations on these bitmaps. The most
commonly used index, such as B+trees, are most efficient if the values it indexes do not repeat or
repeat a smaller number of times. In contrast, the bitmap index is designed for cases where the values
Last Edited:

S. Rishma & S. Saravana Kumar Page 35 of 50


of a variable repeat very frequently. For example, the gender field in a customer database usually
contains two distinct values: male or female. For such variables, the bitmap index can have a significant
performance advantage over the commonly used trees.

Dense index
A dense index in databases is a file with pairs of keys and pointers for every record in the data
file. Every key in this file is associated with a particular pointer to a record in the sorted data file. In
clustered indexes with duplicate keys, the dense index points to the first record with that key.

Sparse index
A sparse index in databases is a file with pairs of keys and pointers for every block in the data
file. Every key in this file is associated with a particular pointer to the block in the sorted data file. In
clustered indexes with duplicate keys, the sparse index points to the lowest search key in each block.

Reverse index
A reverse key index reverses the key value before entering it in the index. E.g., the value 24538
becomes 83542 in the index. Reversing the key value is particularly useful for indexing data such as
sequence numbers, where new key values monotonically increase.

18.2 Index Architecture

A. Clustered index
Clustered indexes sort and store the data rows in the table or view based on their key values.
There can be only one clustered index per table because the rows themselves can be sorted in only
one order.
Advantages
It increases the speed while we are trying to retrieve the data.
Limitations
Insertion and deletion will become a slow process as it uses physical index.
B. Non clustered index
It provides the logical index contains the non clustered index key values and each key value entry has a
pointer to the data row that contains the key value.
We can have more than one non clustered index for a single table.

C. Unique Indexes
A unique index ensures that the indexed column contains no duplicate values. In the case of
multicolumn unique indexes, the index ensures that each combination of values in the indexed column

Last Edited:

S. Rishma & S. Saravana Kumar Page 36 of 50


is unique. For example, if a unique index full_name is created on a combination of last_name,
first_name, and middle_initial columns, no two people could have the same full name in the table.

Both clustered and nonclustered indexes can be unique. Therefore, provided that the data in the
column is unique, you can create both a unique clustered index and multiple-unique nonclustered
indexes on the same table.

18.3 Index implementations

Indexes can be implemented using a variety of data structures. Popular indexes include
balanced trees, B+ trees and hashes.
In Microsoft SQL Server, the leaf node of the clustered index corresponds to the actual data,
not simply a pointer to data that resides elsewhere, as is the case with a non-clustered index. Each
relation can have a single clustered index and many unclustered indexes.

18.4 Index Optimization Tips

 Consider creating index on column(s) frequently used in the WHERE, ORDER BY, and
GROUP BY clauses.
 Keep your indexes as narrow as possible.
 Drop indexes that are not used.
 Try to create indexes on columns that have integer values rather than
character values.
 Limit the number of indexes, if your application updates data very
frequently.
 Check that index you tried to create does not already exist.
 Create clustered index instead of nonclustered to increase performance of
the queries that return a range of values and for the queries that contain
the GROUP BY or ORDER BY clauses and return the sort results.
 Create nonclustered indexes to increase performance of the queries that
return few rows and where the index has good selectivity.
 Create clustered index on column(s) that is not updated very frequently.
 Create clustered index based on a single column that is as narrow as
possibly.
 Avoid creating a clustered index based on an incrementing key.
 Create a clustered index for each table.
 Don't create index on column(s) which values has low selectivity.
 If you create a composite (multi-column) index, try to order the columns in
the key as to enhance selectivity, with the most selective columns to the
leftmost of the key.

Last Edited:

S. Rishma & S. Saravana Kumar Page 37 of 50


 If you create a composite (multi-column) index, try to order the columns in
the key so that the WHERE clauses of the frequently used queries match the
column(s) that are leftmost in the index.
 If you need to join several tables very frequently, consider creating index on
the joined columns.
 Consider creating a surrogate integer primary key (identity, for example).
 Consider creating the indexes on all the columns, which referenced in most
frequently used queries in the WHERE clause which contains the OR
operator.
 If your application will perform the same query over and over on the same
table, consider creating a covering index including columns from this query.
 Use the DBCC DBREINDEX statement to rebuild all the indexes on all the
tables in your database periodically (for example, one time per week at
Sunday) to reduce fragmentation.
 Use the DBCC INDEXDEFRAG statement to defragment clustered and
secondary indexes of the specified table or view.Consider using the
SORT_IN_TEMPDB option when you create an index and when tempdb is on
a different set of disks than the user database.
 Use the SQL Server Profiler Create Trace Wizard with "Identify Scans of
Large Tables" trace to determine which tables in your database may need
indexes.

19.0 Query Optimization Tips

 Distinct aggregation (e.g. select count(distinct key) …) is a SQL language feature that
results in some very slow queries.
 Try to restrict the queries result set by using the WHERE clause. This can reduce
network traffic and boost the overall performance of the query.
 Try to restrict the queries result set by returning only the particular columns from the
table, not all table's columns.
 Use views and stored procedures instead of heavy-duty queries. This can be used to
facilitate permission management also, because you can restrict user access to
table columns they should not see.
 Try to avoid using SQL Server cursors, whenever possible. It can result in performance
degradation when compared to select statement.
 If you need to return the total table's row count, you can use alternative way instead of
 SELECT COUNT (*) statement.
 You can use sysindexes system table, in this case. There is ROWS column in the
sysindexes table. This column contains the total row count for each table in your
database. So, you can use the following select statement
 SELECT rows FROM sysindexes WHERE id = OBJECT_ID('table_name') AND indid
< 2 So, you can improve the speed of such queries in several times.

Last Edited:

S. Rishma & S. Saravana Kumar Page 38 of 50


 Use table variables instead of temporary tables, if your resultset has less than 100
rows.
 Try to avoid the HAVING clause, whenever possible.
 Try to avoid using the DISTINCT clause, whenever possible.
 Include SET NOCOUNT ON statement into your stored procedures to stop the
message indicating the number of rows affected by a T-SQL statement.
 Use the select statements with TOP keyword or the SET ROWCOUNT statement, if
you need to return only the first n rows.
 Use the FAST number_rows table hint if you need to quickly return 'number_rows'
rows.
 Try to use UNION ALL statement instead of UNION, whenever possible.
 Do not use optimizer hints in your queries.

20.0 Execution Plan

 An execution plan is the result of the query optimizer's attempt to calculate the most
efficient way to implement the request represented by the T-SQL query you submitted.
 When a query is submitted, number of processes on the server goes to work on that
query. The purpose of the processes is to manage the system to store and retrieve
data in a timely manner and maintaining the integrity of data.
 The processes around T-SQL are broken down into two stages.

1. Processes that occur in the relational engine

2. Processes that occur in the storage engine.

 In the relational engine the query is parsed and then processed by the Query
Optimizer, which generates an execution plan.
 The plan is sent (in a binary format) to the storage engine, which it then uses to
retrieve or update the underlying data. The storage engine is where processes such
as locking, index maintenance and transactions occur

 SQL Server Query Optimizer uses the cost to make the decision on selecting the most
efficient execution plan. When any query is executed, the SQL Server Query Optimizer
prepares several alternative execution plans to execute the query and selects the
lowest cost plan.

 Two kinds of plan will be available: Trivial Plan and Non-trivial plan

Execution Plan Formats:

 Graphical Plan
 Textual Plan

Last Edited:

S. Rishma & S. Saravana Kumar Page 39 of 50


 XML Plan

Execution plans are there to assist in writing efficient T-SQL code, troubleshooting existing T-
SQL behavior or monitoring and reporting on your systems.

20.1 Graphical Plan

20.1.1 Table Scan

 When you query a table that doesn't have indexes, or if the optimizer decides not to
use an existing index or indexes, the system performs a table scan.
 Table Scan is a logical and physical operator.

 The Table Scan operator retrieves all rows from the table specified in the
Argument column of the query execution plan. If a WHERE :() predicates
appears in the Argument column, only those rows that satisfy the predicate are
returned.

20.1.2 Index scan

When SQL Server does a scan it loads the object which it wants to read from disk into memory,
then reads through that object from top to bottom looking for the records that it needs.

The SQL Server optimizer's uses indexes to improve query execution time. Index access is an
access method in which SQL Server uses an existing index to read and write data pages. Because
index access significantly reduces the number of I/O read operations, it often outperforms a table scan.

20.1.3 Clustered Index Scan

 A clustered index physically sorts the table's contents in the order of the specified index
columns.
 There can be only one clustered index for a table.
 SQL Server navigates from the b-tree root node to the leaf nodes to retrieve data.
 A clustered index property has leaf nodes that contain data pages.

 The Clustered Index Scan logical and physical operator scans the clustered index
specified in the Argument column. When an optional WHERE :() predicates is present,
only those rows that satisfy the predicate are returned.

 If the Argument column contains the ORDERED clause, the query processor has
requested that the rows' output be returned in the order in which the clustered index
has sorted them. If the ORDERED clause is not present, the storage engine will scan
the index in the optimal way (not guaranteeing the output to be sorted).

Last Edited:

S. Rishma & S. Saravana Kumar Page 40 of 50


20.1.4 Non-clustered Index Scan

 A nonclustered index has the same index structure as a clustered index, but with two
important differences. Nonclustered indexes don't change the row's physical order in
the table, and the nonclustered index's leaf level consists of an index key plus a
bookmark.

 A bookmark shows where to find the row that corresponds to the nonclustered index
key.
 We can create 249 non-clustered indexes on a table.

20.1.5 Index Seek

When SQL Server does a seek it knows where in the index that the data is going to be,
so it loads up the index from disk, goes directly to the part of the index that it needs and reads
to where the data that it needs ends.  This is obviously a must more efficient operation than a
scan, as SQL already knows where the data is that it is looking for.

20.1.6 Clustered Index Seek

 The Clustered Index Seek logical and physical operator uses the seeking ability of
indexes to retrieve rows from a clustered index.
 The Argument column contains the name of the clustered index being used and the
SEEK :() predicate. The storage engine uses the index to process only those rows that
satisfy this SEEK :() predicates. It optionally can include a WHERE :() predicate, which
the storage engine evaluates against all rows satisfying the SEEK :() predicate (it does
not use indexes to do this).

 If the Argument column contains the ORDERED clause, the query processor has
determined that the rows must be returned in the order in which the clustered index has
sorted them. If the ORDERED clause is not present, the storage engine searches the
index in the optimal way (not guaranteeing the output to be sorted). Allowing the output
to retain its ordering can be less efficient than producing nonsorted output.

20.2 Plan Interpretation

 Read a graphical execution plan from right to left and top to bottom.
 This arrow represents the data being passed between the operators.

 The thickness of the arrow reflects the amount of data being passed.

 The percentage below each icon represents the cost to the operator. That cost returned
from the optimizer, is the estimated execution time for that operation.
Last Edited:

S. Rishma & S. Saravana Kumar Page 41 of 50


20.2.1 ToolTips

 Here we get the numbers generated by the optimizer on the following:


 Cached plan size – how much memory the plan generated by this query will take up
in stored procedure cache. This is a useful number when investigating cache
performance issues because you'll be able to see which plans are taking up more
memory.

 Estimated Operator Cost – cost of the operator.

 Estimated Subtree Cost – tells us the accumulated optimizer cost assigned to this
step and all previous steps, but remember to read from right to left. This number is
meaningless in the real world, but is a mathematical evaluation used by the query
optimizer to determine the cost of the operator in question; it represents the amount of
time that the optimizer thinks this operator will take.

 Estimated number of rows – calculated based on the statistics available to the


optimizer for the table or index in question.

 The I/O Cost and CPU cost are not actual operators, but rather the cost numbers
assigned by the Query Optimizer during its calculations. These numbers are useful
when determining whether most of the cost is I/O-based or if we're putting a load on the
CPU.

21.0 SQL Server security model

To be able to access data from a database, a user must pass through two stages of
authentication, one at the SQL Server level and the other at the database level. These two stages are
implemented using Logins names and User accounts respectively. A valid login is required to connect
to SQL Server and a valid user account is required to access a database.

During a new connection request, SQL Server verifies the login name supplied, to make sure,
that login is authorized to access SQL Server. This verification is called Authentication. SQL Server
supports two authentication modes:

 Windows authentication mode: With Windows authentication, you do not have to


specify a login name and password, to connect to SQL Server. Instead, your access to
SQL Server is controlled by your Windows NT/2000 account (or the group to which
your account belongs to), that you used to login to the Windows operating system on
the client computer/workstation. A DBA must first specify to SQL Server, all the
Microsoft Windows NT/2000 accounts or groups that can connect to SQL Server

 Mixed mode: Mixed mode allows users to connect using Windows authentication or
SQL Server authentication. Your DBA must first create valid SQL Server login accounts
Last Edited:

S. Rishma & S. Saravana Kumar Page 42 of 50


and passwords. These are not related to your Microsoft Windows NT/2000 accounts.
With this authentication mode, you must supply the SQL Server login and password
when you connect to SQL Server. If you do not specify SQL Server login name and
password, or request Windows Authentication, you will be authenticated using
Windows Authentication.

21.1 Create Login

A valid login name is required to connect to an SQL Server instance. A login could be:

 A Windows NT/2000 login that has been granted access to SQL Server

 An SQL Server login, that is maintained within SQL Server

Syntax

CREATE LOGIN login {WITH PASSWORD = 'password'


[HASHED] [MUST_CHANGE]
[, option_list […]]}

CREATE LOGIN login {FROM sources}

Sources:
WINDOWS [WITH windows_options [...]]
CERTIFICATE certname
ASYMMETRIC KEY asym_key

option_list:
SID = sid
DEFAULT_DATABASE = database
DEFAULT_LANGUAGE = language
CHECK_EXPIRATION = {ON | OFF}
CHECK_POLICY = {ON | OFF}
CREDENTIAL = credential

windows_options:
DEFAULT_DATABASE = database
DEFAULT_LANGUAGE = language

Key:
Login
Login SQL Server / certificate-mapped / asymmetric key-mapped / [Windows].
WINDOWS
Map to a Windows login.
Certname

Last Edited:

S. Rishma & S. Saravana Kumar Page 43 of 50


Certificate to associate with this login.
asym_key
Name of an asymmetric key to associate with this login.
Password
A SQL Server login password for the login.
HASHED
The SQL Server login is already hashed. (so don't hash again)
MUST_CHANGE
Prompt the user for a new SQL Server password
Credential
Credential to be mapped to the new SQL Server login.
Sid
GUID of the new SQL Server login. (Default=automatic)
DEFAULT_DATABASE
The default database to be assigned to the login.(default = master)
DEFAULT_LANGUAGE
The default language to be assigned to the login.
CHECK_EXPIRATION
Enforce password expiration policy
CHECK_POLICY
Enforce Windows password policy

 Passwords are case-sensitive.


 Prehashing of passwords is supported only when you are creating SQL Server logins.

 If MUST_CHANGE is specified, CHECK_EXPIRATION and CHECK_POLICY must be


set to ON.

Examples

CREATE LOGIN [SERVER01\User01] FROM WINDOWS;


GO

CREATE LOGIN user42 WITH PASSWORD = 'pa$$word' MUST_CHANGE;


GO

21.2 Create Users

A valid user account within a database is required to access that database. User
accounts are specific to a database. All permissions and ownership of objects in the database
are controlled by the user account. SQL Server logins are associated with these user accounts.
A login can have associated users in different databases, but only one user per database.

Syntax:

Last Edited:

S. Rishma & S. Saravana Kumar Page 44 of 50


CREATE USER username
IDENTIFIED {BY password | EXTERNALLY | GLOBALLY AS 'external_name'}
options;

Options:

DEFAULT TABLESPACE tablespace


TEMPORARY TABLESPACE tablespace
QUOTA int {K | M} ON tablespace
QUOTA UNLIMITED ON tablespace
PROFILE profile_name
PASSWORD EXPIRE
ACCOUNT {LOCK|UNLOCK}

Examples

 Create a user with no rights to save data or create objects:

CREATE USER limited IDENTIFIED BY ChangeThis;

 Create a user with full rights to create objects and save data:

DROP USER MySchemaOwner CASCADE;

CREATE USER MySchemaOwner IDENTIFIED BY ChangeThis


DEFAULT TABLESPACE
data
TEMPORARY TABLESPACE
temp
QUOTA UNLIMITED ON
data;

CREATE ROLE conn;

GRANT CREATE session, CREATE table, and CREATE view,


CREATE procedure, CREATE synonym,
ALTER table, ALTER view, ALTER procedure, ALTER synonym,
DROP table, DROP view, DROP procedure, DROP synonym,
TO conn;

GRANT conn TO MySchemaOwner;

You have to create a user first before you can GRANT permissions, roles or assign a default
ROLE.

21.3 Roles

Last Edited:

S. Rishma & S. Saravana Kumar Page 45 of 50


A role is nothing but a group to which individual logins/users can be added, so that the
permissions can be applied to the group, instead of applying the permissions to all the
individual logins/users. There are three types of roles in SQL Server 7.0

 Fixed server roles

These are server-wide roles. Logins can be added to these roles to gain the associated
administrative permissions of the role. Fixed server roles cannot be altered and new
server roles cannot be created.

 Fixed database roles

Each database has a set of fixed database roles, to which database users can be
added. These fixed database roles are unique within the database. While the
permissions of fixed database roles cannot be altered, new database roles can be
created.

 Application roles

After creating and assigning the required permissions to an application role, the client
application needs to activate this role at run-time to get the permissions associated with
that application role. Application roles simplify the job of DBAs, as they don't have to
worry about managing permissions at individual user level. All they need to do is to
create an application role and assign permissions to it.

22.0 SQL Syntax

Data Definition Language (DDL) statements are used to define the database structure or schema.
Statement Syntax Purpose
CREATE CREATE [TEMPORARY] To create table in the
TABLE [table name] ( [column definitions] ) [table database
parameters].
ALTER ALTER TABLE [table name] ADD [column Alters the structure of the
definitions] database

ALTER TABLE [table name] DROP COLUMN


[column Name];

DROP DROP TABLE [table name] Delete table from the


Last Edited:

S. Rishma & S. Saravana Kumar Page 46 of 50


database
TRUNCATE TRUNCATE TABLE [table name] Remove all records from a
table, including all spaces
allocated for the records
are removed

Table 22-1. DDL Statements


Data Manipulation Language (DML) statements are used for managing data within schema
objects.
Statement Syntax Purpose
SELECT SELECT [column names] Retrieve data from the a
FROM [table name] database

INSERT INSERT INTO [table name] ([column names]) Insert data into a table
VALUES([column values]);
UPDATE UPDATE [table name] Updates existing data
SET ([column values]) within a table.
WHERE [conditions] It is mainly used for
incrementing or
decrementing the column
values.
DELETE DELETE from [table name] Deletes all records from a
WHERE [conditions] table, the space for the
records remain

Table 22-2. DML Statements

Data Control Language (DCL) statements deal with the user privileges.
Statement Syntax Purpose
GRANT GRANT SELECT, UPDATE Gives user's access
ON [table name] privileges to database
TO [user names]
REVOKE REVOKE SELECT, UPDATE Withdraw access privileges

Last Edited:

S. Rishma & S. Saravana Kumar Page 47 of 50


ON [table name] given with the GRANT
FROM [user names] command

DENY DENY SELECT, INSERT, UPDATE, DELETE ON Denies a specific


[dbo].[CRONUS$Item] TO [public]
permission to the specified
user or role in the current
database

Table 22-3. DCL Statements


Transaction Control (TCL) statements are used to manage the changes made by DML statements.
It allows statements to be grouped together into logical transactions.

Figure 22-1. Simple Transaction system

The above figure represents how the change occurred in a transaction is committed or discarded from
the target table.

Statement Syntax Purpose


COMMIT COMMIT[work] Save work done in
particular transaction.

Last Edited:

S. Rishma & S. Saravana Kumar Page 48 of 50


SAVEPOINT SAVEPOINT [Save point name] Identify a point in a
transaction to which you
can later roll back

ROLLBACK ROLLBACK[work] Restore database to


original since the last
COMMIT

Table 22-4. TCL Statements

23.0 Conclusion
Thus the document provides detailed view about SQL Server 2005 and it will be useful for the
future trainees of Photon Infotech. And the sample coding are zipped and attached here. And reference
links are specified.

23.1 Attachments

SQL PRACTICE Query-Rishma.rar SQL PRACTICE Query-Saravanakumar.rar

23.2 Reference Links

http://www.tizag.com/sqlTutorial/sqlsyntax.php

http://social.msdn.microsoft.com/Search/en-IN?query=sql&ac=8

http://weblogs.sqlteam.com/mladenp/articles/9502.aspx

Last Edited:

S. Rishma & S. Saravana Kumar Page 49 of 50


http://www.sqlservercentral.com/Forums/Topic497615-359-1.aspx

http://vyaskn.tripod.com/sql_server_security_best_practices.htm

http://www.mssqlcity.com/Tips/tipTSQL.htm

http://www.codeproject.com/KB/database/sqldodont.aspx

http://www.erpgenie.com/sap-technical/abap/sql-performance-qdos-and-dontsq

Last Edited:

S. Rishma & S. Saravana Kumar Page 50 of 50

You might also like