SQL
SQL
Data Base Management System is defined as collection of Software Programs used to store the
data, manage the data, and retrieve the data. Data retrieval is based on three points
Accuracy Data Free from Errors.
Timelines With in a time
Relevancy Related Data
Maintaining of the data can be done in two ways.
File System
Data Base
Why Database Management System and why not flat files to maintain the data.
Flat Files has many disadvantages they are
No Security
Difficulty in accessing the data
Redundancy
Data Inconsistency
Sequential Search Technique (Time Consuming Process)
Indexing is not present in file system
No Identifier (Related Information)
DATABASE: It is defined as Logical Container which contains related objects, Objects Includes Tables,
Views, Synonyms, Stored Procedures, Functions, Triggers Etc.
MODELS OF DATABASE MANAGEMENT SYSTEM
Entity Relationship Model
Object Relation Ship Model
Record Based Model
Hierarchical DBMS
Network DBMS
Relational DBMS
Object Relational DBMS
Info Logical Model
Semantic Based Model
**SQL Server 2005(9.0) & 2008 (10.0) Includes both RDBMS & ORDBMS Model.
RDBMS = R + DBMS {R Stands for Referential Integrity Constraint}
Relation can be defined as Referential Integrity Constraint, with which we create relationships One
to One & One to Many (Direct Implementation) Many to Many (Indirect Implementation)
DR EF CODD has outlined 12 rules often called as CODDS rules if any Database Software Satisfies 8
or 8.5 rules, it can be considered as pure RDBMS Database.
Sybase (Teradata)
MS Access is not a pure DBMS, because it satisfies only 6 rules, so it is called as Partial / Semi
Database.
RDBMS always presents the data in 2 Dimensional formats, i.e. in Rows and Columns, further
to tables.
Collection of characters or we call as IDENTIFIERS /FIELD/ ATTRIBUTE.
Collection of columns: ROW or RECORD or TUPLE.
Collection of Rows & Columns: Table or Entity or Objects or Relations.
RDBMS always represent the data in a Normalized way.
COMPONENETS OF RDBMS:
SQL SERVER:
SQL SERVER
SQL
(Different Sub
Languages)
T-SQL
(SQL + Procedural
Language)
Anonymous Block
Or
Name Less Block
Business
Intelligence Tools
ORACLE
It was Introduced In 1979
It Is CUI Based RDBMS
It can be Installed on any
SQL SERVER
In 1989 It was Introduced
It Is GUI Based RDBMS
It Requires Specific OS
Platform
Provides High Security
It Is High Priced RDBMS
(Windows)
It Is Less Security
It Is Low Priced RDBMS
CONFIGURATION TOOLS
Service Management
Client Network Utility
Server
BIDS (BUSSINESS INTELLIGENCE DEVELOPMENT STUDIO)
SSIS (SQL SERVER INEGRATION SERVICES)
SSAS (SQL SERVER ANALYTICAL SERVICES)
SSRS (SQL SERVER REPORTING SERVICES)
SSNS (SQL SERVER NOTIFICATION SERVICES)
T-SQL ENHANCEMENTS: SQL SERVER 2008 introduces several important new T-SQL Programmability
features and enhancements to some existing ones.
Following are the key Features:
Declaring and Initializing Variables
Compound Assignment Operators
Table Value Constructors(Support Through Values Clause)
Enhancements to Convert Functions
New Date and Time Data types & Functions
Large UDTS(User Defined Types)
Hierarchyid Data Type
Table Type and Table Valued Parameters
The Merge Statement (Grouping Sets Enhancements)
DDL Trigger Enhancements
Sparse Columns
Filtered Indexes
Large CLR User Defined Aggregates
Multi Input CLR User Defined Aggregates
The Order Option For CLR Table Valued Functions
Object Dependencies
Change Data Capture
EDITIONS OF SQL SERVER:
ENTERPRISE EDITION to perform administration related tasks
STANDARD EDITION - to perform administration related tasks
DEVELOPERS EDITION
WORKGROUP EDITION
EXPRESS EDITION
MOBILE EDITION
As Database creation is an administration related task, it should be carried out through MASTER
system data base,
Syntax:
Data File
Specifications
Log File
Specifications
Example:
CREATE DATABASE TESTDB
ON (
NAME = TESTDB ,
FILENAME = 'C:\SQL Server\MSSQL.1\MSSQL\DATA\TESTDB.MDF' ,
SIZE = 5MB , MAXSIZE = 10MB , FILEGROWTH = 2MB )
LOG ON (
NAME = TESTDBLOG ,
FILENAME = 'C:\SQL Server\MSSQL.1\MSSQL\DATA\TESTDBLOG.LDF' ,
SIZE = 3MB, MAXSIZE = 8MB, FILEGROWTH = 2MB)
Removing Files:
ALTER DATABASE TESTDB
REMOVE FILE TESTDB1 - Logical Name
Syntax:
SP_RENAMEDB < OLD_DATABASE_NAME >,< NEW_DATABASE_NAME >
SP_RENAMEDB 'TESTDB','DBTEST'
Dropping a Database:
Syntax:
DROP DATABASE < DATABASE_NAME >
DROP DATABASE TESTDB
Database.
SP_HELPDB: This predefined Stored Procedure will provide list of databases available in SQL
SERVER.
SP_HELPDB <DATABASE_NAME> - It will provide the complete information of the database.
SQL is a called Common Database Language, since it gets understand by every RDBMS
SQL is a Command Based Language
SQL is a Insensitive Language
SQL is a Non Procedural Language
INSERT
INSERT
INSERT
INSERT
INSERT
INSERT
INSERT
INSERT
INSERT
INSERT
INSERT
INSERT
INSERT
INSERT
INTO
INTO
INTO
INTO
INTO
INTO
INTO
INTO
INTO
INTO
INTO
INTO
INTO
INTO
EMP
EMP
EMP
EMP
EMP
EMP
EMP
EMP
EMP
EMP
EMP
EMP
EMP
EMP
INTO
INTO
INTO
INTO
DEPT
DEPT
DEPT
DEPT
VALUES
VALUES
VALUES
VALUES
(10,'ACCOUNTING','NEW YORK')
(20,'RESEARCH','DALLAS')
(30,'SALES','CHICAGO')
(40,'OPERATIONS','BOSTON')
INTO
INTO
INTO
INTO
INTO
SALGRADE
SALGRADE
SALGRADE
SALGRADE
SALGRADE
VALUES
VALUES
VALUES
VALUES
VALUES
(1,
(2,
(3,
(4,
(5,
700,
1201,
1401,
2001,
3001,
1200)
1400)
2000)
3000)
9999)
Q) Display ENAME, JOB, SALARY, COMM and DEPTNO of all the EMPLOYEES.
SELECT ENAME,JOB, SAL, COMM, DEPTNO FROM EMP
COLUMN ALIAS:
It is the other name provided for a COLUMN.
It is a temporary name provided for a COLUMN.
It provides its effect only in the output of a query.
It provides its usage till the query is in execution.
It cannot be used in other clauses of SELECT statement except ORDER BY clause.
When COLUMN ALIAS is specified directly it does not allow blank spaces and special
characters except underscores.
In order to have blank spaces and special characters it should be enclosed in Double Quotes
or Square Brackets [ ]
It can be specified in two ways:
With using AS Key word
With out using AS Key word
Examples:
SELECT
SELECT
SELECT
SELECT
SELECT
EMPNO
EMPNO
EMPNO
EMPNO
EMPNO
SELECT
SELECT
SELECT
SELECT
SELECT
SELECT
SELECT
10 + 20 {FOR ADDITION}
10 * 20 {FOR MULTIPLICATION}
5/2 -- WILL TREAT AS INTEGER
5/2.0
10 + 5 * 6 M1, (10+5)* 6 M2
**The above query calculates TOTAL SALARY of those EMPLOYEES who are earning COMMISSIONS
and all other EMPLOYEES TOTAL SALARY has been displayed as NULL values, since VALUE + NULL
=NULL. It is applicable for all ARITHMETIC OPERATORS.
WHERE CLAUSE:
OPERATORS:
RELATIONAL OPERATORS: >, <, >=, <=, {! = or <>} not equal to
LOGICAL OPERATORS: AND, OR, NOT
SPECIAL OPERATORS: IN, BETWEEN, IS, LIKE, DISTINCT, SAME/ANY, ALL, EXISTS
NOT + SPECIAL OPERATORS: NOTIN, NOT BETWEEN, ISNOT, NOT LIKE, NOT EXISTS
Q) Display all those EMPLOYEES who are working as CLERKS.
SELECT ENAME, JOB FROM EMP WHERE JOB = 'CLERK'
Q) Display ENAME, JOB of those EMPLOYES who are not working as MANAGER
SELECT ENAME, JOB FROM EMP WHERE JOB != 'MANAGER'
Q) Display ENAME, JOB, and DEPTNO of those EMPLOYEES who are working as CLERK at DEPT NO 20.
SELECT * FROM EMP WHERE JOB = 'CLERK' AND DEPTNO = 20
Q) Display ENAME, JOB of those EMPLOYEES who are working as CLERK, ANALYST.
SELECT ENAME, JOB FROM EMP WHERE JOB = 'CLERK' OR JOB = 'ANALYST'
SELECT ENAME, JOB FROM EMP WHERE JOB IN ('CLERK','ANALYST')
Q) Display EMPNO, ENAME, DEPTNO of those EMPLOYEES who are working at 10, 30 Departments.
SELECT EMPNO, ENAME, DEPTNO FROM EMP WHERE DEPT IN (10,30)
IN:
The list should contain only one column values; multiple columns data is invalid.
Q) Display ENAME, SAL of EMPLOYEE SAL Greater than or equal to 2000 & SAL less than or equal to
3000.
SELECT ENAME, SAL FROM EMP WHERE SAL >= 2000 AND SAL <=3000
SELECT ENAME, SAL FROM EMP WHERE SAL BETWEEN 2000 AND 3000
BETWEEN:
Q) Display ENAME, JOB, DEPTNO of those Employees who are not working as CLERK, ANALYST.
SELECT ENAME, JOB, DEPTNO FROM EMP WHERE JOB NOT IN ('CLERK','ANALYST')
Q) Display all those Employees whose salary is not in a range of 1000 and 3000.
SELECT * FROM EMP WHERE SAL NOT BETWEEN 1000 AND 3000
Q) Display all the Employees who are working as CLERK, ANALYST and SAL is greater than 1000.
SELECT * FROM EMP WHERE JOB = 'CLERK' OR 'ANALYST' AND SAL > 1000
SELECT * FROM EMP WHERE JOB IN ('CLERK','ANALYST') AND SAL > 1000
Q) Display ENAME, SAL, ANNUAL SAL of those Employees whose annual salary is in range of 18000
and 36000.
SELECT ENAME, SAL, SAL*12 AS ANNUALSAL FROM EMP
WHERE SAL*12 BETWEEN 18000 AND 36000
Q) Display ENAME, JOB, SAL, COMM and DEPTNO who are working as SALESMAN at DEPTNO 30 and
there commission is > half of their salary.
SELECT * FROM EMP WHERE JOB = 'SALESMAN' AND DEPTNO = 30 AND COMM > SAL/2
ANSI NULLS:
Working with IS Operator.
This operator is exclusively used for comparing NULL values.
It can be used any number of times.
SQL server also supports to compare the NULL values using relation operator.
Following SET Command should be used
SET ANSI_NULLS OFF | ON [Default it is ON]
It should be turned to off when NULL value is compared with relational operator.
Q) Display all those Employees who are not earning commission.
SELECT * FROM EMP WHERE COMM IS NULL
Q) Display EMPNO, ENAME & MGR of those Employees who dont have manager to report.
SELECT * FROM EMP WHERE MGR IS NULL
Q) Display EMPNO, ENAME & MGR of those Employees who have managers to report.
SELECT * FROM EMP WHERE MGR IS NOT NULL
Q) Display EMPNO, ENAME, MGR, SAL and COMM of those Employees who have managers to report
and do not earn commission.
SELECT * FROM EMP WHERE MGR IS NOT NULL AND COMM IS NULL
SET ANSL_NULLS OFF
SELECT * FROM EMP WHERE
SELECT * FROM EMP WHERE
SELECT * FROM EMP WHERE
SELECT * FROM EMP WHERE
COMM != NULL
COMM = NULL
MGR = NULL
NULL = NULL
WILD CHARACTERS:
These characters are used to provide pattern matching when data is searched into a column
SQL SERVER supports to work with following characters.
LIKE OPERATOR:
It is used for comparing the data which is enclosed with wild characters. It can be used for
any number of times.
This operator when compares the data using wild characters it should be enclosed in single
quotes.
Comparison to any type data should be placed in single quotes
If data in a column is enclosed with wild characters to search the data escape option should
be specified
SELECT
SELECT
SELECT
SELECT
SELECT
SELECT
SELECT
*
*
*
*
*
*
*
FROM
FROM
FROM
FROM
FROM
FROM
FROM
EMP
EMP
EMP
EMP
EMP
EMP
EMP
WHERE
WHERE
WHERE
WHERE
WHERE
WHERE
WHERE
ENAME
ENAME
ENAME
ENAME
ENAME
ENAME
ENAME
LIKE
LIKE
LIKE
LIKE
LIKE
LIKE
LIKE
'J%'
'%S'
'J%S'
'%A%'
'%A%E%'
'J[_]%'
'J\_%' ESCAPE '\'
SELECT
SELECT
SELECT
SELECT
SELECT
*
*
*
*
*
FROM
FROM
FROM
FROM
FROM
EMP
EMP
EMP
EMP
EMP
WHERE
WHERE
WHERE
WHERE
WHERE
ENAME
ENAME
ENAME
ENAME
ENAME
LIKE '[A-F]%'
NOT LIKE '[A-F]%'
LIKE '[^A-F]%'
LIKE '___'
LIKE '%?_%' ESCAPE '?'
DISTINCT OPERATOR:
Eliminates duplicates.
Always arranges the data in ASCENDING ORDER.
It should be used immediately after SELECT command.
It includes NULL VALUES.
When multiple columns are used with DISTINCT operator it eliminates only if all the columns
contains duplicates.
SELECT
SELECT
SELECT
SELECT
SELECT
DISTINCT
DISTINCT
DISTINCT
DISTINCT
DISTINCT
ORDER BY:
This clause is used to arrange the data in ASCENDING / DESCENDING order.
By default it arranges the data in ASCENDING order.
Order by clause will work after the execution of SELECT statement.
Order by clause will arrange the data in order at buffer location, hence it is temporary.
It can arrange the data in order based on COLUMN_NAME or COLUMN_ALIAS_NAME or
COLUMN_POSITION {according to query} to specify order type.
ASC ----- ASCENDING & DESC ---- DESCENDING
When multiple columns are used at ORDER BY clause. First column will be fully arranged in
order and other columns will be arranged based on previous column.
When multiple columns are used at ORDER BY clause, they can be specified with same order
type or different order type.
SELECT
SELECT
SELECT
SELECT
SELECT
* FROM
EMPNO,
EMPNO,
EMPNO,
EMPNO,
PAY
PAY
PAY
PAY
FROM
FROM
FROM
FROM
EMP
EMP
EMP
EMP
ORDER
ORDER
ORDER
ORDER
BY
BY
BY
BY
PAY
3
3,4 DESC
3 ASC, 4 DESC
FUNCTIONS:
It is a predefined program which returns one value, returned value can be of numeric, string data,
data type functions can be used for calculations
Built In Functions
Or
Predefined Functions
Single Row Functions
Or
Individual Functions
Scalar
Functions
Table Valued
Functions
SINGLE ROW FUNCTION: This function will process one row at a time and returns one value.
Mathematical Functions
String Functions
Date & Time Functions
Data Conversion {Type Casting Functions}
Ranking Functions {Windows Functions}
Meta Data Functions
Other Functions
MULTIPLE ROW FUNCTION: This function will process multiple rows at a time and returns one value.
Aggregate Functions
SQL SERVER supports to work with 12 categories of Functions and they are found at following paths
Click on Object Explorer Data Bases
Select the Data Base - TESTDB
Check under Programmability Functions.
Check under System Functions.
MATHEMATICAL FUNCTIONS:
This function will take input as numbers and will return output as numbers
ABS (NUMBER) - returns unsigned value of a given number (Number - Argument or Parameter.
SELECT ABS(-890), ABS(17)
SQRT (NUMBER) - Returns square root of a given positive number.
SQUARE (NUMBER) - Returns square of a given value
POWER ( NUMBER(Base), NUMBER(Exponent)) - It will find the power of a given number.
SELECT POWER (2,5)
SIGN ( NUMBER )
1234.5600
1234.5700
1234.5600
1234.6000
1235.0000
1234.0000
1200.0000
5700.0000
1234.5600
1234.5000
1234.0000
This function is used to round a given number with respect to Integer value or Decimal value based
on user required number of digits. If 3rd argument is specified other than zero it works as TRUNCATE.
CEILING(NUMBER) This function will increment a given number to its nearest integer. Based on
STRING FUNCTIONS: This are used to perform different operations on STRING DATA TYPE.
LEN(TEXT) - Returns number of characters.
SELECT ENAME, LEN(ENAME) FROM EMP WHERE LEN(ENAME)
LOWER(STRING) Converts characters to Lower case.
UPPER(STRING) Converts characters to Upper case.
ASCII(STRING) returns ASCII code of the given character
ASCII('A')----65
ASCII('P')----80
UNICODE( STRING ) Returns UNICODE of a given string.
CHAR ( NUMBER ) Returns character of a given ASCII code
CHAR (65) - A { Only 0-255 characters are available}
NCHAR(NUMBER)
NCHAR(256) {1-65535 Characters are available}
> 5
String1 ---- given string, String2 ---- search string, String3 ---- replace string
REPLACE ('COMPUTER','UT','IR')
It will search for String2 in String1 and replaces with String3 at all occurrences of String 2 in String1
STUFF(STRING1, NUMBER1, NUMBER2, STRING2)
String1 --- Given String, Number 1--- Start Position, Number2 --- Number of Characters
String2 --- Replace
STUFF('COMPUTER',5,2,'IL') -- COMPILER
CHARINDEX(STRING1, STRING2, [NUMBER])
String1 --- Search String, String2 --- Given String, Number --- Position
It will search for string1 in string2 and returns position of string1, if it exists else returns zero, by
default it will search from first character. It also supports to search for character/string after a
specific position
SELECT CHARINDEX('R','COMPUTER',7)
SELECT REPLICATE ('*', GRADE) FROM SALGRADE
Q) Display all the employees from the EMP table with half of the string in upper case and next string
in lower case
SELECT LEFT (ENAME, CEILING (LEN (ENAME)/2.0)) +
LOWER(RIGHT (ENAME, CEILING (LEN (ENAME)/2))) FROM EMP
ARITHMETIC OPERATIONS on data & time data type +, - are the operations which can be used
for performing operations on date type data.
DATE + NUMBER = DATE
DATE NUMBER = DATE
DATE DATE = NUMBER [Number of days]
SELECT HIREDATE, HIREDATE+15, HIREDATE-28 FROM EMP
given date.
DATEPART can be specified with this format - DD: MM: YY: HH: MI: SS: DW
SELECT
SELECT
SELECT
SELECT
SELECT
SELECT
DATEADD(DAY,10,GETDATE())
DATEADD(DD,10,GETDATE())
DATEADD(MONTH,10,GETDATE())
DATEADD(MM,10,GETDATE())
DATEADD(YEARS,10,GETDATE())
DATEADD(YY,10,GETDATE())
Q) Display all those Employees data that have been hired on Sunday.
SELECT ENAME, HIREDATE FROM EMP WHERE DATENAME(DW,HIREDATE) = 'SUNDAY'
Q) Display all those Employees who have been hired in the month of December.
SELECT ENAME,HIREDATE FROM EMP WHERE DATENAME(MM,HIREDATE)= 'DECEMBER'
Q) Display all those Employees who have been hired in second half of the week.
SELECT ENAME, HIREDATE FROM EMP
WHERE DATEPART (DW, HIREDATE) > = ROUND(7/2.0,0)
DATA CONVERSION:
This function will support to convert the data stored with one type to the other type.
SQL SERVER will convert the data with the support of following two functions.
CAST(SOURCE_DATA AS TARGET_DATA_TYPE)
CONVERT(TARGET_DATA_TYPE, SOURCE_DATA [NUMBER])
SELECT ENAME + ' WORKING AS ' + JOB + ' IN DEPT ' + CAST(DEPTNO AS
VARCHAR(3)) FROM EMP
5/ CAST(2 AS FLOAT)
5/ CONVERT(FLOAT,2)
CONVERT(VARCHAR(30), GETDATE(),0)
CONVERT(VARCHAR(30), GETDATE(),8) for time
** 0 stands for Date formats, there are more than 100 Date formats.
** 8 & 108 are particularly assigned for time format
**The data will be grouped into four groups based on given NTILE number.
OTHER FUNCTIONS
ISNULL(EXPRESSION1, EXPRESSION2)
This Function will search for NULL values in Expression1 and Substitutes Expression2 at all the rows
of Expression1 where NULL values are found, Expression2 is depended on data type of Expression1.
SELECT ENAME, SAL, COMM, ISNULL(COMM,0) RS FROM EMP
SELECT ENAME, SAL, COMM, ISNULL(ENAME,'UNKNOWN') UN FROM EMP
SELECT ENAME ,SAL, COMM, ISNULL ( CAST(COMM AS VARCHAR(4),'NC') RS
FROM EMP
SELECT ENAME,SAL,COMM,SAL+ISNULL(COMM,0) RS FROM EMP
COALESCE(EXPRESSION1,EXPRESSION2EXPRESSIONN) - It will search for NULL values and
Substitutes Expression2 at all rows of Expression1 where NULL values are found. It Substitutes
Expression3 if Expression2 contains NULL values so on it can have any number of expressions.
SELECT EMPNO,ENAME,MGR,SAL,COMM COALESCE(COMM,SAL,MGR,EMPNO,25) RS
FROM EMP
NULLIF( EXPRESSION1, EXPRESSION2) - It is used to compare two expressions of any data
NULLIF(10,10) -----NULL
NULLIF(10,90) -----10
NULLIF(X,Y)--- X
ENAME,LEN(ENAME)L1,JOB,LEN(JOB)L2 NULLIF(LEN(ENAME),LEN(JOB))RES
EMP
CASE EXPRESSION
It supports to specify multiple conditions provided with their respective results. If no condition is
satisfied then it will provide default result.
Syntax:
CASE EXPRESSION
WHEN CONDITION1 THEN RESULT1
[ WHEN CONDITION2 THEN RESULT2 ]
ELSE
DEFAULT_RESULT
END [ALIAS_NAME]
Q) Display ENAME, SAL and INCREMENT the salary with difference %s based on category of JOB.
Manager 18%, Clerk 15%, Others 12%
SELECT ENAME,SAL,JOB,
CASE JOB
WHEN 'MANAGER' THEN SAL*18/100
WHEN 'CLERK' THEN SAL * 15/100
ELSE
SAL*12/100
END INCR
FROM EMP
Q) Display ENAME, DEPTNO, SAL and INCREMENT the Salary with different %s on category of Dept
No 10 20%, Dept no 20 18%, Dept no 30 15%
SELECT ENAME, DEPTNO, SAL,
CASE DEPTNO
WHEN 10 THEN SAL* 20/100
WHEN 20 THEN SAL * 18/100
WHEN 30 THEN SAL*15/100
END INCR
FROM EMP
SELECT
SELECT
SELECT
SELECT
SELECT
Q) Display DEPTNO, total salary and number of employees related to Dept No 20.
SELECT DEPTNO, SUM(SAL), COUNT(*) FROM EMP
WHERE DEPTNO = 20 GROUP BY DEPTNO
CUBE:
This operator is also used only at GROUP BY clause.
It will support to perform individual totals, group totals, regroup totals and additional row is
generated for grand totals.
SELECT DEPTNO, JOB, SUM(SAL), COUNT(*) FROM EMP
GROUP BY DEPTNO, JOB WITH CUBE
SELECT
SUM
SUM
SUM
SUM
FROM
DISTINCT JOB,
(CASE DEPTNO WHEN 10 THEN SAL END) D10,
(CASE DEPTNO WHEN 20 THEN SAL END) D20,
(CASE DEPTNO WHEN 30 THEN SAL END) D30,
(SAL) TOTAL SAL
EMP GROUP BY JOB
**This type of queries is called as CROSS TAB QUERIES or MATRIX FORMAT QUERIES.
HAVING CLAUSE:
It is used to make conditions on grouped data.
It also supports to make conditions on columns those columns which are used at group by
clause.
Q) Display Dept No, Total Salary of those departments where total salary is more than 9000.
SELECT DEPTNO,SUM(SAL) FROM EMP GROUP BY DEPTNO HAVING SUM(SAL) > 9000
Q) Display Dept No, total salary of those departments where total salary is more than 9000 and
belong to dept no 20.
SELECT DEPTNO,SUM(SAL) FROM EMP GROUP BY DEPTNO
HAVING DEPTNO = 20 AND SUM(SAL) > 9000
When columns are different in output, it will provide that column name which is in first
query.
To arrange the data in ascending order or in descending order order by clause should be
associated to last query.
When columns are different in queries column of first query should be used at order by
clause.
UNION
Eliminates duplicates.
It always arranges the data in ascending order.
When multiple columns are used, it will eliminate only if all the columns contain duplicates.
SELECT JOB FROM EMP WHERE DEPTNO = 10
UNION
SELECT JOB FROM EMP WHERE DEPTNO = 20
SELECT
UNION
SELECT
SELECT
UNION
SELECT
INTERSECT
Extracts common rows from two or more result sets.
Eliminates duplicates.
Always arranges in ascending order.
SELECT JOB FROM EMP WHERE DEPT NO=10
INTERSECT
SELECT JOB FROM EMP WHERE DEPT NO=20
EXCEPT
It always produces output from first query, except the rows that are found at the result set
of 2nd query.
It will eliminate duplicates.
SELECT JOB FROM EMP WHERE DEPT NO=10
EXCEPT
SELECT JOB FROM EMP WHERE DEPT NO=20
SELECT JOB FROM EMP WHERE DEPT NO=20
EXCEPT
SELECT JOB FROM EMP WHERE DEPT NO=10
SELECT
SELECT
SELECT
SELECT
JOINS
It is a process of joining columns from 2 or more tables, which always produces a new table
Joining conditions is must
To join n tables n-1 join conditions are required
A joining condition is followed by any number of filtering conditions.
It is a temporary name provided for a table, which provides its usage till the query is in
execution.
It is flexible in usage.
It can be used anywhere in SELECT statement.
NON EQUI JOIN: At these joining concept columns from two or more tables can be joined by making
a joining condition other than equal to operator.
SELECT E.*, GRADE FROM EMP E, SALGRADE S
WHERE SAL BETWEEN LOSAL AND HISAL
SELECT E.*, GRADE FROM EMP E, SALGRADE S
WHERE SAL >= LOSAL AND SAL <= HISAL
Q) Display EMPNO, ENAME, DNAME, LOC, and GRADE of all the Employees.
SELECT
FROM
WHERE
AND
EMPNO, ENAME,D.DNAME,D.LOC,S.GRADE
EMP E , DEPT D , SALGRADE S
E.DEPTNO = D.DEPTNO
E.SAL BETWEEN S.LOSAL AND S.HISAL
Q) Display ENAME, JOB, SAL, COMM, DEPTNO, DNAME, LOC & GRADE of all those Employees who
are working at ACCOUNTING, SALES and they have managers to report and they dont earn
commission and their Salary more than 1000, arrange the data in ascending order.
SELECT
FROM
WHERE
AND
AND
AND
AND
AND
ENAME,JOB,SAL,COMM,MGR,E.DEPTNO,D.DNAME,D.LOC,S.GRADE
EMP E, DEPT D, SALGRADE S
E.DEPTNO = D.DEPTNO
E.SAL BETWEEN S.LOSAL AND S.HISAL
D.DNAME IN('ACCOUNTING','SALES')
E.MGR IS NOT NULL
E.COMM IS NULL
E.SAL > 1000 ORDER BY E.DEPTNO
SELF JOIN:
At this joining concept single table will be used for more than once differentating them with
the Alias Name.
Data is retrived and joining condition is made in a single table.
Q) Display EMPNO, ENAME, MGR, MGRNAME for those Employees who have managers to report.
SELECT M.EMPNO,M.ENAME,M.MGR,E.ENAME FROM EMP E , EMP M
WHERE E.EMPNO = M.MGR
CARTESIAN JOINS:
At this joining concept, Columns from two or more tables can be joined without using any
joining condition.
It provides mutliplication of Rows among the tables used for joins
SELECT EMPNO, ENAME, JOB, E.DEPTNO, D.DNAME FROM EMP E,
DEPT D
OUTER JOINS :
At this concept of joining, Columns from two or more tables with respect to rows can be
joined that gets matched and unmatched records with the joining condition.
* Operator is used for Outer Joins.
SQL Server 2005 is restriced with the implementation of Outer joins through operator
In order to implement outer joins in SQL Server 2005 data base compatability level should be
used by a predefined procedure called SP_DBCMPTLEVEL.
Syntax :
SP_DBCMPTLEVEL @DBNAME = <'DATABASE_NAME'>
@NEW_CMPTLEVEL = '80'
Syntax:
SELECT * FROM TABLE1 , TABLE2
WHERE TABLE1.COLUMN1 *= TABLE2.COLUMN2
SELECT EMPNO, ENAME, JOB, SAL, D.DNAME
FROM EMP E , DEP D WHERE E.DEPTNO *= D.DEPTNO
SELECT EMPNO, ENAME, JOB, SAL, D.DNAME
FROM EMP E , DEP D WHERE D.DEPTNO *= E.DEPTNO
RIGHT OUTER JOIN: At this joining concept, Outer Join operator is placed on RIGHT side of joining
condition, it will extract matched and unmatched rows from the table which is placed on RIGHT side
of Joining condition and substitutes NULL Values for the columns of a table which is on LEFT side of
the Joining Condition.
Syntax:
SELECT * FROM TABLE1 , TABLE2
WHERE TABLE1.COLUMN1 =* TABLE2.COLUMN2
SELECT EMPNO, ENAME, JOB, SAL, D.DNAME
FROM EMP E , DEP D WHERE E.DEPTNO =* D.DEPTNO
SELECT EMPNO, ENAME, JOB, SAL, D.DNAME
FROM EMP E , DEP D WHERE D.DEPTNO =* E.DEPTNO
ANSI JOINS: This are implemented by using key words used at FROM Clause of SELECT STATEMENT.
SELECT TABLE1.COLUMN1,TABLE2.COLUMN2
FROM TABLE1 [ALIAS] < JOIN_TYPE > TABLE2 [ALIAS]
ON <JOIN_TYPE> -- JOINING CONDITION
TABLE3[ALIAS] ON ---- JOINING CONDITION
SELF JOIN:
SELECT M.EMPNO,M.ENAME,M.MGR,E.ENAME FROM EMP E INNER JOIN EMP M
ON E.EMPNO = M.MGR
CROSS JOIN:
SELECT EMP.*, DEPT.* FROM EMP CROSS JOIN DEPT
SELECT EMP.*, DEPT.*, SALGRADE.*
FROM EMP CROSS JOIN DEPT CROSS JOIN SALGRADE
OUTER JOINS
LEFT OUTER JOIN:
SELECT E.*, D.* FROM EMP E LEFT OUTER JOIN DEPT D
ON E.DEPTNO = D.DEPTNO
A Query which is written with the other Query refers to NESTED Query.
A Query which allows to write other query is called Outer Query or Main Query.
A Query which is written in main query is called INNER or SUB-QUERY
Q) Display EMPNO, ENAME, JOB, SAL, DEPTNO of that Employee who is being paid by Max Salary.
SELECT EMPNO, ENAME, JOB, SAL, DEPTNO
FROM EMP WHERE SAL = ( SELECT MAX(SAL) FROM EMP)
Q) Display Ename, Job of those Employees who are working on a same job as of TURNER.
SELECT ENAME, JOB
FROM EMP WHERE JOB = ( SELECT JOB FROM EMP WHERE ENAME = 'TURNER')
Q) Display ENAME,SAL of those Employees whose salary is more than average salary of Deptno 20.
SELECT ENAME , SAL
FROM EMP WHERE SAL > ( SELECT AVG(SAL) FROM EMP WHERE DEPTNO = 20)
Q) Display ENAME,JOB,SAL of those Employees who are working on a same job as of Allen and
Salary is more than Salary of Miller.
SELECT ENAME, JOB, SAL
FROM EMP WHERE JOB = ( SELECT JOB FROM WHERE ENAME = 'ALLEN')
AND SAL > ( SELECT SAL FROM EMP WHERE ENAME = 'MILLER')
Q) Display EMPNO, ENAME, JOB, DEPTNO of those Employees who are working at ACCOUNTING,
SALES Departments.
SELECT EMPNO, ENAME, JOB, DEPTNO FROM EMP WHERE DEPT IN ( SELECT DEPTNO
FROM DEPT WHERE DNAME IN ('ACCOUNTING', 'SALES'))
Q)Dislay ENAME, JOB, SAL, DEPTNO of those Employees whose salary is more than Max Sal of Sales
Department.
SELECT
FROM
WHERE
WHERE
EMPNO,ENAME,JOB,SAL
EMP WHERE SAL > ( SELECT MAX(SAL) FROM EMP
DEPTNO = (SELECT DEPTNO FROM DEPT
DNAME = 'SALES'))
Q) Display DEPTNO & Average Salary of those departments whose average salary is more than the
average salary of all Employees.
SELECT DEPTNO, AVG(SAL) FROM EMP
HAVING AVG(SAL) > (SELECT AVG(SAL) FROM EMP GROUP BY DEPTNO)
Syntax:
SELECT ........ FROM ( SELECT ....... FROM TABLE) ALIAS_NAME
SELECT * FROM ( SELECT EMPNO, ENAME, SAL, DEPTNO FROM EMP) E
SELECT EMPNO, ENAME, JOB, SAL
FROM ( SELECT EMP, ENAME, SAL FROM EMP ) E
Q) Write a query to display all those Employees whose record position at odd Number
SELECT * FROM ( SELECT EMPNO,ENAME,SAL, ROW_NUMBER()
OVER (ORDER BY EMPNO) RN FROM EMP) E WHERE RN %2 =1
Q) Write a query to display all thoose Employees whose record position at even numbers
SELECT * FROM ( SELECT EMPNO,ENAME,SAL, ROW_NUMBER()
OVER (ORDER BY EMPNO) RN FROM EMP) E WHERE RN %2 = 0
SOME/ANY:
This Operator will allow a Sub Query to written multiple rows even though in OUTER Query
Condition is made by using relational operators.
It works like OR LOGICAL OPERATOR.
It Can be used with all RELATIONAL OPERATORS [ > ANY , < ANY, = ANY, !=ANY , >= ANY, <=
ANY ]
SELECT * FROM EMP WHERE SAL < ANY (SELECT DISTINCT SAL FROM EMP
WHERE DEPTNO = 20)
ALL :
This Operator also allows a sub query to written muliple rows even though in Outer Query
condition is made using relational operators.
It works like AND LOGICAL OPERATOR.
It can also be used with ALL Relational Operators.
SELECT * FROM EMP WHERE SAL < ALL (SELECT DISTINCT SAL FROM EMP
WHERE DEPTNO =20)
CORRELATED SUBQUERIES :
This Queries provides different execution to Nested Queries i.e First it executes OUTER
Query then executes INNER Query.
Nested Query is called as UNI-DIRECTIONAL Query
Correlated Query is called as BI-DIRECTIONAL Query
Correlated queries gets executed in the following way First executes OUTER query retriveing
only one ROW(called as CANDIDATE ROW) at a time and that ROW is given to INNER Query
for processing after procesing INNER Query returns Output and will be given to OUTER
Query for comparision, based on it OUTER Query displays the Output.
This Queries are identified when outer queris table name is provided with the Alias name
and that alias Name is been used at Sub-Query.
Q) Display EMPNO,ENAME,JOB,SAL,DEPTNO of those Employees whose salary is more than
AVERAGE SALARY of respective Departments.
SELECT EMPNO,ENAME,JOB,SAL,DEPTNO FROM EMP E
WHERE SAL > ( SELECT AVG(SAL) FROM EMP WHERE DEPTNO = E.DEPTNO )
Q) Display those Employee Details who are being paid by minimumm salaries in their respective
Departments.
SELECT EMPNO, ENAME, JOB, SAL , DEPTNO FROM EMP E
WHERE SAL = ( SELECT MIN(SAL) FROM EMP WHERE DEPTNO = E.DEPTNO)
NOT EXISTS:
This operator also writtens Boolean Value i.e. TRUE or FALSE
If Condition at INNER Query is FALSE then it returns TRUE
Q) Display DEPTNO, DNAME of those Departments where no Employee is working.
SELECT DEPTNO, DNAME FROM DEPT D
WHERE NOT EXISTS (SELECT 1 FROM EMP WHERE DEPTNO = D.DEPTNO)
OR
SELECT DEPTNO,DNAME FROM DEPT
WHERE DEPTNO = (( SELECT DEPTNO FROM DEPT )
EXCEPT (SELECT DISTINCT DEPTNO FROM EMP))
INSERT:
This DML Command is used to Insert a row into an existing table , it provides its working in 3
ways.
Inserting ONE Row at a time in ONE Table.
Inserting MULTIPLE Rows at a time in ONE Table.
Inserting MULTIPLE Rows at a time in MULTIPLE Tables.
INSERT ..... ONE ROW ...... ONE TABLE
When One Row is inserted at a time in One Table it supports to store data of all Columns or
Partial Columns
When Datais inserted for required Columns, The Other Columns will be stored by NULL
Values
Syntax:
INSERT [ INTO ] <TABLE_NAME>[ COLUMN_ALIAS ]
VALUES ( LIST_OF_VALUES )
INSERT DEPT VALUES (50,'HR','HYD')
INSERT DEPT VALUES (60,'ADMIN')
INSERT DEPT VALUES (70,'ECE',NULL)
INSERT DEPT (DEPTNO,DNAME)
VALUES (80,'FINANCE'),
VALUES (90,'ARTS'),
VALUES (95,'TEST')
**Using Values in More than once in INSERT Command is valid in 2008 Version of SQL Server.
INSERT ..... MULTIPLE ROWS ...... IN ONE TABLE
Select as Sub-Query can be written under Insert Query, Output returned by Sub Query can be used
by INSERT Query to INSERT the Rows into an Existing Table.
Syntax:
INSERT [ INTO ] <TABLE_NAME> [(COLUMNS_LIST)] < SELECT QUERY >
INSERT EMP2 SELECT * FROM EMP
INSERT EMP2 ( EMPNO, ENAME, JOB, SAL) SELECT (EMPNO, ENAME, JOB, SAL)
FROM EMP
INSERT EMP2 ( EMPNO, ENAME, JOB, SAL) SELECT (EMPNO, ENAME, JOB, SAL)
FROM EMP WHERE DEPTNO =10
UPDATE :
This DML Command is used to modify existing Data with User Required new Data.
Syntax:
UPDATE < TABLE_NAME >
SET COLUMN1 = VALUE/EXPRESSION, COLUMN2 = VALUE/EXPRESSION
WHERE = CONDITIONS
Q) Update the JOB, SAL of MARTIN from SALESMAN to CLERK and 1250 to 2000.
UPDATE EMP SET JOB = 'CLERK', SAL = 2000 WHERE ENAME = 'MARTIN'
Q) Update the Salary of James with an increament of 1000 and provided the Comm as 10% of Salary.
UPDATE EMP SET SAL = SAL+1000, COMM = (SAL+1000)*10/100.0
WHERE ENAME = 'JAMES'
Q) Update the Salary of ALLEN with an increament of 1000, Sal of JAMES with 500 and other
Employees sal should remain unchanged.
UPDATE EMP
SET SAL = CASE ENAME
WHEN 'ALLEN' THEN SAL + 1000
WHEN 'JAMES' THEN SAL + 500
ELSE SAL
END
WHERE ENAME IN( 'ALLEN','JAMES')
When Multiple Colums are used with Update Command all the Columns get updated at a
time.
Single column cannot be used for more than once
When Single Column has modification with different Values we need to use CASE Expression
DELETE :
It is used to Delete One or More rows at a time from an existing table.
Syntax :
DELETE FROM < TABLE_NAME > [ WHERE CONDITIONS ]
Q) Delete all those Employees whose Salary is more than Average Salary of all Employees.
DELETE FROM EMP WHERE SAL > ( SELECT
Q) Delete all those Employees who are working on a same Job as of SMITH.
DELETE FROM EMP WHERE JOB = (SELECT JOB FROM EMP WHERE ENAME = 'SMITH')
MERGE :
It is introduced in SQL SERVER 2008
It is called as an ETL Command ( Extracting, Transformation, Loading)
It is used to Join the data from 2 Tables into a Single Table
It is used to Execute INSERT, UPDATE, DELETE commands simmaltenously
It works based on Four Clauses USING, ON , WHEN MATCHED, WHEN NOT MATCHED
WHEN MATCHED, WHEN NOT MATCHED Clauses are Flexible in usage any number of times
can be used.
Usage of Semi-Colon at the end of the Query is compulsory.
Syntax :
MERGE INTO < TABLE_1_NAME > [TABLE_1_ALIAS]
USING < TABLE_2_NAME > / < SELECT QUERY > [ TABLE_2_ALIAS ]
ON JOINING CONDITION
WHEN MATCHED [ FILTERING CONDITIONS ] THEN
UPDATE / DELETE COMMANDS
WHEN NOT MATCHED [ FILTERING CONDITIONS ] THEN
INSERT [ COLUMNS_LIST ] VALUES [ LIST_OF_VALUES ] ;
Example:
MERGE INTO EMP E1
USING (SELECT EMPNO, ENAME, JOB, SAL, SAL*12 ASAL FROM EMP) E2
ON (E1.EMPNO = E2.EMPNO)
WHEN MATCHED THEN
UPDATE SET E1.SAL = E2.SAL
WHEN NOT MATCHED THEN
INSERT VALUES (E2.EMPNO,E2.ENAME,E2.JOB,E2.ASAL);
MERGE INTO EMPB E1
USING (SELECT EMPNO, ENAME, JOB, SAL, SAL*12 ASAL FROM EMP)E2
ON (E1.EMPNO = E2.EMPNO)
WHEN MATCHED AND E1.JOB = 'CLERK' THEN
UPDATE SET E1.SAL = E2.SAL
WHEN MATCHED AND E1.JOB = 'SALESMAN' THEN
DELETE
WHEN NOT MATCHED AND E2.JOB = 'ANALYST' THEN
INSERT VALUES( E2.EMPNO,E2.ENAME,E2.JOB,E2.ASAL);
COMMIT :
This TCL Command is used to Make a transaction ( SET OF OPERATIONS ) Permanent in a
DATABASE.
When multiple isolate transactions are created requires equal number of COMMITS to make
them permanent in a DATABASE.
ROLLBACK :
This TCL Command is used to Cancel the Complete Transaction or Partial Transaction
When isolated Multiple transactions are created in a Singel Session.
A Single ROLLBACK command would cancel all the transactions.
ROLLBACK [ TRAN / TRANSACTION ] NAME
SAVE :
This TCL Command is used to create a Sub-Transactions under a Main Transcation. The
Created Sub Transaction can be cancelled partialy.
Random Selection from Cancellaiton of Sub Transaction is not allowed
SAVE [ TRAN / TRANSACTION ] NAME
Example:
BEGIN TRAN
DELETE FROM EMP WHERE DEPTNO = 30
SAVE TRAN F
INSERT DEPT VALUES (.....)
UPDATE DEPT SET COL = VAL WHERE DEPTNO = 10
SAVE TRAN S
DELETE FROM SALGRADE
DELETE FROM EMP
Second
ROLLBACK TRAN S
ROLLBACK TRAN F
ROLLBACK
Third
ROLLBANK TRAN F
ROLLBACK
When a session contains a transaction it cannot be closed directly , if it is trying closed it confirms for
COMMIT and ROLLBACK of Transactions.
DATA DEFINATION LANGUAGE :
This language is used to Create, Modify and Drop DATABASE Objects ie. Tables, Views,
Indexes, Synonms, Stored Procedures , Stored Functions, Stored Triggers.
This language includes the following Commands CREATE, ALTER, TRUNCATE, DROP
In SQL Server 2005 if DDL Commands are associated to Transaction then the Operation is
Temporary.
REPRESENTATION OF DATA
Data in SQL Server gets represented based on three Key Points DATANAME, DATATYPE, DATASIZE.
DATA NAME : Often Called Column Name , Identifier or Field or Attribute. It is the one which gives
Identification to Data.
Rules to be followed before using Column Names :
Column Name can be Minimum of 1 Character and Maximum of 127 Characters.
4 BYTES
2 BYTES [ -32768 to 32767 ]
8 BYTES
1 BYTES [ 0 to 255 ]
(PREC [SCALE])
(PREC [SCALE])
8 BYTES
4 BYTES
VARIES
4 BYTES
STRING DATATYPE:
CHAR(SIZE)
NCHAR( SIZE )
VARCHAR( SIZE )
NVARCHAR ( SIZE )
UNSTURCTURED DATA
BINARY
VARBINARY
IMAGE
XML Introduced from 2005 to store data in XML Format,
Note:
TYPES OF COLUMNS
Column in SQL Server 2005 are classified in following types.
Normal Column: Column Associated by DATA TYPE & DATA SIZE.
RNO INT, SNAME VARCHAR (10)
Points to be remember:
IDENTITY COLUMN
A table can have only ONE IDENTITY Column.
IDENTITY Column will generate sequence of numbers automatically by default starts from
One and increaments by One.
By Default IDENTITY Column will not accpet Explicit Values.
IDENTITY Column can be specified by User Defined Start (SEED) and Increament Value.
Syntax:
IDENTITY ( SEED, INCREAMENT )
SNO INT IDENTITY
**By default it starts from 1 and it will increament by 1
SNO INT IDENTITY (101,4)
**It starts from 101 and it will increament by 4
In order to store explicit values for IDENTITY COLUMN Following SET Command should be
used.
SET IDENTITY_INSERT < TABLE_NAME > ON / OFF [ DEFAULT IS OFF ]
When Explicit Values are provided for identity colum it is must to mention that column name
in the Column List.
IDENTITY COLUMN will allows duplicates.
When Explicit Values are stored in IDENTITY COLUMN, later when implicit values are stored
it would be generate the sequence of numbers based on the biggest value of that column.
IDENTITY COLUMN can be associated with the following data types i.e
INT,BIGINT,SMALLINT,TINYINT,DECIMAL OR NUMERIC with SCALE
@@IDENTITY - It returns the Last Value stored into IDENTITY COLUMN ( Related to Last Table )
specific table.
SELECT IDENT_CURRENT( < TABLE_NAME > )
SYS.IDENTITY_COLUMNS - This System Table also supports to get the last value of IDENTITY
IDENT_SEED ( < TABLE_NAME > ) - It returns the start value of the IDENTITY COLUMN
created at table.
SELECT IDENT_SEED ('PRODUCT')
IDENT_INCR ( < TABLE_NAME > ) - It returns the increamented value of the IDENTITY
To restart the sequence of Numbers for IDENTITY COLUMN an option called CHECKIDENT of DBCC (
DATABASE CONSISTENCY CHECKER ) Command.
DBCC CHECKIDENT ( <TABLE_NAME>, RESEED , VALUE )
Example:
CREATE TABLE PRODUCT (
QTY INT, PRICE FLOAT,
INSERT
INSERT
INSERT
INSERT
INSERT
INTO
INTO
INTO
INTO
INTO
PRODUCT
PRODUCT
PRODUCT
PRODUCT
PRODUCT
VALUES
VALUES
VALUES
VALUES
VALUES
PNAME VARCHAR(10),
(201,'X',10,15)
(202,'Y',10,15)
(203,'Z',10,15)
(204,'A',10,15)
(204,'B',10,15)
Q) Create a Table Called STUDENT which contains ROLLNO, NAME, MPC MARKS.
Calculate for total and average marks.
Using Computed Column
CREATE TABLE STUDENT ( ROLLNO INT , STNAME VARCHAR(10),
MATHS INT, PHYSICS INT, CHEMISTRY INT,
TOTAL AS MATHS*PHYSICS*CHEMISTRY,
AVGM AS ((MATHS*PHYSICS*CHEMISTRY)/3.0))
UPDATE STUDENT
SET TOTAL = MATHS*PHYSICS*CHEMISTRY,
AVGM =((MATHS*PHYSICS*CHEMISTRY)/3.0))
Q) Create a table EMP which contains ECODE, ENAME & GENDER, UPDATE Gender by changing the
data to MALE to FEMALE and FEMALE to MALE.
UPDATE EMP
SET GENDER = CASE GENDER
WHEN 'MALE' THEN 'FEMALE'
WHEN 'FEMAE' THEN 'MALE'
END
Syntax:
SP_RENAME ' < TABLENAME.COLUMNNAME > ', ' < NEW_COLUMN_NAME >'
SP_RENAME 'EMP.EMPNO','ECODE'
SP_RENAME ' < OLD_TABLENAME > ', ' < NEW_TABLENAME >'
TRUNCATE :
This DDL Command is used to delete the rows from a table
Syntax:
DELETE
It is a DML Command
Supports to delete the rows on
conditional basis
Slow in Execution
Supports to invoke Triggers
Identity Column Value will be in
continuation even after deleting all
rows.
TRUNCATE
It is a DDL Command
No Conditional deletion is allowed
Fast in Execution
Does not support
When a table is truncated Identity
Column Values will be resetted to start
position(SEED VALUE)
DROP:
This DDL Command is used to drop the DATABASE Objects like tables, views, synonms, indexes,
Stored Procedures, Functions, Trigers Etc.
Dropping a Table:
When a table is dropped, objects like constraints, indexes, triggers are automattically dropped.
Syntax:
**To get Top rows with out using TOP Keyword or WHERE Clause, we need to use SET ROWCOUNT
Function.
Q) Display maximum salaries
SELECT * FROM EMP WHERE SAL IN (
SELECT DISTINCT TOP 3 SAL FROM EMP ORDER BY SAL DESC)
UPDATE TOP(3) FROM EMP SET SAL = SAL + 1000
DELETE TOP (3) FROM EMP
Data Constraint will make SQL Server to avoid invalid data entry.
Every Constraint is provided by a unique name, which can be of predefined or user defined.
To specify User Defined Constraint Name a Keyword called CONSTRAINT is used.
Advantage of Constraint Name is found when a constraint is disabled/enabled or when the
constraint is dropped.
Constraint is created as DATABASE Object.
Constraint Names should be always provided with unique names Because it will be checked
at Schema Level.
Types of Constriants
DOMAIN INTEGRITY CONSTRAINTS -- NOTNULL, CHECK, DEFAULT
ENTITY INTEGRITY CONSTRAINTS -- PRIMARY KEY, UNIQUE
REFERENTIAL INTEGRITY CONSTRAINTS -- FOREIGN KEY
DOMAIN INTEGRITY CONSTRAINT
These constaints are specified immediately after a Column, It includes NOTNULL, CHECK, DEFAULT.
NOTNULL
It is not a Constraint.
It can be provided for any Number of Columns.
It will not allow to store NULL VALUES, But will allow to store Duplicates
CHECK
This Constraint is used to specify User Defined Conditions
Any Number of Columns Can be set with the CHECK Constratint
DEFAULT
This Constraint is used to specify Default Value for Column.
When a user does not provide data (INSERT) then it will store Default value.
Example:
CREATE TABLE EMP1(
ENO INT NOT NULL, ENAME VARCHAR(10) NOT NULL,
JOB VARCHAR(15) CHECK (JOB IN ('CLERK','MANAGER','OPERATIONS')),
SAL INT CONSTRAINT SAL_CHK CHECK (SAL BETWEEN 15000 AND 20000),
DOJ SMALLDATETIME DEFAULT GETDATE(),
DNO INT CONSTRAINT DF_DNO DEFAULT 20)
TABLE LEVEL
CREATE TABLE STUDENT ( RNO INT , SNAME VARCHAR(10) PRIMARY KEY (RNO))
NORMALIZATION
It is a process of splitting a single table into two or more tables to avoid redundancy and to promote
integrity.
It is a process of deciding number of tables required columns in each table, relationships among
tables is known as NORMALIZATION.
The aim of Normalization is to store the data in simple format.
Advantages:
Minimizes redundancy
Reduces Complexity
Easy Maintanence
Making tables ready to perform JOINS and SUBQUERIES
UNNORMALIZED TABLE :
OrdNo
OrdDate
Cid
Cname
Caddr
Cphone
12/7/2011
S12
Sunil
S Nagar
111
11/7/2011
A13
Shiva
R Nagar
222
10/7/2011
S12
Sunil
S Nagar
111
Items
P10 PENS 100
B12 BOKS 200
E17 ERSR 200
P10 PENS 100
S13 SCLS 200
P10 PENS 300
S13 SCLS 200
To satisfy the First Normal Form, for the above unnormalized table, the below tables can be created
to normalize the tables.
CID(Primary Key)
Customer
Cname Caddr CPhone
OrderNo(Primary Key)
OrderNo
Order 1
Ord_Date Items
CID(Foregin Key)
Order 2
Ord_Date ItemNo ItemName Qty
CID(Foreign Key)
OrderNo(Primary Key)
Order 3
Ord_Date CID(Foreign Key)
Items
ItemNo ItemName Qty OrderNo(Foreign Key)
THIRD NORMAL FORM
Unnormalized Table:
WID(Primary Key)
E10
M15
C3
Workers 1
Skills
Electrician
Mechanic
-
Bonus
3000
2500
Skills(Primary Key)
Bonus
Workers2
WID(Primary Key)
Skills (Foreign Key)
SYNONYMS
It is introduced from SQL SERVER 2005.
It is created for tables, views where from they can be referred with that name.
It is a DATABASE Object which resides in DATABASE Server and provides its working till the
Base Object exists.
It is a Permanent Alias Name, any modifications are made through SYNONYM will reflect on
Base object and vice versa.
Note: SQL Server does not allow to create recursive Synonym.
Syntax:
CREATE SYNONYM < SYNONYM_NAME > FOR < BASE_OBJECT >
Q) Display the List of Synonyms and Base Object Names in the DATABASE.
SELECT NAME, BASE_OBJECT_NAME FROM SYS.SYNONYMS
Q) Drop a SYNONYM.
DROP SYNONYM < SYNONYM_NAME >
DROP SYNONYM SL
Syntax:
Q) Creating a Schema.
CREATING INDEX
**A table can have more than One Index whereas a column can have only one Index.
CLASSIFIED IN THREE TYPES
Clustered Index
Non Clustered Index
Unique
Syntax:
CREATE [UNIQUE] / [CLUSTERED] / [NON CLUSTERED]
ON [ TABLE_NAME (COLUMN_NAME..)]
This index will not Alter the physical requirement of rows in a table.
A table can have 249 Non Clustered Indexs.
Data is not arranged in Order.
It is a default index created.
Data pages & index pages are stored at different level.
UNIQUE INDEX
This index can be created only on those columns which contains unique data.
This index is automatically created when unique constraint is created on a column.
**SQL SERVER creates an Index automatically for two Constraints Primary Key & Unique key.
TO REBUILD AN INDEX
When a page split occurs for the block which is stored at data page, to provide
fragmentation of that page to compress the memory at that data page, index can be rebuild.
Syntax:
Example:
CREATING VIEWS
View is a window of virtual table which will allow related users to view and modify related
data.
Any modifications are made through a view will reflect on base table and vice versa , which
leads to data consistency
A view is a database object which resides in database server and stores only select query in
compiled format hence it is called stored query.
ADVANTAGES
Provides Security.
Improves the performance of a query.
Network traffic gets reduced.
Shortens SQL queries.
Supports to perform DML operations on related data.
Support to generate summarized reports fastly.
Difference between TABLES and VIEWS
Tables
Contains Data
Tables are limited.
Independent object
Supports to DML operations on any
data
It can be associated with any Trigger
Views
Contains no data.
Views are Unlimited.
Dependent Object.
It supports to only related data.
It Can be associated with only INSTEAD
OF TRIGGER
TYPES OF VIEWS
Simple View
Check Option View
Complex View
Indexed View
**Simple View, Check Option View & Complex View are called as Standard Views.
SIMPLE VIEW:
A view which is created on a single table refers to single view and it should not contain
group functions, group by clause, distinct operator, joins and mathematical expressions.
When a simple view is created it should contain all mandatory columns of base table.
Syntax:
CREATE
[ WITH
AS
SELECT
[ WITH
In order to store Order by clause through SELECT query into a view, it is must to enclosed
TOP keyword.
When DDL operations are performed on base object they do not get reflected in view, to
update the view it should get refreshed, using a predefined procedure.
Example:
CREATE VIEW V1
AS
SELECT * FROM EMP
SP_HELP V1 to get the information about the View.
DELETE FROM V1 WHERE DEPTNO = 10
UPDATE FROM V1 WHERE ENAME = NULL
INSERT V1 (EMPNO,ENAME,SAL,DEPTNO) VALUES (1001,'X',5000,10)
Example:
ALTER TABLE EMP ADD EXP INT
SP_REFRESHVIEW V1
ALTER TABLE EMP DROP COLUMN HIREDATE
SELECT * FROM V1 -- it would be an error as column is missing.
SP_REFRESHVIEW V1
Example:
CREATE VIEW V2
AS
SELECT TOP(5) EMPNO, ENAME, SAL, DEPTNO, FROM EMP ORDER BY SAL
** For ORDER BY Clause TOP keyword is must.
CREATE VIEW V3
AS
SELECT EMPNO, ENAME, DEPTNO FROM EMP WHERE DEPTNO = 10
INSERT V3 VALUES()
Check Option View: When this option is associated with a view then it will check the condition
specified at where clause before data is inserted or updated into base object.
CREATE VIEW V4
AS
SELECT EMPNO, ENAME FROM EMP WHERE DEPTNO = 10 WITH CHECK OPTION
Complex View: A view is said to be complex view when it is associated with any of the following
Group By Clause
Group Functions
Distinct Operator
Joins
Mathematical Expressions
By Default Complex View is not updatable view(i.e. read only)
CREATE VIEW V5
AS
List of columns, table names that are enclosed in view through SELECT Query
Encrypted View:
When a view is encrypted it does not support to display the text which is stored in a view.
SQL Server does not support decryption of view.
To create this view, it should be associated by with encryption
The query which is stored in encrypted view can be altered
CREATE VIEW V9 WITH ENCRYPTION
AS
SELECT * FROM EMP
Schema Binding View: Rules to be followed for creating schema binding view.
Schema binding view will not support to store select query with * Selection operator.
It is must that table name specified in select query should be preceded by schema name
The advantage of creating schema binding views is that it will restrict the dropping of the
base objects
CREATE VIEW V10 WITH SCHEMA BINDING
AS
SELECT * FROM EMP
DROP TABLE DEPT --- ERROR
Indexed View:
These views will provide the improved performance than standard views.
These views when gets created should be attached with schema binding and there should be
an existing of clustered index.
These views will provide their importance specially when a query contains aggregate
functions
If a query contains aggregate function it includes following steps for the execution of a
query.
1)
2)
3)
4)
Syntax:
WITH TABLE_ALIAS (COLUMN_ALIAS)
AS
( SELECT QUERY) [ SELECT / INSERT / UPDATE / DELETE ]
If non recursive query is enclosed with multiple tables, mathematical expressions, distinct operator
etc is restricted with Data Manipulation Language Operations
WITH E (ENO, EM, PAY,
AS
(SELECT EMPNO, ENAME,
SELECT ENO, EM, PAY,
WHERE PAY = (SELECT
UNION ALL
SELECT * FROM E
DN)
SAL, DEPTNO FROM EMP)
DN FROM E
MAX (PAY) FROM E)
AS
(SELECT EMPNO, ENAME, SAL, DEPTNO, LOC FROM EMP, DEPT
WHERE EMP.DEPTNO = DEPT.DEPTNO)
Recursive Query: Common Table Expression which is created for the storage of select query and the
query which is used as a statement of execution will provide with temporary view name
WITH V1(I)
AS
(SELECT I = 1
UNION ALL
SELECT I = I + 1 FROM V1 WHERE I <=10)
SELECT I FROM V1
SECURITY
SQL SERVER 2005 provides a connection to a database server in 2 ways;
Windows Authentication: At this authentication a user connects to database server using windows
accounts i.e. users existing at windows operating system. It is called trusted connection.
SQL SERVER Authentication: At this authentication a user connects to database server using the SQL
SERVER accounts. By default SQL SERVER provides a login called SA, for which blank password cant
be provided in SQL SERVER 2005, whereas in previous versions blank password for SA can be
created.
CREATING A NEW LOGIN
To create a new login, it is essential that user should enter into a database which has got
system administration privileges.
Syntax:
CREATE LOGIN <LOGIN_NAME> WITH PASSWORD='PASSWORD'
CHECKEXPIRATION = OFF, CHECKPOLICY = OFF
DROPING A LOGIN:
To drop a login user should be in a database which has got administration privileges.
Syntax:
To create a login:
USE MASTER
CREATE LOGIN TESTLOGIN WITH PASSWORD = N 'TEST123'
DEFAULT_DATABASE = [TESTDB]
CHECKEXPIRATION = OFF, CHECKPOLICY = OFF
To Create a User
CREATE USER KUMAR FOR LOGIN SHIVA
'DB_DATAREADER','KUMAR'
'DB_DATAWRITER','KUMAR'
'DB_DATADDLADMIN','KUMAR'
'DB_OWNER','KUMAR'
Grant: This Data Control Language command is used to give rights on database objects created by
one user to get them access by other users
When permissions are granted it can be for multiple users, with multiple permissions but objects will
be only one.
Syntax
GRANT PRIVELLAGES [COLUMN_LIST]/ALL ON OBJECT_NAME TO USER1
[USER2,USER3...] /PUBLIC [WITH GRANT OPTION]
TRANSACT SQL
Transact SQL deals with set of statements that are grouped in the form of a block and submitted at
server at once for execution.
Difference between SQL & TSQL
SQL is a NON PROCEDURAL LANGUAGE since it deals with WHAT data to be extracted.
T-SQL is a PROCEDURAL LANGUAGE, it deals with WHAT Data to be extracted and HOW it
should be displayed.
T-SQL supports to submit a Block to server for execution in two ways.
Anonymous block it supports to store a block in SQL File.
Stored Block it stores the blocks in DataBase Server.
Stored Procedures
Stored Functions
Stored Triggers
Global Variables
These variables are comes with software (SQL Server).
These variables cant be used to initialize the values manually.
These variables will stored with data automatically based on the operations performed by
SQL Statements.
These variables are preceded by @@.
SELECT
SELECT
SELECT
SELECT
SELECT
number.
To display the List of ERROR messages
SELECT * FROM SYS.MESSAGES
** In SQL Server 2008 declaration & Initialization can be carried out simultaneously.
DECLARE @VARIABLE_NAME DATATYPE [( SIZE )] [ =VALUE ]
PRINT: It is an Output Statement of T-SQL which performs two tasks Display Messages & Display
Memory Values.
PRINT ' MESSAGE ' / @VARIABLE
IF CONDITIONAL STATEMENTS
It is used to compare the data provided with the result on Boolean expressions i.e. True or False.
Simple IF
IF Else IF
Nested IF
Simple IF Condition
This conditional statement is used to compare the data and allow to write a single true or
false statement or block.
If Multiple statements are to be executed on the basis of conditions then they should be
enclosed in a BEGIN and END Block
Syntax:
IF
ELSE
< FALSE STATEMENT >
Or
Q) Write a program to check whether a given number has perfect square or not.
DECLARE @N INT, @S INT
SET @N = 16
SET @S = SQRT(@N)
IF @S * @S = @N
PRINT 'YES'
ELSE
PRINT 'NO'
Q) Write a program to check whether a given number is ODD or EVEN without using MOD operator.
DECLARE @N INT, @R INT
SET @N = 7
SET @R = @N / 2
IF @R * 2 = @N
PRINT 'IT IS EVEN NUMBER'
ELSE
PRINT 'IT IS ODD NUMBER'
GOTO STATEMENT:
It is called branching statement, since it supports to transfer the control from one part of a
program to the other part of a program.
It works with Label assignment and Label Definition.
Label Assignment:
Label Definition:
Label_Name
< STATEMENTS >
**Label Defined with no label assignment is valid.
**Label Assigned but no label definition is invalid.
Example:
PRINT 'WELCOME'
GOTO X
Y:
PRINT 'THREE'
PRINT 'NINE'
GOTO Z
X:
PRINT 'SEVEN'
GOTO Y
Z:
PRINT 'THANX'
LOOPING CONSTRUCTS
LOOP: Execution of one or more statements repeatedly until a condition is satisfied. SQL Server
supports to work with the following Looping constructs.
WHILE LOOPING CONSTRUCT
WHILE < CONDITION >
BEGIN
< STATEMENTS >
END
ELSE
SET
SET
END
PRINT
PRINT
@C = @C + 1
@I = @I + 1
'VOWELS IN THE STRING '+@S+' ARE '+CAST(@V AS VARCHAR(5))
'CONSONANTS IN THE STRING '+@S+' ARE '+CAST(@C AS VARCHAR(5))
Q) Write a program to display the given string into substrings eliminating special characters.
DECLARE @W VARCHAR(50),@W1 VARCHAR(50)
DECLARE @I INT
SET @W='XYZ;ABC;PQR;AAA;BBB'
SET @I=CHARINDEX(';',@W)
WHILE @I>0
BEGIN
SET @W1 = LEFT(@W,@I-1)
IF LEN(@W1)!= 0
PRINT @W1
SET @W = SUBSTRING(@W,@I+1,LEN(@W))
SET @I = CHARINDEX(';',@W)
IF @I = 0
PRINT @W
END
DECLARE @X INT
SET @X=1
WHILE @X<=10
BEGIN
IF @X%3=0
BEGIN
SET @X=@X+1
CONTINUE
END
PRINT @X
SET @X=@X+1
END
IF @S = @N
PRINT ' IT IS A PERFECT NUMBER '
ELSE
PRINT 'IT IS NOT A PERFECT NUMBER'
EXCEPTION HANDLING:
Errors are classified into 3 types:
Complex Time Errors: These errors are often called as Syntax Errors. These errors are occurred when
the statements are written beyond the rule.
Logical Errors: Required output and generated output, when does not get match such type of errors
are called Logical Errors.
Runtime Errors: These errors will occur during the execution of a program. When these errors occur
in a program which is in execution in between gets terminated. In order to have a smooth execution
of program exception handling is used.
In SQL Server 2000 Exception handling was implemented using global variable @@ERROR
In order to raise the error with respect to user defined error message, a predefined
statement called RAISERROR is used.
Syntax:
RAISERROR (ARG1,ARG2,ARG3)
RAISERROR (50000,15,16)
ELSE
PRINT @A
SP_DROPMESSAGE MESSAGE_ID
Note:
Nested Try blocks are valid.
Multiple Try and Catch blocks are valid.
Following are the functions are used to display information about errors.
ERROR_SEVERITY()
ERROR_STATE()
ERROR_LINE()
ERROR_MESSAGE()
ERROR_NUMBER()
Q) Write a program to find the division of two values and handle the necessary exception using TRY
& CATCH Blocks.
DECLARE @A INT,@B INT,@C INT
SET @A = 5
SET @B = 0
BEGIN TRY
SET @C = @A/@B
PRINT 'QUOTIENT IS.....'+CAST(@C AS VARCHAR(5))
END TRY
BEGIN CATCH
PRINT 'CANT DIVIDE THE NUMBER BY 0'
PRINT ERROR_NUMBER()
PRINT ERROR_LINE()
PRINT ERROR_MESSAGE()
PRINT ERROR_SEVERITY()
PRINT ERROR_STATE()
END CATCH
PRINT 'THANX'
Q) Write a program to find square root of a given number and handle the necessary exceptions.
DECLARE @N INT, @S INT
SET @N = 144
BEGIN TRY
SET @S = SQRT(@N)
PRINT 'SQUARE ROOT IS ' + CAST(@S AS VARCHAR(5))
END TRY
BEGIN CATCH
PRINT 'CANT FIND THE SQUARE ROOT '
END CATCH
Q) Write a program illustrating that runtime error which occurs when the data exceeds the capacity
of Data Type.
DECLARE @N TINYINT
BEGIN TRY
SET @N = 200
PRINT @N
END TRY
BEGIN CATCH
PRINT 'VALUE EXCEEDS'
END CATCH
Q) Write a program to handle that runtime error which occurs when data stored in child table does
not exist at parent table.
CREATE TABLE REGISTER (REGNO INT CONSTRAINT REGNO_PK PRIMARY KEY)
INSERT
INSERT
INSERT
INSERT
INTO
INTO
INTO
INTO
REGISTER
REGISTER
REGISTER
REGISTER
VALUES(101)
VALUES(102)
VALUES(109)
VALUES(104)
CREATE TABLE RESULTS (HTNO INT CONSTRAINT HTNO_FK FOREIGN KEY REFERENCES
REGISTER(REGNO))
BEGIN TRY
INSERT INTO RESULTS VALUES(201)
END TRY
BEGIN CATCH
PRINT 'VALUE DOES NOT EXIST AT PARENT TABLE'
END CATCH
Working with EXEC (Execute): This Command is used to execute the queries that are stored in
variables.
Syntax:
EXEC (VARIABLE)
**The Query stored in a variable can be passed with arguments through variables.
DECLARE @S VARCHAR(200)
SET @S = 'SELECT * FROM EMP'
EXEC (@S)
DECLARE @S VARCHAR(200)
SET @S = 'SELECT * FROM EMP WHERE DEPTNO =10'
EXEC (@S)
DECLARE @S VARCHAR(200),@DNO INT
SET @DNO = INT
SET @S = 'SELECT * FROM EMP WHERE DEPTNO ='+CAST(@DNO AS VARCHAR(3))
EXEC (@S)
DECLARE @S VARCHAR(200)
SET @S = 'INSERT EMP(EMPNO,ENAME) VALUES(1001,''XYZ'')'
EXEC (@S)
SUB PROGRAMS:
It is a process of splitting a large application program into small modules or blocks.
SQL Server supports to write a sub program based on the following concepts
Stored Procedures, Stored Functions, Stored Triggers
Advantages of Sub Programs:
Provides security
It improves performance
Reduces Network Traffic
Readability gets increases
Code Reusability
Error Detection and modification is quite easy
Extensibility - It will allow a user to increase or decrease the code
STORED PROCEDURES:
SQL Server Supports to work with the following types of procedures
Predefined Procedures (SP_HELP, SP_RENAME.)
User Defined Stored Procedures
Extended Stored Procedures (XP_CMDSHELL,XP_READMAIL,XP_SENDMAIL)
USER DEFINED STORED PROCEDURES:
It is a stored block Data Base Object which resides in Data Base Server and contains SQL
Statements and Procedural Features.
A procedure in SQL Server 2005 can be made to return value to main program using RETURN
Key Word.
It can be created with and without arguments.
Data can be sent to procedures using INPUT Arguments, after processing that input few
values can be taken back to the main program using OUTPUT Arguments.
A procedure can be set with 1024 INPUT & OUTPUT Arguments.
When a Procedure is set with OUTPUT arguments then it is essential that at sending
arguments also OUPUT should be specified.
OUTPUT Arguments at a procedure which gets data the same will be reflected in main
program.
Procedure Set with INPUT Arguments will work for call by value and OUTPUT arguments
will work for call by reference
Syntax:
CREATE PROC / PROCEDURE < PROCEDURE_NAME > [(LIST_OF_ARGUMENTS)]
[ WITH ENCRYPTION ]
AS
BEGIN
[ DECLARATION BLOCKS ]
[ EXECUTION BLOCKS ]
[ EXCEPTION HANDLERS]
END
Q) Create a Procedure called DIV that takes two values as input and finds the quotient, handle the
necessary exceptions.
CREATE PROCEDURE DIV( @A INT, @B INT)
AS
BEGIN
DECLARE @C FLOAT
BEGIN TRY
SET @C = @A/CAST(@B AS FLOAT)
PRINT ' QUOTIENT OF TWO VALUES IS ' + CAST(@C AS VARCHAR(10))
END TRY
BEGIN CATCH
PRINT ' CANT DIVIDE THE NUMBERS BY ZERO '
END CATCH
END
EXEC DIV 20,20 Output: QUOTIENT OF TWO VALUES IS 1
Q) Create a Procedure called ADDTWO that take two values as input and returns the result to main
program through output arguments.
CREATE PROCEDURE ADDTWO(@A INT, @B INT, @C INT OUTPUT)
AS
BEGIN
SET @C = @A + @B
END
Second Method
CREATE PROCEDURE ERET2 (@ENO INT)
AS
BEGIN
DECLARE @EN VARCHAR(15), @DES VARCHAR(10), @PAY INT, @DNO INT
SELECT @EN = ENAME, @DES = JOB, @PAY = SAL, @DNO = DEPTNO FROM EMP
WHERE EMPNO = @ENO
PRINT
PRINT
PRINT
PRINT
PRINT
@EN
@DES
@PAY
@ENO
@DNO
END
EXEC ERET2 7369
Third Method
CREATE PROCEDURE ERET3 (@ENO INT ,@EN VARCHAR(15) OUTPUT,
@DES VARCHAR(10) OUTPUT, @PAY INT OUTPUT , @DNO INT OUTPUT)
AS
BEGIN
SELECT @EN = ENAME,@DES = JOB, @PAY = SAL, @DNO = DEPTNO FROM EMP
WHERE EMPNO = @ENO
END
DECLARE @EC INT, @N VARCHAR(10), @J VARCHAR(10),@DC INT, @P INT
SET @EC = 7788
EXEC ERET3 @EC,@N OUTPUT, @J OUTPUT, @DC OUTPUT,@P OUTPUT
PRINT @EC
PRINT @N
PRINT @J
PRINT @DC
PRINT @P
Q) Create a Procedure to insert a record in EMP by checking different validations EMPNO, ENAME,
SAL and DEPTNO.
CREATE PROCEDURE INSROW(@ENO INT,@EN VARCHAR(20),@PAY INT, @DNO INT)
AS
BEGIN
SET NOCOUNT ON
DECLARE @I INT, @J INT, @K INT
SELECT @I =COUNT(*) FROM EMP WHERE EMPNO =@ENO
SELECT @J =COUNT(*) FROM DEPT WHERE DEPTNO =@DNO
SELECT @K = MIN(SAL) FROM EMP
IF @I > 0
PRINT 'EMPLOYEE DETAILS ALREADY EXISTS'
ELSE
IF @J = 0
PRINT 'DEPARTMENT IS NOT AVAILABLE'
ELSE
IF @PAY < @K
PRINT 'INVALID SALARY'
ELSE
BEGIN
BEGIN TRAN
INSERT EMP(EMPNO,ENAME,SAL,DEPTNO) VALUES(@ENO,@EN,@PAY,@DNO)
COMMIT
PRINT 'DETAILS INSERTED SUCCESSFULLY'
END
END
EXEC INSROW 7369,'test',5000,50
Q) Create a procedure to update the salary of employee if it is valid increment of more than 500.
CREATE PROCEDURE UPDROW(@ENO INT,@INCR INT)
AS
BEGIN
SET NOCOUNT ON
DECLARE @I INT
SELECT @I = COUNT(*) FROM EMP WHERE EMPNO=@ENO
IF @I = 0
PRINT 'EMPLOYEE DOES NOT EXIST'
ELSE
IF @INCR < 500
PRINT 'INVALID INCREMENT'
ELSE
BEGIN
BEGIN TRAN
UPDATE EMP SET SAL=SAL+@INCR WHERE EMPNO=@ENO
COMMIT
PRINT 'ROW UPDATED SUCCESSFULLY'
END
END
EXEC UPDROW 7788,200
EXEC UPDROW 2001,1200
EXEC UPDROW 7788,1000
-- Invalid Increment
-- Employee Does Not Exist
-- Row Updated Successfully
Q) Create a procedure to delete the rows from a table based on valid deptno.
CREATE PROCEDURE DELROW(@DNO INT)
AS
BEGIN
DECLARE @I INT, @J INT
SELECT @I = COUNT(*) FROM DEPT WHERE DEPTNO = @DNO
IF @I = 0
PRINT ' INVALID DEPARTMENT '
ELSE
BEGIN
SELECT @J = COUNT(*) FROM EMP WHERE DEPTNO = @DNO
IF @J = 0
PRINT 'NO EMPLOYEES EXISTS'
ELSE
BEGIN
BEGIN TRAN
DELETE FROM EMP WHERE DEPTNO =@DNO
PRINT CAST(@J AS VARCHAR(10))+' ROWS DELETED SUCCESSFULLY'
END
END
END
Q) Create a Procedure that performs Bank Transactions provided its implementation on two tables.
CREATE TABLE BANK (ACNO INT,AHN VARCHAR(12),ADDRESS VARCHAR(15),BAL INT)
INSERT BANK VALUES(1001,'HARI','AMRPT',12340)
INSERT
INSERT
INSERT
INSERT
BANK
BANK
BANK
BANK
VALUES(1007,'KIRAN','BHEL',12900)
VALUES(1002,'RAJ','ECIL',15400)
VALUES(1009,'KARAN','AMRPT',23800)
VALUES(1004,'SUNIL','ABIDS',34900)
END
DYNAMIC QUERIES
A query is a block is provided with input at the execution of a program, so that dynamically
changes can be made to the query, and will generate the different output.
Q) Retrieving the data from any table.
CREATE PROC RETTAB(@TN VARCHAR(12))
AS
BEGIN
EXEC ('SELECT * FROM '+@TN )
END
EXEC RETTAB EMP
EXEC RETTAB DEPT
Syntax:
EXEC @VARIABLE=PROC_NAME LIST_OF_ARGS
Example:
CREATE PROCEDURE ATWO(@A INT,@B INT)
AS
BEGIN
DECLARE @C INT
SET @C = @A+@B
RETURN @C
END
DECLARE @X INT,@Y INT,@Z INT
SET @X = 26
SET @Y = 89
EXEC @Z = ATWO @X,@Y
PRINT 'ADDITION IS.......'+CAST(@Z AS VARCHAR(10))
Calling a Function for Execution: User Defined Functions should be called for execution by using
Schema Name preceded to Function Name.
Using SELECT Command -- SELECT DBO.FUNCTION_NAME (ARG_LIST)
Using Anonymous Block -- SET @VAR = DBO.FUNCTION_NAME (ARG_LIST)
Q) Create a function that takes two values as input and returns Product of two values.
CREATE FUNCTION PROD(@A INT,@B INT)
RETURNS INT
AS
BEGIN
DECLARE @C INT
SET @C = @A*@B
RETURN @C
END
SELECT DBO.PROD(12,12)
Q) Create a function called Fact that takes one number as input to a function and returns factorial of
a given number.
CREATE FUNCTION FACT(@N INT)
RETURNS INT
AS
BEGIN
DECLARE @F INT
SET @F = 1
WHILE @N > 0
BEGIN
SET @F = @F * @N
SET @N = @N - 1
END
RETURN @F
END
SELECT DBO.FACT(5)
Q) Create a function that takes empno as an argument and returns employee name.
CREATE FUNCTION FIND_EMP(@ENO INT)
RETURNS VARCHAR(12)
AS
BEGIN
DECLARE @EN VARCHAR(12)
SELECT @EN = ENAME FROM EMP WHERE EMPNO = @ENO
RETURN @EN
END
SELECT DBO.FIND_EMP(1005)
RETURNS TABLE
[ WITH ENCRYPTION ]
AS
RETURN ( SELECT QUERY )
Q) Create a function called EMPRET that retrieves the rows of those employees who are working in
deptno 20.
CREATE FUNCTION EMPRET(@DNO INT)
RETURNS TABLE
AS
RETURN (SELECT * FROM EMP WHERE DEPTNO=@DNO)
SELECT * FROM DBO.EMPRET(20)
Viewing the code related to stored functions: SP_HELPTEXT < FUNCTION_NAME >
Dropping a function: DROP FUNCTION < FUNCTION_NAME >
To display list of user created scalar functions:
SELECT NAME FROM SYSOBJECTS WHERE XTYPE='FN'
TRIGGERS
It is a stored T-SQL program unit in a database as stored block object, which is associated to
a specific table.
Triggers are executed (fired) automatically when invalid operations are performed over a
Trigger Associated table.
Triggers will not take any arguments like procedures and functions.
Triggers will not be executed manually as of Procedures and functions.
Triggering statement will be responsible for the execution of triggers.
ADVANTAGES OF TRIGGERS:
It can audit the transactions
We can provide high security for the data and database objects.
We can provide complex business rules that cant be possible with constraints.
It can have backup of data without the notice of a user.
TYPES OF TRIGGERS:
FOR/AFTER Triggers
DML Triggers
DDL Triggers
INSTEADOF Triggers
LOG ON Triggers
DDL Triggers and LOGON Triggers are introduced in SQL SERVER 2005 to perform administration
related tasks.
Syntax:
CREATE TRIGGER < TRIGGER_NAME >
ON TABLE_NAME/VIEW_NAME/DATABASE
FOR / AFTER / INSTEADOF DML/DDL COMMANDS
AS
BEGIN
[ DECLARATION PART ]
[ TRIGGER CONSTRAINT ]
[ TRIGGER ACTION ]
END
Q) Create a trigger TR2 for INSERT, DELETE Triggering event where trigger should be fired if the
transaction is performed before 10AM and after 5PM.
Q) Create a trigger TR3 for UPDATE triggering event where trigger should be fired to store the
updated and old data into a separated table.
CREATE TABLE EMPB (ENO INT,OSAL INT,NSAL INT,DOT SMALLDATETIME)
CREATE TRIGGER TR3
ON EMP
FOR UPDATE
AS
BEGIN
IF UPDATE(SAL)
INSERT EMPB SELECT I.EMPNO,D.SAL,I.SAL,GETDATE()
FROM INSERTED I,DELETED D
END
Or
CREATE TRIGGER TR3
ON EMP
FOR UPDATE
AS
BEGIN
SET NOCOUNT ON
IF UPDATE(SAL)
INSERT EMPB SELECT A.EMPNO,A.OLD, A.NEW, A.MDATE
FROM (SELECT I.EMPNO, D.SAL OLD, I.SAL NEW, GETDATE() MDATE FROM
INSERTED I, DELETED D WHERE I.EMPNO=D.EMPNO)A
END
Q) Create a trigger TR4 for DELETE triggering event on DEPT table, where trigger should be fired by
deleting the records from EMP table.
CREATE TRIGGER TR4
ON DEPT
FOR DELETE
AS
BEGIN
SET NOCOUNT ON
DELETE FROM EMP WHERE DEPTNO IN(SELECT DEPTNO FROM DELETED)
PRINT CAST(@@ROWCOUNT AS VARCHAR(5))+' Rows Are Deleted'
END
Q) Create a trigger for DDL triggering event that restricts the dropping and altering of a table in a
database.
CREATE TRIGGER TR5
ON DATABASE
FOR DROP_TABLE,ALTER_TABLE
AS
BEGIN
ROLLBACK
RAISERROR('CANT ALTER OR DROP THE TABLES',15,16)
END
INSTEADOF TRIGGERS:
These triggers are used to make the modifications into base table thru a complex view.
By default a complex view is not updatable view (i.e. read only view).
A complex view consists of joins, mathematical expressions, group by clause, distinct
operator.
Q) Create a complex view on EMP table that stores a query for empno, sal and annual salary.
CREATE VIEW V1
AS
SELECT EMPNO,SAL M_SAL,SAL*12 A_SAL FROM EMP
CREATE TRIGGER TR6
ON V1
INSTEAD OF INSERT
AS
BEGIN
INSERT EMP(EMPNO,SAL) SELECT EMPNO,M_SAL FROM INSERTED
END
CURSORS
Deallocating a Cursor
DECLARING A CURSOR:
A cursor is declared by its name associated with a standard SELECT query using DECLARE keyword. It
stores a query for retrieving all rows of a table or retrieving the rows on conditional basis. It also
includes navigation of cursor, type of cursor and type of lock provided on cursor.
Syntax:
DECLARE < CURSOR_NAME > /VAR CURSOR
NAVIGATION_TYPE FORWARD / SCROLL
CURSOR_TYPE STATIC / KEYSET / DYNAMIC / FAST FORWARD
LOCK_TYPE READONLY / SCROLL LOCK / OPTIMISTIC
FOR SELECT QUERY
**By default a cursor is FORWARD only cursor, which supports to access the cursor sequentially.
**If navigation type is provided as SCROLL then can access cursor randomly.
CURSOR TYPES: SQL SERVER will support to create a cursor with any of the following types;
STATIC: When this cursor type is specified it will not make the changes in the cursor when
the table is changed in a database.
KEYSET: When this cursor type is specified it will make the changes in a cursor when the
table is provided with the changes thru DML operations.
DYNAMIC: When this cursor type is specified it also makes the changes in cursor when the
table is changed in a database but performance gets decreases.
FAST FORWARD: When this cursor type is specified it will work similar to KEYSET and
provides fast performance.
LOCKS provided on Cursor:
READ ONLY (Shared Lock): When this lock is provided cursor will not accept any changes
into it.
SCROLL LOCK (Exclusive Lock): It will allow to make modifications but only by one user.
OPTIMISTIC: It will allow to make modifications but only by multiple users.
OPENING A CURSOR:
A cursor which is created when gets opened; the query which is associated gets executed and makes
the data available in a cursor.
Syntax:
CLOSING A CURSOR:
The created cursor when gets closed it does not support to fetch the data from a cursor.
The operations can be performed over that cursor when it gets reopened.
Syntax:
DEALLOCATING A CURSOR:
When the cursor gets deallocated, it removes the complete structure and does not support to
reopen the cursor. If operations are to be performed over a cursor again it should be created.
Syntax:
DEALLOCATE < CURSOR_NAME >
Note:
Any number of cursors can be created in a single program but with unique names.
Global variable @@FETCH_STATUS plays an important role, where it returns Boolean value
i.e. returns 0 if it makes a fetch operation successful over a cursor else returns -1.
Q) Create a cursor which supports to access all the employ records.
DECLARE @EN VARCHAR(12),@DES VARCHAR(14),@DNO INT
DECLARE C1 CURSOR FOR SELECT ENAME,JOB,DEPTNO FROM EMP
OPEN C1
FETCH NEXT FROM C1 INTO @EN,@DES,@DNO
WHILE @@FETCH_STATUS<>-1
BEGIN
PRINT @EN+'
'+@DES+'
'+CAST(@DNO AS VARCHAR(5))
FETCH NEXT FROM C1 INTO @EN,@DES,@DNO
END
CLOSE C1
DEALLOCATE C1
Q) Write a program to create a cursor to store unique department numbers and the other cursor
which stores employees of those departments.
DECLARE @ENO INT,@EN VARCHAR(12),@PAY INT,@DNO INT
DECLARE C1 CURSOR FOR SELECT DISTINCT DEPTNO FROM EMP
OPEN C1
FETCH NEXT FROM C1 INTO @DNO
WHILE @@FETCH_STATUS<>-1
BEGIN
PRINT 'DEPARTMENT........'+CAST(@DNO AS VARCHAR(10))
PRINT 'EMPNO'+'
'+'ENAME'+'
'+'SALARY'
DECLARE C2 CURSOR FOR SELECT EMPNO,ENAME,SAL FROM EMP WHERE DEPTNO=@DNO
OPEN C2
FETCH NEXT FROM C2 INTO @ENO,@EN,@PAY
WHILE @@FETCH_STATUS<>-1
BEGIN
PRINT CAST (@ENO AS VARCHAR(8))+'
'+@EN+'
'+CAST(@PAY AS
VARCHAR(10))
FETCH NEXT FROM C2 INTO @ENO,@EN,@PAY
END
CLOSE C2
DEALLOCATE C2
FETCH NEXT FROM C1 INTO @DNO
END
CLOSE C1
DEALLOCATE C1
Q) Write a program to create SCROLL cursor and access first and last records of EMP table.
DECLARE @ENO INT,@EN VARCHAR(12),@DNO INT
DECLARE C1 CURSOR SCROLL FOR SELECT EMPNO,ENAME,DEPTNO FROM EMP
OPEN C1
FETCH FIRST FROM C1 INTO @ENO,@EN,@DNO
IF @@FETCH_STATUS = 0
BEGIN
PRINT CAST(@ENO AS VARCHAR(10))+'
'+@EN+'
'+CAST(@DNO AS
VARCHAR(12))
END
ELSE
BEGIN
PRINT 'FETCHING FAILED'
END
FETCH LAST FROM C1 INTO @ENO,@EN,@DNO
IF @@FETCH_STATUS=0
BEGIN
PRINT CAST(@ENO AS VARCHAR(10))+'
'+@EN+'
'+CAST(@DNO AS
VARCHAR(12))
END
ELSE
BEGIN
PRINT 'FETCHING FAILED'
END
CLOSE C1
DEALLOCATE C1
Q) Write a program to display required record from a cursor using absolute position.
DECLARE @ENO INT,@EN VARCHAR(12),@DNO INT
DECLARE C1 CURSOR SCROLL FOR SELECT EMPNO,ENAME,DEPTNO FROM EMP
OPEN C1
FETCH ABSOLUTE 3 FROM C1 INTO @ENO,@EN,@DNO
FETCH RELATIVE 2 FROM C1 INTO @ENO,@EN,@DNO
IF @@FETCH_STATUS=0
BEGIN
PRINT CAST(@ENO AS VARCHAR(10))+'
'+@EN+'
'+CAST(@DNO AS
VARCHAR(12))
END
ELSE
BEGIN
PRINT 'FETCHING FAILED'
END
CLOSE C1
DEALLOCATE C1
Note:
When RELATIVE position is specified with +Ve value, it moves the record pointer from
current position to the next record in forward direction.
If -Ve value is specified it moves the record pointer in backward direction from current
position. To the current position relative position is added or subtracted and then takes the
control to the next record.
CLR INTEGRATION
In SQL Server 2005 Database Engine is integrated with CLR (Common Language Runtime
Environment) Database objects can be created with T-SQL Code + DOT NET Language Code.
A Database object created with T-SQL + DOT NET Language Code can be called as CLR Database
Object
}
Step 2: Register the Assembly in SQL Server.
GUI
Step 1: Select the Database
Step 2: Click on Programmability
Step 3: Click on New Assembly
Step 4: Provide the Path of the Compiled C# DLL File
Query Based
CREATE ASSEMBLY MYCLRASSEMBLY FROM 'C:MYCLR\BIN\DEBUG\MYCLR.DLL'
WITH PERMISSION_SET = SAFE
PERMISSION_SET = SAFE / UNSAFE / EXTERNALACCESS
CREATE FUNCTION MYCLRTEST(@I INT, @J INT)
RETURNS INT
AS
EXTERNAL NAME
MYCLRASSEMBLY.CLRCLASS.MYCLRMETHOD
SELECT DBO.MYCLRTEST(27,89)
XML INTEGRATION
In SQL SERVER 2005 XML integration is introduced, which supports to store and access the data in
XML format.
Retrieving the table data in XML Format:
The data in a table which is in the form of rows and columns can be displayed in XML Format using
FOR XML clause of SELECT Statement.
Syntax:
SELECT .....................
FROM TABLE1...........
FOR XML <RAW / AUTO / PATH>, ROOT (NAME)
Data which is represented in XML format can be stored into a table in the form of rows and
columns using OPENXML ()
XML data is converted in table format by creating a temporary memory and it is done by
using a predefined procedure.
EXEC SP_XML_PREPAREDOCUMENT ARG1 OUTPUT, ARG2
Arg1 is a pointer to that temporary memory table which stores the address
of that table. It can be used when that temporary table is to be removed.
Arg2 is a variable which contains the data in XML format.
Use INSERT INTO SELECT query.
To remove that temporary memory table, a predefined procedure is used.
EXEC SP_XML_REMOVEDOCUMENT Arg1
Arg1 is a pointer variable which contains the address of that temporary table.
XML Architecture
XML String
SP_XML_PREPAREDOC
MSXML PARSER (MSSQL.DLL)
Temp Table
Empno
1001
Ename
XYZ
EMP
(Server)
OpenXML ()
Dynamic RowSet
query () : This function will support to retrieve the required attribute information from the XML data
stored in a column. This function is case sensitive, which means it should be used with small letters
only. This function should be used with column name created with XML data type.
SELECT info.query('/EMP/ENAME') FROM EMPT
SELECT info.query('/EMP/SAL') FROM EMPT
exist() : This function will return Boolean value i.e. 1 if the specified element exists else returns with
0.
SELECT info.exist('/EMP/SAL') FROM EMPT
SELECT A.ENAME,A.AVER FROM (SELECT ENAME,AVG(MAR) AVER ,ROW_NUMBER() OVER
(ORDER BY AVG(MAR) DESC) AS AA FROM STU
GROUP BY ENAME) A WHERE A.AA = 2
Exclusive Lock (X): This Lock mode is very straight forward where group of records are taken (Row,
Pages, Extent, Table or Database) and are held exclusively by one transaction. When an insert,
Updated, Delete Statement runs Exclusive Lock will be issued. No other operation of any kind can
use the records hold by X Lock.
Shared Lock: A Shared Lock is applied on records read by a Select Statement. It is designed to allow
concurrent read access from other transactions, but none can modify the held records.
Dead Lock: Dead Lock refers to the condition in which one resource is waiting on the action of a
second while that second is waiting on first; it neither completes any of the two conditions.
Other Locks: SQL also provides other type of locks, but they will not be used for Lock Optimization.
Schema Locks(Sch*) are usually used when a table is being modified such as column being added,
Bulk Update Tools are used for Bulk Update Statements , intent Lock(I*) are used internally by SQL to
increase performance.
SP_LOCK- It will return the list of information about locks that are available in database.
SELECT * FROM SYS.DM_TRAN_LOCKS
Session 2:
SELECT * FROM EMPL WITH (NOLOCK)
ISOLATION LEVELS:
These are classified in four types:
READ COMMITTED
READ UNCOMMITTED
REPEATABLE READ
SERIALIZABLE
**By Default a transaction isolation level is READ COMMITED
Syntax:
SET TRANSACTION ISOLATION LEVEL < LEVEL_TYPE >
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
SELECT * FROM EMPL
The Bulk Copy Program Utility in SQL Server enables Database administrator to import bulk
data into a table or export it from a table into a file.
It also supports several options that define how data will be imported. Where it will be
imported and which data will be loaded.
BCP Commands will allow a user to Bulk Copy Data IN & OUT of SQL Server Tables.
Syntax:
BCP < Source.DB > IN / OUT < Destination file > [Options]
IN Import, OUT Export
Options are Case Sensitive
-T --- Trusted Connection (Windows Authentication)
-S --- Server Name
-U ---User Name
-P --- Password (SQL Server Authentication)
-c --- Character Format
-r --- Row Terminator (CR-LF) Carriage Return Line Field
-E --- Field Terminator (Tab Default)
Exporting data with BCP Utility one of the simplest operations that can perform with BCP is to bulk
copy data out of a SQL Server table into a Text File
Exporting data through Query
BCP SELECT * FROM TESTDB.DBO.EMP QUERYOUT C:\emp.csv c T -t
Importing Data: To Import the data of a file into a table create at SQL Server, BCP will provide an
option called IN
BCP testdb.dbo.emp IN C:\emp.csv c T t -E
BACKUP & RECOVERY OF A DATABASE
Backup of a Database: As system is an electronic device, at any point of time it may come across
with a problem in hardware or at Operating System or at Database, due to which data available in
Database may be lost.
In order to have security for data and Database objects. It is essential that at the End of the Day to
go for a Backup. It creates a backup of Database in to Flat Files. Backup Data later can be transferred
into other external devices for security reasons.
Backup is done in different ways
Full Backup
Differential Backup
Files & File Groups
Transaction Logs
Syntax:
BACKUP DATABASE <DATABASE_NAME>
TO DISK ='FILEPATH.BAK'
Syntax:
BACKUP DATABASE <DATABASE_NAME>
TO DISK ='FILEPATH.BAK'
WITH DIFFERENTIAL
Restore of Database: Database can be restored in a same system or it can be on different system.
Syntax:
RESTORE DATABASE <DATABASE_NAME>
FROM DISK ='FILEPATH.BAK'
DEPLOYMENT OF DATABASE: The process of copying database objects structures with data from
one server to another server is called Deployment of Database.
Method 1:
Copy Backup file (.BAK) to destination system and return it on destination system.
Method 2:
SP_DETACH_DB <DATABASE_NAME>
Method 3:
Creating a Batch and Script Files:
Batch is nothing but set of T-SQL Statements executed under single execution plan.
Every Batch is followed by GO (which makes a separate execution plan) Creation of any
Objects, Setting any property should be presented in different batches.
Script is nothing but collection of batches saved in a file with .SQL extension.
Advantages:
Script files are reusable.
Script files are used to copy database objects from one system to another system.
Generating T-SQL Scripts for existing Database SQL Server provides Script wizard to generate scripts
for existing Database and other objects.
Select Database
Click on Tasks
Click on Generate Scripts - Click Next
Select Database Name - Click Next
Check Scripts all objects in Database - Click Next
Provides Scripting options
Append to File = True (If True Select Existing File)
Script Database Create = True (If True Create Database statement generated)
(If False Create Database Statement will not generated)
Script for server version SQL Server 2005
Click Finish
DATA TRANSFORMATION SERVICE or SQL SERVER INTEGRATION SERVICES
In SQL Server 2000 we have DTS Packages which are based on COM Technology (Component
Object Model)
In SQL Server 2005 it is introduced as SSIS package based on DOTNET Technology.
To import or export Database objects and data from one source to another data source we
can use DTS or SSIS Package.
SSIS Package will support to import or export the database and data between following softwares.
SQL Server ------------ MS Access
SQL Server ------------ Oracle
SQL Server ------------ SQL Server
SQL Server ------------ Text File/XML Files/Excel Files etc
DTS/SSIS communicates with any data source with the help of ODBC or OLEDB or DOTNET data
providers.
Note: SSIS Packages will be stored in MSDB Database.
SQL Native Client: Interface can be used to communicate with only SQL Server
Exporting data from SQL Server to Excel Sheet
Select Database
Right Click on Select Export Data - Click Next
Specify Source Data
Data Source: SQL Native Client
Object Explorer
Click on SQL Server Agent
Step 1:
New Job
Name: INS_REC_JOB
Owner: SA
Category [uncategorized (local)]
Step 2:
Select Steps from select a page window
Click New
Step Name: INS_REC
Type: T-SQL Script
Database: TestDB
Command: INSERT SSA VALUES (GETDATE())
Step 3:
Select Schedule from select a page Window
Click New
Name: SCH_INS_REC
Schedule Type: Recurring
Frequency Occurs: Daily
Click Finish
SQL SERVER REPORTING SERVICES
It is a server based reporting generation software system from Microsoft. It can be used to
prepare and deliver a variety of interactive and printed reports.
It is administrated via a web interface reporting services features a web service interface to
support the development of custom reporting applications.
SSRS Competes with crystal reports and other business intelligence tools and it is included in
express, workgroup, standard and enterprise edition of SQL Server as an install option.
Reporting services was first released in 2004 as an add-on to SQL Server 2000.
The Second version was released as a part of SQL Server 2005 in November 2005.
The latest version was released as part of SQL Server 2008 in August 2008.
Reporting services frame work contains the following components.
Report Server
Report Manager
Report Temporary Database
Report Designer
Report Manager
Report Server
Data Source
Report Server: It compiles and executes client requests connecting to different data sources and
loads the required data in to temporary database.
Report Manager: It will verify security information connections information of client.
Report Temporary Database: To store the reporting data temporary for processing purpose.
Generating Sample Reports:
Starting the Service: Configuration Tools SQL Server Configuration Manager SSRS
Generating the Report
SQL Server 2005 SQL Server Business Intelligence Development Studio
Step 1:
Click on File New Project Report Server Project Wizard
Name: User Report
Location: C:\TestReport
Click Ok & Click Next
Step 2:
New Data Source
Name: Datasource1
Type: MS SQL Server
Connection String
Click on Edit
Server Name: Sys-PC (Server Name of the SQL Server)
Database Name: TempDB (Select the User Defined Database)
Click Test Connection and Click Ok
Click Next
Step 3:
Query String
SELECT ENAME, JOB, SAL FROM EMP
Click Next
Step 4:
Select Report TypeTabular
Click Next
Step 5: