SQL & T-SQL Ver 1 by Shareef PDF
SQL & T-SQL Ver 1 by Shareef PDF
Data Base Management System is defined as collection of Software Program’s 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
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.
**SQL Server 2005(9.0) & 2008 (10.0) Includes both RDBMS & ORDBMS Model.
DR EF CODD has outlined 12 rules often called as CODD’S rules if any Database Software Satisfies 8
or 8.5 rules, it can be considered as pure RDBMS Database.
COMPONENETS OF RDBMS:
SQL SERVER:
SQL SERVER
XML Integration
XML data type is introduced
XML indexes are introduced
FOR XML, OPEN XML
QUERY (), EXIST ()
T-SQL ENHANCEMENTS
DDL Triggers {Used To Perform Administration Related Tasks}
LOGON Triggers.
Structured Exception Handling [TRY, CATCH]
Ranking Functions (Window Functions)
Table Partitioning.
Synonym as Database Object Is Introduced.
Recursive Queries.
NEW TOOLS
SQL SERVER Management Studio
Query Analyzer (Command Based)
Enterprise Manager (GUI Based)
Query Editor (Command Based)
Object Explorer (GUI Based)
CONFIGURATION TOOLS
Service Management
Client Network Utility
Server
T-SQL ENHANCEMENTS: SQL SERVER 2008 introduces several important new T-SQL Programmability
features and enhancements to some existing ones.
TYPES OF DATABASES
System Data Base – Master, Model, MSDN, TempDB
Sample Data Base – 2000(Pubs, Northwind), 2005(Adventures, Adventures DW)
User Defined Data Base – Created by Developers
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)
Syntax:
ALTER DATABASE < DATABASE_NAME >
ADD FILE = < FILE_SPECIFICATIONS >
ADD LOG FILE = < FILE_SPECIFICATIONS >
MODIFY FILE = < FILE_SPECIFICATIONS >
REMOVE FILE= < LOGICAL_NAME >
MODIFY NAME = < NEW_DATABASE_NAME >
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
Command to Use Navigate between Data Base’s
Syntax:
USE < DATABASE_NAME >
USE TESTDB
SP_HELP: It will return list of predefined objects provided by MASTER Data Base to a User Defined
Database.
SP_HELPDB: This predefined Stored Procedure will provide list of database’s available in SQL
SERVER.
Insertion of new rows, modifications to existing rows, removing unwanted rows, collectively known
as DATA MANIPULATION LANGUAGE, It includes INSERT, UPDATE, DELETE and MERGE (introduced in
2008)
This language supports to make a transaction permanent in a database or supports to cancel the
transaction. It includes COMMIT, ROLLBACK, SAVE commands.
This language is used to CREATE, ALTER and DROP Database objects like tables, views, indexes,
synonyms, store procedures, store functions, stored triggers. It includes CREATE, ALTER, TRUNCATE,
DROP Commands.
It is used to give rights on Database objects created by one user to get them access by other users it
also supports to cancel the given rights, It includes GRANT, REVOKE, DENY Commands.
Syntax:
Q) Display ENAME, JOB, SALARY, COMM and DEPTNO of all the EMPLOYEES.
COLUMN ALIAS:
Literals refer to a constraint which means input provided for a query the same is provided in
the output.
A literal can be of numeric, string and date type data
Examples:
Examples:
SELECT 10 + 20 {FOR ADDITION}
SELECT 10 * 20 {FOR MULTIPLICATION}
SELECT 5/2 -- WILL TREAT AS INTEGER
SELECT 5/2.0
SELECT 10 + 5 * 6 M1, (10+5)* 6 M2
WHERE CLAUSE:
This clause will restrict number of rows in the output of a query.
This clause is used to compare the data by making condition in two ways. Filtering
Conditions and Joining Conditions.
At Filtering Condition data given by a user will be compared into a column.
At Joining Condition data of one column will be compared with the data of another column.
At Filtering Condition Comparison to string type data is not case sensitive and it should be
placed in single query.
Comparison to Numeric Type Data is direct or it can also be placed in single quotes.
OPERATORS:
Q) Display ENAME, JOB of those EMPLOYES who are not working as MANAGER
Q) Display ENAME, JOB, and DEPTNO of those EMPLOYEES who are working as CLERK at DEPT NO 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'
Q) Display EMPNO, ENAME, DEPTNO of those EMPLOYEES who are working at 10, 30 Departments.
IN:
This operator compares list of similar type values.
It works like “OR” Logical operator.
It can be used for any number of times.
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:
It is used to compare range of values
Compares range of values including the specified data
It can also be used for any number of times
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.
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 EMPNO, ENAME & MGR of those Employees who don’t have manager to report.
Q) Display EMPNO, ENAME & MGR of those Employees who have managers to report.
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
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
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.
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.
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 User Defined Functions
Or Or
Predefined Functions Stored 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.
SIGN ( NUMBER )
Returns 1 if a number is positive
Returns -1 if a number is negative
Returns 0 if a number is zero
SIN (NUMBER) - By default this function will take input given in radians, hence radians should be
converted to degrees by a standard formula is PI ()/180
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
any digit in decimal points is greater than zero.
STRING FUNCTIONS: This are used to perform different operations on STRING DATA TYPE.
NCHAR(NUMBER)
NCHAR(256) {1-65535 Characters are available}
LEFT(STRING,NUMBER) – Extracts number of characters from left side of a string
LEFT('COMPUTER',3) ---- COM
RIGHT( STRING, NUMBER) – Extracts number of characters from right side of a string
RIGHT('COMPUTER',3)-----TER
SUBSTRING ('COMPUTER',4,3)—PUT
REPLACE ('COMPUTER','UT','IR')
It will search for String2 in String1 and replaces with String3 at all occurrences of String 2 in String1
STUFF('COMPUTER',5,2,'IL') -- COMPILER
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)
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
SELECT GETDATE()
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 DAY(GETDATE())
SELECT MONTH(GETDATE())
SELECT YEAR(GETDATE())
DATEPART can be specified with this format - DD: MM: YY: HH: MI: SS: DW
SELECT DATEADD(DAY,10,GETDATE())
SELECT DATEADD(DD,10,GETDATE())
SELECT DATEADD(MONTH,10,GETDATE())
SELECT DATEADD(MM,10,GETDATE())
SELECT DATEADD(YEARS,10,GETDATE())
SELECT DATEADD(YY,10,GETDATE())
Q) Display all those Employees data that have been hired on Sunday.
Q) Display all those Employees who have been hired in the month of December.
Q) Display all those Employees who have been hired in second half of the week.
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
** 0 stands for Date formats, there are more than 100 Date formats.
** 8 & 108 are particularly assigned for time format
SELECT EMPNO, ENAME, SAL, RANK() OVER(ORDER BY SAL DESC) RNK FROM EMP
SELECT EMPNO, ENAME, SAL, NTILE(4) OVER( ORDER BY EMPNO) NT FROM EMP
**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.
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%
AGGREGATE FUNCTIONS:
This function will process multiple rows at a time and returns one value.
SQL SERVER supports to work with following functions
SUM (EXPRESSION) - finds the sum of values in given expression.
AVG (EXPRESSION) - first finds the sum and then divide with number of values in the
expression.
MAX (EXPRESSION) - finds the maximum value in the given expression.
MIN (EXPRESSION) - finds the minimum value in the given expression.
COUNT (EXPRESSION) --- returns number of values in a expression including duplicates.
COUNT (DISTINCT (EXPRESSION) - returns number of values in an expression excluding
duplicates.
COIUNT (*) - returns number of rows.
COUNT_BIG (EXPRESSION) - returns number of values.
GROUPING (EXPRESSION) - returns zero or one.
Returns ZERO if there is no group
Returns ONE if there is a group data
POINTS TO BE REMEMBERED
Aggregate Function will exclude NULL values.
When a SELECT statement is enclosed with Aggregate Functions, along with them writing
expressions that returns multiple rows is invalid.
Aggregate functions cannot be used in where clause.
In SQL SERVER Aggregate Functions cannot be cascaded.
SP_SPACEUSED EMP
SELECT @@ROWCOUNT
Q) Display DEPTNO, total salary and number of employee’s related to Dept No 20.
ROLLUP:
This operator should be used only at GROUP BY clause.
It will calculate individual totals, group totals, and additional row is generated for grand
totals.
SELECT DEPTNO, SUM(SAL), COUNT(*) FROM EMP GROUP BY DEPTNO WITH ROLLUP
SELECT DEPTNO ,
CASE GROUPING(JOB)
WHEN 0 THEN JOB
WHEN 1 THEN “ALL JOBS” -- Replaces NULLS With The Value
END DEP, SUM(SAL), COUNT(*)
FROM EMP GROUP BY DEPTNO, JOB WITH ROLLUP
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
SUM (CASE DEPTNO WHEN 10 THEN SAL END) “D10”,
SUM (CASE DEPTNO WHEN 20 THEN SAL END) “D20”,
SUM (CASE DEPTNO WHEN 30 THEN SAL END) “D30”
FROM EMP
**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.
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.
INTERSECT
Extracts common rows from two or more result sets.
Eliminates duplicates.
Always arranges in ascending order.
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.
TABLE ALIAS:
Table Alias can be used under any clause.
It is other name provided for a table.
It can be specified with or without as keyword.
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.
Q) Display EMPNO, ENAME, DNAME, LOC, and GRADE of all the Employees.
SELECT ENAME,JOB,SAL,COMM,MGR,E.DEPTNO,D.DNAME,D.LOC,S.GRADE
FROM EMP E, DEPT D, SALGRADE S
WHERE E.DEPTNO = D.DEPTNO
AND E.SAL BETWEEN S.LOSAL AND S.HISAL
AND D.DNAME IN('ACCOUNTING','SALES')
AND E.MGR IS NOT NULL
AND E.COMM IS NULL
AND 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.
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
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'
For SQL SERVER Version 7.00 = 70 should be used
For SQL SERVER Version 2000 = 80 should be used
For SQL SERVER Version 2005 = 90 should be used
SQL Server supports two types of Outer Joins through NON ANSI JOINS
LEFT OUTER JOIN: At this joining concept, Outer Join operator is placed on left side of joining
condition, it will extract matched and unmatched rows from the table which is placed on LEFT side of
Joining condition and substitutes NULL Values for the columns of a table which is on RIGHT side of
the Joining Condition.
Syntax:
SELECT * FROM TABLE1 , TABLE2
WHERE TABLE1.COLUMN1 *= TABLE2.COLUMN2
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:
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
EQUI JOIN
SELF JOIN:
OUTER JOINS
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
**SQL Server supports to write 32 Sub Queries where as in ORACLE it supporsts up to 255 Sub
Queries.
CLASSIFICATION OF SUB QUERIES
Based on Usage
Normal Sub Query
Coorelated Sub Query
Based on Execution
Single Column – Single Row
Single Column – Multiple Rows
Multiple Columns – Single Rows (SQL Server Doesnot supports)
Multiple Columns – Multiple Rows (SQL Server Doesnot supports)
SELECT * FROM TABLE -- MAIN / OUTER QUERY WHERE EXPRESSION OPERATOR (SELECT
FROM TABLE2 WHERE CONDITION)--INNER/SUBQUERY
Q) Display EMPNO, ENAME, JOB, SAL, DEPTNO of that Employee who is being paid by Max Salary.
Q) Display EMPNO, ENAME, JOB, SAL of those Employees whose salary is more than Average Salary
of all Employees.
Q) Display Ename, Job of those Employees who are working on a same job as of TURNER.
Q) Display ENAME,SAL of those Employees whose salary is more than average salary of 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 MAX(SAL) FROM EMP WHERE SAL < ( SELECT MAX(SAL) FROM EMP)
SELECT EMPNO, ENAME, SAL FROM EMP WHERE SAL >= (SELECT MAX(SAL) FROM EMP)
WHERE SAL < (SELECT MAX(SAL) FROM EMP
WHERE SAL < (SELECT MAX(SAL) FROM EMP)))
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'))
**Single Column and Multiple rows
SELECT EMPNO,ENAME,JOB,SAL,DEPTNO
FROM EMP WHERE EMPNO IN (SELECT DISTINCT MGR FROM EMP
WHERE MGR IS NULL)
Q)Dislay ENAME, JOB, SAL, DEPTNO of those Employees whose salary is more than Max Sal of Sales
Department.
SELECT EMPNO,ENAME,JOB,SAL
FROM EMP WHERE SAL > ( SELECT MAX(SAL) FROM EMP
WHERE DEPTNO = (SELECT DEPTNO FROM DEPT
WHERE DNAME = 'SALES'))
Q) Display DEPTNO & Average Salary of those departments whose average salary is more than the
average salary of all Employees.
Syntax:
Q) Write a query to display all thoose Employees whose record position at even numbers
Select as Sub Query can be written as an expression in outer query, where it returns the output of
only one column, Hence it is named as SCALAR SUB QUERY.
Syntax:
SELECT EXPRESSION1, EXPRESSION2.....,(SELECT EXPRESSION .....) [ALIAS
NAME]..... FROM ......
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 those Employee Details who are being paid by minimumm salaries in their respective
Departments.
EXISTS:
It Returns Boolean value ie.. True or False
If Condition at inner query is satisfied than it will written True else written with False
Q) Display DEPTNO, DNAME of those Department’s where atleast one Employe is working.
OR
Syntax :
SELECT * INTO <NEW_TABLE_NAME> FROM < EXISTING_TABLE >
SELECT EMPNO ECODE, ENAME EN, SAL PAY, SAL*12 ASAL, DEPTNO
INTO EMP3 FROM EMP
Syntax:
INSERT [ INTO ] <TABLE_NAME>[ COLUMN_ALIAS ]
VALUES ( LIST_OF_VALUES )
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 ( 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 Salary of SMITH from 800 to 1800.
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 = 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
UPDATE EMP
SET SAL = ( SELECT SAL FROM EMP WHERE ENAME = 'MILLER' )
WHERE ENAME = 'SMITH'
UPDATE EMP
SET SAL = ( SELECT AVG( SAL ) FROM EMP WHERE DEPTNO =20 )
WHERE DEPTNO = 30
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 AVG(SAL) FROM EMP )
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);
TRANSACTION:
It is defined as small logical unit which contains set of operations.
Transaction will works on ACID Properties
A – Atomicity
C – Consistency
I – Isolated
D – Durability
In SQL Server 2005 Transactio will start with a Key Word “ BEGIN TRAN / TRANSACTION “ [
NAME ]
By default set of operations associated to a transaction or temporary.
Syntax :
BEGIN TRANSACTION
< STATEMENTS >
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.
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
When a session contains a transaction it cannot be closed directly , if it is trying closed it confirms for
COMMIT and ROLLBACK of Transactions.
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.
INT 4 BYTES
SMALLINT 2 BYTES [ -32768 to 32767 ]
BIGINT 8 BYTES
TINYINT 1 BYTES [ 0 to 255 ]
DECIMAL (PREC [SCALE])
NUMERIC (PREC [SCALE])
MONEY 8 BYTES
SMALLMONEY 4 BYTES
STRING DATATYPE:
CHAR(SIZE)
Supports to store any type data.
Default size it will take as ONE.
Provides Fixed Memory / Static Memory which leads to wastage of Memory.
It Stores data using “ASCII” Code Conept.
Minimum can be 1 BYTE Maximum of 8000 BYTES.
NCHAR( SIZE )
Supports to store any type data
Default size it will take as ONE
It Stores data using “UNICODE” Concept
Size can be specified Minimum 1 BYTE Maximum 4000 BYTES
VARCHAR( SIZE )
Supports to store any type data
Provides variable Length Memory, Dynamic Memory which results to saving of Memory.
It Stores data using “ASCII” Code Conept
Size can be specified Minimum 1 BYTE Maximum 8000 BYTES
NVARCHAR ( SIZE )
Supports to store any type data
Provides variable Length Memory, Dynamic Memory which results to saving of Memory.
It Stores data using “UNICODE” Code Conept
Size can be specified Minimum 1 BYTE Maximum 8000 BYTES
UNSTURCTURED DATA
BINARY
VARBINARY
IMAGE
XML – Introduced from 2005 to store data in XML Format,
Memory is provided upto 2GB.
Syntax:
CREATE TABLE < TABLE_NAME > (
COLUMN1 COLUMN_DEFINATION,
COLUMN2 COLUMN_DEFINATION,
COLUMN3 COLUMN_DEFINATION.....)
Note:
A DATABASE can contain TWO BLLION Tables.
A Table can have Minimum of One Column and Maximum of 1024 Columns.
No Limit for Rows.
All the DATABASE Objects by default gets associated to predefined Schema i.e “dbo” [
DATABASE OWNER ]
DATABASE Objects should be unique in Schema.
Table Name can be of Minimum One Character and Maximum of 127 Characters.
TYPES OF COLUMNS
Column in SQL Server 2005 are classified in following types.
Points to be remember:
This column is introduced from 2005.
DATA TYPE of computed column is based on Datatype of Those Columns which are used in
Mathematical Expression.
One Computed column cannot be under other Computed Column.
Explicit data is not allowed for computed columns.
A Table can have more than ONE Computed Columns.
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
In order to store explicit values for IDENTITY COLUMN Following SET Command should be
used.
@@IDENTITY - It returns the Last Value stored into IDENTITY COLUMN ( Related to Last Table )
It works at session level.
IDENT_CURRENT - This function returns the last IDENTITY COLUMN value which is stores in a
specific table.
SELECT IDENT_CURRENT( < TABLE_NAME > )
SYS.IDENTITY_COLUMNS - This System Table also supports to get the last value of IDENTITY
COLUMN of any table.
IDENT_INCR ( < TABLE_NAME > ) - It returns the increamented value of the IDENTITY
COLUMN created at table.
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 ( SNO INT IDENTITY, PCODE INT, PNAME VARCHAR(10),
QTY INT, PRICE FLOAT, AMT AS (QTY * PRICE) )
SELECT @@IDENTITY
SELECT SCOPE_IDENTITY()
SELECT IDENT_CURRENT('PRODUCT')
DBCC CHECKIDENT('PRODUCT',RESEED,3)
Q) Create a Table Called STUDENT which contains ROLLNO, NAME, MPC MARKS.
Calculate for total and average marks.
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:
ALTER TABLE < TABLE_NAME >
ADD COLUMN1 COLUMN1_DEFINATION, COLUMN2 COLUMN2_DEFINATION .......
ALTER TABLE EMP ADD SNO INT IDENTITY, EXPR INT, ASAL AS ( SAL *12)
Syntax:
Syntax :
ALTER TABLE < TABLE_NAME > DROP COLUMN COLUMN_NAME .....
SP_RENAME
This predefined procedure will support to rename columns and table
It will suppport to rename only independent columns and tables
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
DELETE TRUNCATE
It is a DML Command It is a DDL Command
Supports to delete the rows on No Conditional deletion is allowed
conditional basis
Slow in Execution Fast in Execution
Supports to invoke Triggers Does not support
Identity Column Value will be in When a table is truncated Identity
continuation even after deleting all Column Values will be resetted to start
rows. 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.
Inserting IMAGE
DATABASE CONSTRAINTS:
Types of Constriants
DOMAIN INTEGRITY CONSTRAINTS -- NOTNULL, CHECK, DEFAULT
ENTITY INTEGRITY CONSTRAINTS -- PRIMARY KEY, UNIQUE
REFERENTIAL INTEGRITY CONSTRAINTS -- FOREIGN KEY
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)
UNIQUE
This Constraint will not allow to store duplicate values but can store only ONE NULL Value.
It Can be used for any number of times
COLUMN LEVEL
CREATE TABLE STUDENT
(RNO INT UNIQUE, SN VARCHAR(10) CONSTRAINT SN_UQ UNIQUE)
TABLE / ENTITY LEVEL
Example:
CREATE TABLE STUDENT(
RNO INT, SNAME VARCHAR(10), CLASS INT, UNIQUE (RNO,CLASS))
COLUMN LEVEL
CREATE TABLE STUDENT ( RNO INT , SNAME VARCHAR(10) PRIMARY KEY (RNO))
Multiple Columns set with One Primary key refers to Composite Primary Key.
It can be created only at table level.
Behaviour of Composite Primary Key that it will allow One column Store Duplicates only
when the corresponding column contains Unique Data.
Composite Primary Key can be created Minimum of 2 and Maximum of 16 Columns
**Difference in Composite Unique Key and Composite Primary Key – Composite Unique Key will
allow NULL Values, Composite Primary Key will not allow NULL Values.
CREATE TABLE RESULT( HTNO INT PRIMARY KEY, MARKS INT, RES VARCHAR(10), RANK
INT, FOREIGN KEY (HTNO) REFERENCES REGISTER(REGNO) ON DELETE CASCADE ON
UPDATE CASCADE)
CREATE TABLE EMPLOYEE( ECODE INT PRIMARY KEY, EN VARCHAR(10), MCODE INT
FOREIGN KEY REFERENCES EMPLOYEE(ECODE))
CREATE TABLE EMP( EID INT PRIMARY KEY, ENAME VARCHAR(10), JOB VARCHAR(10),
DNO INT FOREIGN KEY REFERENCES DEPT(DNO) ON DELETE SET NULL, ON UPDATE SET
NULL)
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.
Advantages:
Minimizes redundancy
Reduces Complexity
Easy Maintanence
Making tables ready to perform JOINS and SUBQUERIES
Tables are said to be in FIRST NORMAL FORM if they satisfy the following rules.
Isolate repeating groups to other table by adding Common Column.
Every Column should be Atomic.
UNNORMALIZED TABLE :
To satisfy the First Normal Form, for the above unnormalized table, the below tables can be created
to normalize the tables.
Customer
CID(Primary Key) Cname Caddr CPhone
Order 1
OrderNo(Primary Key) Ord_Date Items CID(Foregin Key)
Order 2
OrderNo Ord_Date ItemNo ItemName Qty CID(Foreign Key)
Order 3
OrderNo(Primary Key) Ord_Date CID(Foreign Key)
Items
ItemNo ItemName Qty OrderNo(Foreign Key)
THIRD NORMAL FORM
Unnormalized Table:
Workers 1
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.
Syntax:
CREATE SYNONYM < SYNONYM_NAME > FOR < BASE_OBJECT >
Q) Display the List of Synonyms and Base Object Name’s in the DATABASE.
SP_HELP SL
Q) Drop a SYNONYM.
DROP SYNONYM SL
Q) Creating a Schema.
CREATE SCHEMA DBSQLTEST
SP_HELP 'DBSQLTEST.EMP'
CREATING INDEX
Indexing plays a major role when a data is to be searched in bulk records.
When data is searched in a normal table it uses Sequential Search Technique, which always a
time consuming process or it leads to wastage of time.
When data is specified with Sequential Search Technique, first it arranges the data in
ASCENDING Order of that column and then start searching, whenever it finds the value, it
stops the searching process.
Again and again sorting of the data of that column in Ascending order can be overcome by
creating Index.
In Indexing a separate Index structure is created that includes search key value and address
of a record(ROWID) and Index always stores data in Ascending order for permanent.
When search operation is made first it searches for the data in a related index and then from
there it will transfer the control to DATABASE.
In SQL SERVER 2005 a table can be associated with 250 Index’s which One is Clustered Index
and 249 is Non Clustered Index are created
In SQL SERVER 2008 a table can be associated with 1000 Index’s which One is Clustered
Index and 999 is Non Clustered Index are created
**A table can have more than One Index whereas a column can have only one Index.
Syntax:
CREATE [UNIQUE] / [CLUSTERED] / [NON CLUSTERED]
ON [ TABLE_NAME (COLUMN_NAME…..)]
**When index is created on multiple columns it is called as Composite Index.
CLUSTERED INDEX
It will Alter the physical representation of rows in a table.
A table can have only One Clustered Index.
It will always arrange the data of a table in Ascending order
Data pages and Index pages will be stored at one level.
Index should be created for a column where more than one search value is available.
This index will not Alter the physical requirement of rows in a table.
A table can have 249 Non Clustered Index’s.
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.
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.
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 VIEW < VIEW_NAME >
[ WITH ENCRYPTION ]/ [ WITH SCHEMA BINDING ]
AS
SELECT QUERY
[ WITH CHECK OPTION ]
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.
Syntax:
SP_REFRESHVIEW < VIEW_NAME >
Example:
CREATE VIEW V1
AS
SELECT * FROM EMP
Example:
ALTER TABLE EMP ADD EXP INT
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
SELECT DEPTNO, SUM(SAL) TOTSAL FROM EMP GROUP BY DEPTNO
CREATE VIEW V6
AS
SELECT DISTINCT DEPTNO FROM EMP
CREATE VIEW V7
AS
SELECT ENAME, JOB, SAL, SAL*12 FROM EMP
CREATE VIEW V8
AS
SELECT EMPNO, ENAME, JOB, DNAME, LOC FROM EMP, DEPTNO
WHERE EMP.DEPTNO = DEPT.DEPTNO
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
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
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.
SELECT DEPT NO, COUNT (*) FROM EMP GROUP BY DEPTNO
1) Checks the syntax
2) Compiles the query
3) Execution plan is generated
4) Query gets executed
i. Takes the rows of database into buffer
ii. Sorts the data
iii. Creates a group on each deptno
iv. Count function will visit to each group to count the number of employees
v. Displays the output
vi. All these steps are avoided by creating indexed views.
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 V1(I)
AS
(SELECT I = 1
UNION ALL
SELECT I = I + 1 FROM V1 WHERE I <=10)
SELECT I FROM V1
SECURITY
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 can’t
be provided in SQL SERVER 2005, whereas in previous versions blank password for SA can be
created.
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.
To create a login:
USE MASTER
CREATE LOGIN TESTLOGIN WITH PASSWORD = N 'TEST123'
DEFAULT_DATABASE = [TESTDB]
CHECKEXPIRATION = OFF, CHECKPOLICY = OFF
Granting server roles to login
EXEC MASTER.SP_ADDSRVRROLEMEMBER
@LOGINNAME = 'TESTLOGIN', @ROLENAME= 'SYSADMIN'
To Create a User
CREATE USER KUMAR FOR LOGIN SHIVA
USE TESTDB
EXEC SP_ADDROLEMEMBER 'DB_DATAREADER','KUMAR'
EXEC SP_ADDROLEMEMBER 'DB_DATAWRITER','KUMAR'
EXEC SP_ADDROLEMEMBER 'DB_DATADDLADMIN','KUMAR'
EXEC SP_ADDROLEMEMBER 'DB_OWNER','KUMAR'
USE MASTER
ALTER LOGIN TESTLOGIN WITH PASSWORD = 'SAMPLE123'
USE MASTER
DROP LOGIN TESTLOGIN
Syntax
With Grant Option: refers to privileges granted to one user the same privileges that user can grant
to other users
Cascade under revoke refers to canceling the privileges from the main user to whom the owner
gives the privileges and those privileges will be cancelled from other users
Deny: This Data Control Language command is used to deny privileges on objects that are granted /
not granted
USE TESTDB
GRANT SELECT ON EMP TO AHMED
GRANT SELECT, DELETE ON DEPT TO AHMED
GRANT ALL ON PROD1 TO KHAN
GRANT SELECT ON SALGRADE TO AHMED WITH GRANT OPTION
GRANT SELECT ON EMP2 TO PUBLIC
Global Variables
These variables are comes with software (SQL Server).
These variables can’t 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 “@@”.
Syntax:
DECLARE @VARIABLE_NAME DATATYPE [( SIZE )]
** In SQL Server 2008 declaration & Initialization can be carried out simultaneously.
DECLARE @VARIABLE_NAME DATATYPE [( SIZE )] [ =VALUE ]
SET: This command is used to set a value for a variable.
SET @VARIABLE = VALUE/EXPRESSION/FUNCTION
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 < CONDITION > Or IF < CONDITION >
< TRUE STATEMENT > BEGIN
ELSE < STATEMENTS >
< FALSE STATEMENT > END
ELSE
BEGIN
< STATEMENTS >
END
Q) Write a program to check whether a given number has perfect square or not.
Q) Write a program to check whether a given number is ODD or EVEN without using MOD operator.
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.
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.
DECLARE @I INT
SET @I = 1
WHILE @I<=5
BEGIN
PRINT @I
SET @I = @I+1
END
Q) Write a program to display the given string into substrings eliminating special characters.
EXCEPTION HANDLING:
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)
DECLARE @A INT
SET @A = 50
IF @A BETWEEN 100 AND 200
RAISERROR (50000,15,16)
ELSE
PRINT @A
SP_DROPMESSAGE MESSAGE_ID
In SQL Server 2005 exception handling is carried out using Structured Exception, which
supports to write two blocks.
TRY: It is used to monitor all those instructions in which run time errors are expected
CATCH: It is used to catch the thrown exceptions. This block is executed only when exception is
raised.
Syntax:
BEGIN TRY
STATEMENTS
END TRY
BEGIN CATCH
STATEMENTS
END CATCH
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.
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 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
ERROR_MESSAGE(),ERROR_SEVERITY()
END CATCH
SET NOCOUNT ON
DECLARE @A INT,@B INT,@C INT,@N INT,@S INT
SET @A = 5
SET @B = 0
BEGIN TRY
SET @C = @A/@B
PRINT @C
BEGIN TRY
SET @N = -8
SET @S = SQRT(@N)
PRINT @S
END TRY
BEGIN CATCH
PRINT 'CANT FIND THE SQUARE ROOT OF -VE VALUE'
INSERT ERROR_LOG SELECT ERROR_NUMBER(),ERROR_LINE(),
ERROR_MESSAGE(),ERROR_SEVERITY()
END CATCH
PRINT 'WE ARE OUT OF INNER TRY AND CATCH BLOCK'
END TRY
BEGIN CATCH
PRINT 'CANT DIVIDE THE NUMBER BY 0'
INSERT ERROR_LOG SELECT ERROR_NUMBER(),ERROR_LINE(),
ERROR_MESSAGE(),ERROR_SEVERITY()
END CATCH
Working with EXEC (Execute): This Command is used to execute the queries that are stored in
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)
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
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)
Q) Create a Procedure called ADDONE that takes two values as input and finds sum of the values.
Q) Create a Procedure called ADDTWO that take two values as input and returns the result to main
program through output arguments.
Q) Create a Procedure called RET1 that will retrive all the records of EMP Table, This Procedure will
call RET2 to display all the records of DEPT Table and it calls the other Procedure RET3 that will
display all the records of SALGRADE Table.
EXEC RET1 Output: EMP,SALGRADE,DEPT all three tables will get displayed.
** Up to 32 Levels Procedures can be created.
Q) Create a Procedure called ERET1 that takes EMP No as input and displays ENAME, JOB, SAL and
DEPTNO.
Second Method
Third Method
Q) Create a Procedure to insert a record in EMP by checking different validations EMPNO, ENAME,
SAL and DEPTNO.
Q) Create a procedure to update the salary of employee if it is valid increment of more than 500.
Q) Create a procedure to delete the rows from a table based on valid deptno.
Q) Create a Procedure that performs Bank Transactions provided its implementation on two tables.
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.
EXEC CRETAB E1
EXEC CRETAB E2
SQL server will allow a procedure to return 1 value of only numeric type.
Syntax:
CREATE PROC / PROCEDURE PROC_NAME(LIST_OF_ARGS)
[WITH ENCRYPTION]
AS
BEGIN
STATEMENTS
RETURN VARIABLE/VALUE
END
Example:
Scalar Valued Functions: These functions are stored as database objects in a database server and
can return max of 1 value. It takes the input thru arguments and returns 1 value after processing
those arguments.
Syntax:
CREATE FUNCTION FUNC_NAME(LIST_OF_ARGS)
RETURNS DATA_TYPE[(SIZE)]
[WITH ENCRYPTION]
AS
BEGIN
[DECLARATION PART]
[EXECUTION PART]
RETURN VAR/VAL
END
Calling a Function for Execution: User Defined Functions should be called for execution by using
Schema Name preceded to Function Name.
Q) Create a function that takes two values as input and returns Product of two values.
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.
SELECT DBO.FACT(5)
Q) Create a function that takes empno as an argument and returns employee name.
SELECT DBO.FIND_EMP(1005)
Syntax:
CREATE FUNCTION FUNC_NAME(LIST_OF_ARGS)
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.
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'
To display the information about the user created function:
SP_HELP < FUNCTION_NAME >
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 can’t 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
INSERTED:
This table will store the same data which is provided in target table (user defined table).
If a record is inserted into a target table then the same record is available in this magic table.
Data available in this table can be used to perform operations and can be again stored into
the other user
Defined tables
If the record is updated in a target table, new value is stored in this magic table and old
value is transferred to DELETED Table.
DELETED:
This magic table stores the removed rows from a target table.
It also stores the old value when update operation is performed over a target table.
Note:
These tables will store the data for temporary.
These tables can be used individually or both at a time in a single trigger.
Q) Create a trigger TR1 for INSERT, DELETE triggering event where trigger should be fired if the
transactions are performed on SUNDAY.
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.
Q) Create a trigger TR4 for DELETE triggering event on DEPT table, where trigger should be fired by
deleting the records from EMP table.
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
CURSORS
It creates a temporary memory at database server to store result set of a query.
It is created at a system database TempDB
Cursors will create a memory to store multiple rows that are returned by a SELECT query.
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.
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:
FETCH {FIRST/LAST/NEXT/PREV}
ABSOLUTE =POSITION
RELATIVE =POSITION
FROM CURSOR_NAME
INTO TEMPORARY VARIABLES
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.
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.
Q) Write a program to create a cursor to store unique department numbers and the other cursor
which stores employees of those departments.
Q) Write a program to create SCROLL cursor and access first and last records of EMP table.
Q) Write a program to display required record from a cursor using absolute position.
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.
Q) Write a program to delete all tables from a Database.
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
using.system;
using.system.collections.generic;
using.system.text;
using.system.data;
using.system.data.SQLClients;
using.system.data.SQLTypes;
using.microsoft.SQLserver.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
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.
Syntax:
SELECT .....................
FROM TABLE1...........
FOR XML <RAW / AUTO / PATH>, ROOT (NAME)
SELECT EMPNO,ENAME,DEPTNO FROM EMP FOR XML RAW
Output: <row EMPNO="7369" ENAME="SMITH" DEPTNO="20" />
<row EMPNO="7499" ENAME="ALLEN" DEPTNO="30" />
<row EMPNO="7521" ENAME="WARD" DEPTNO="30" />
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.
Temp Table
Empno Ename OpenXML ()
1001 XYZ
EMP
(Server) Dynamic RowSet
exist() : This function will return Boolean value i.e. 1 if the specified element exists else returns with
0.
Transaction is nothing but a logical unit of work, which contains a set of operations.
Transaction & Locks increase the complexity of Database operations, by the guarantee valid data
and query results in multi user applications. This guarantee is expressed with ACID Properties
Atomic: For a transaction to be ATOMIC all the DML Statements INSERT, UPDATE, DELETE must
either call COMMIT or ROLLBACK which means a transaction can’t be left in half done.
Consistency: Means a user should not never see data changes in the mid of transaction. Their view
should return the data as it appears prior to beginning of the transaction or if the transaction is
finished. Then they should see the changed data.
Isolation: it is the heart of Multi User Transaction; it means one transaction should not disrupt
another transaction.
Durability: Implies that the changes made by the transaction are recorded permanently.
Locking mechanism eliminates concurrency problem and Provides consistency. Locks can be applied
at different levels.
LOCK GRANULARITY
The Simplest way to meet the ACID requirements would be for a transaction to create a lock that
seizes the entire Database affected, not letting anyone touch or see any other data until the
transaction completed.
This solution would of course cause a great deal performance problems as other transactions try to
access data. The other extreme would be to lock on a single row. A lock can be issued against a
Database, Table, Extent, Page or a Row. A Page is usually of 8KB Storage Area on the hard drive. An
extent is a group of 8 Pages.
Lock Modes:
SQL Server utilizes several different types of locks & modes. The way in which a lock shares or does
not share records.
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
Syntax:
SET TRANSACTION ISOLATION LEVEL < LEVEL_TYPE >
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
SELECT * FROM EMPL
BULK COPY PROGRAM
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
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
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.
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'
Extended Stored Procedures are used to perform operations in Operating system and Mail Server.
XP_CMDSHELL (Operating System Command) it is used to communicate with Operating System to
execute commands.
Note: to work with this extended procedure it should be enable at configuration tools
SP_CONFIGURE 'CMDSHELL',1
RECONFIGURE
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:
Copy Data Files and Log Files to destination system.
Detach the Database on Source System
SP_DETACH_DB <DATABASE_NAME>
Copy the Database Files to same location on destination system.
Attach these files to a Database on destination system
CREATE DATABASE < DATABASE_NAME >
ON
FILENAME = 'FILE_PATH'
FOR ATTACH
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
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 software’s.
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.
SQL Native Client: Interface can be used to communicate with only SQL Server
Select Database
Right Click on Select Export Data - Click Next
Specify Source Data
Data Source: SQL Native Client
Server Name: Sys-PC
Database: TestDB - Click Next
Specify Destination
Destination: MS EXCEL
File Path: ‘C:\Testexcel.xls ’
Check First row has column names - Click Next
Select Copy data from one or more tables or views - Click Next
Select Tables/ Views whose data is to be copied into Excel sheet - Click Next
Check Execute Immediately
Click Finish
Report Server: It compiles and executes client requests connecting to different data sources and
loads the required data in to temporary database.
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 Type—Tabular
Click Next
Step 5:
Design the Table
Groups – Job
Details – Ename, Sal
Click Next
Step 6:
Choose the Table Style—Slate
Step 7:
Choose the Deployment Location
Report Server: http://localhost/ReportServer
Deployment Folder: Report Test
Click Next
Step 8:
Completing the Wizard
Check the Preview Report
Click Finish