Sei sulla pagina 1di 184

select coalesce(100+null,128-null+1000,12*null,255,2345,9888)

select nullif(100,50*2),nullif(300,30*100),nullif(600,300+300)
1.Write a SQL Query to find first day of month?
ans : SELECT CONVERT(VARCHAR(10),DATEADD(dd,-(DAY(GETDATE())-1),GETDATE()),103)
AS currentdate
2.Write a SQL Query to find Last day of month?
SELECT CONVERT(VARCHAR(10),DATEADD(dd,-(DAY(DATEADD(mm,1,GETDATE()))),DATEADD(mm
,1,GETDATE())),103) AS Date
3.How to find 6th highest salary.
ans :select ename,empno,SAL,deptno from EMP e where 6=(select COUNT(distinct(sal
)) from EMP where SAL>=e.SAL)
4.How to delete the rows which are duplicate (don t delete both duplicate records)
.
ans :delete from EMP1 where %%physloc%% not in
(select min(%%physloc%%) from emp1 group by eno)
5.Find duplicate rows in a table? OR I havea table with one column which has man
y records which are not distinct. I need to find the distinct values from that c
olumn and number of times it s repeated.
ans :select eno from emp group by eno having count(*)>1
6.How to know how many tables contains empno as a column in a database?
ans: select COUNT(name) from sys.columns
where name='empno'
7.Select the details of 3 max salaried employees from employee table.
select ename,empno,SAL,deptno from EMP e where 3>=(select COUNT(distinct(sal)) f
rom EMP where SAL>=e.SAL)
8.how to find max salary from two tables
SELECT MAX(E.Salary) FROM
(SELECT MAX(Sal) Salary FROM emp
UNION
SELECT MAX(Salary) Salary FROM emp1) E

9.Normalized forms
NORMALIZATION:
-------------It is a process of splitting a single table into
2 or more sub tables to avoid redundancy and promote integrity.
OR
It is a process of deciding number of
tables required in a database,
columns in each table and relationships
among the tables is known as Normalization.
Noramlization is used to store the data in simple forms.
Advantages of Normalization:
1. Minimizes Redundancy

2. Reduces Complexity
3. Easy Maintainance
4. Making tables ready to perform joins and sub queries.
A table can be normalized in different ways often called Normal Forms;
Real form
1. First Normal Form (1NF)
2. Second Normal Form (2NF)
3. Third Normal Form (3NF)
Ideal form
4.Fourth normal form
5.Fifth normal form
6.Sixth normal form
7.Seventh normal form
insert/update/delete
delete from invoice where part2=nut
1. First Normal Form (1NF):
Tables are said to be in 1st Normal form
only when it satisfies the following rules;
i. Isolate repeating column groups to other table by adding a common column.
ii. Every Column should be atomic(very small).
2. Second Normal Form (2NF):
---------------------------i. Tables should be in 1NF.
ii. All Non key columns should be made dependent on whole key
but not part of a key.

3. Third Normal Form (3NF)


i. Tables should be in 2NF.
ii. No Transitive Dependency.
SET IMPLICIT_TRANSACTIONS
* Sets implicit transaction mode for the connection.
Syntax
SET IMPLICIT_TRANSACTIONS { ON | OFF }
When ON, SET IMPLICIT_TRANSACTIONS sets the connection into implicit transaction
mode. When OFF, it returns the connection to autocommit transaction mode.
how to check the memory physical memory size?
SELECT * FROM SYS.DM_OS_SYS_INFO

DBCC MEMORYSTATUS
MCTS: SQL Server 2008, Implementation and Maintenance
MCTS (70-432) DBA
MCTS: SQL Server 2008, Database Development
MCTS (70-433)
MCTS: SQL Server 2008, Business Intelligence Development and Maintenance
MCTS (70-448)
http://www.microsoft.com/en-in/download/details.aspx?id=26727
create procedure p1(@deptno int,@dname varchar(20),@loc varchar)
as
begin
if not exists(select * from dept where deptno=@deptno)
insert dept values(@deptno,@dname,@loc)
end
How to convert the decimal number into binary number?
CREATE FUNCTION udf_bin_me (@IncomingNumber int)
RETURNS varchar(200)
as
BEGIN
DECLARE @BinNumber
SET @BinNumber = ''

VARCHAR(200)

WHILE @IncomingNumber <> 0


BEGIN
SET @BinNumber = SUBSTRING('0123456789', (@IncomingNumber % 2) + 1, 1) + @BinNum
ber
SET @IncomingNumber = @IncomingNumber / 2
END
RETURN @BinNumber
END
How to convert the binary into decimal number?
CREATE FUNCTION [dbo].[BinaryToDecimal]
(
@Input varchar(255)
)
RETURNS bigint
AS
BEGIN
DECLARE @Cnt tinyint = 1
DECLARE @Len tinyint = LEN(@Input)
DECLARE @Output bigint = CAST(SUBSTRING(@Input, @Len, 1) AS bigint)
WHILE(@Cnt < @Len) BEGIN
SET @Output = @Output + POWER(CAST(SUBSTRING(@Input, @Len - @Cnt, 1) * 2
AS bigint), @Cnt)
SET @Cnt = @Cnt + 1

END
RETURN @Output
END

How can i update multiple records in a single SQL statement?


UPDATE EMP SET SAL= CASE DEPTNO
WHEN 10 THEN SAL+100
WHEN 20 THEN SAL+200
WHEN 30 THEN SAL+300
END
SQL SERVER 2000:
1.Query Analyser and Enterprise manager are separate.
2.No XML datatype is used.
3.We can create maximum of 65,535 databases.
4.Nil
5.Nil
6.Nil
7.Nil
8.Nil
9.Nil
10.Nil
11.Nil
12.Nil
13.cant compress the tables and indexes.
14.Datetime datatype is used for both date and time.
15.No varchar(max) or varbinary(max) is available.
16.No table datatype is included.
17.No SSIS is included.
18.CMS is not available.
19.PBM is not available.
SQL SERVER 2005:
1.Both are combined as SSMS(Sql Server management Studio).
2.XML datatype is introduced.
3.We can create 2(pow(20))-1 databases.
4.Exception Handling
5.Varchar(Max) data type
6.DDL Triggers
7.DataBase Mirroring (SQL DBA)
8.RowNumber function for paging
9.Table fragmentation
10.Full Text Search
11.Bulk Copy Insert
12.Cant encrypt
13.Can Compress tables and indexes.(Introduced in 2005 SP2)
14.Datetime is used for both date and time.
15.Varchar(max) and varbinary(max) is used.
16.table datatype is included.
17.SSIS is started using.
18.CMS is not available.
19.PBM is not available.

SQL SERVER 2008:


1.Both are combined as SSMS(Sql Server management Studio).
2.XML datatype is used.
3.We can create 2(pow(20))-1 databases.
4.Exception Handling
5.Varchar(Max) data type
6.DDL Triggers
7.DataBase Mirroring
8.RowNumber function for paging
9.Table fragmentation
10.Full Text Search
11.Bulk Copy Update
12.Can encrypt the entire database introduced in 2008.
13.Can compress tables and indexes.
14.Date and time are seperately used for date and time datatype,geospatial and t
imestamp with internal timezone
is used.
15.Varchar(max) and varbinary(max) is used.
16.Table datatype introduced.
17.SSIS avails in this version.
18.Central Management Server(CMS) is Introduced.
19.Policy based management(PBM) server is Introduced.
Installation Guide:
http://www.sqlserverclub.com/pdfs/how-to-install-sql-server-2008-a-step-by-stepguide.pdf
microsoft corporation:
1.operating system
Windows
2.application tools
vb.net
c#.net
asp.net
3.database server
Sqlserver,Msaccess.
4.datawarehousing tools
MS-BI (
ssis
ssrs
ssas
5.ERP(Enterprise resource planning)
Microsoft Dynamics
EMPLOYEE

ENAME
XXX
YYY
ZZZ
MMM

EMPNO
1001
1002
1003
1004

SALARY
2000 RECORD
3000
4000
5000

FIELD EACH COLUMN IN A TABLE IS CALLED FIELD OR


COLLECTION OF RELATED DATA IS CALLED FILED OR ATTRIBUTES
RECORDS : EACH ROW IN TABLE IS CALLED RECORDS OR
COLLECTION OF RELATED FIELDS IS CALLED RECORDS OR TUPLES.
TABLE : COLLECTION OF RELATED RECORDS IS CALLED TABLES.
DATABASE : COLLECTION OF RELATED TABLE IS CALLED DATABASES.
DBMS: IT IS A SOFTWARE.IT IS USED TO INSERT THE RECORDS,
UPDATE THE RECORDS AND DELETE THE RECORDS IN A SINGLE TABLE.
RDBMS: IT IS A SOFTWARE IS USED TO INSERT THE RECORDS,UPDATE THE RECORDS,DELETE
THE RECORDS IN MULTIPLE TABLES.
OORDBMS: OBJECT ORIENTED RDBMS
BASIC CONCEPT OF OOPS
1.OBJECT
2.CLASS
3.INHERITANCE
4.POLYMORPHISM
5.DATA ABSTRACTION
6.DATA ENCAPSULATION
7.DYNAMIC BINDING
8.MESSAGE PASSING
SQL : STRCTURED QUERY LANGAUGE. (IBM PRODUCT)
SEQEL : STRUCTURED ENGLISH QUERY LANGUAGE
5 SUB LANGUAGE:
DDL
DML
DCL
TCL
DQL

:
:
:
:
:

DATA DEFINIATION LANGUAGE ( CREATE,ALTER,TRUNCATE,DROP)


DATA MANIPULATION LANGUAGE( INSERT,UPDATE,DELETE)
DATA CONTROL LANGUAGE ( GRANT,REVOKE)
TRANSACTION CONTROL LANGUAGE( COMMIT,ROLLBACK,SAVETRANSACTION)
DATA QUERY LANGUAGE ( SELECT)

DATABASE NAME : PEERS


PHYSICALY FILES:
1.PEERS.MDF (MASTER DATA FILE)
2.PEERS_LOG.LDF(LOG DATA FILE)

Candidate Key(Primary Key) is a Key which Maintains the Row

Unique .Can be defined based on the Entity


candidate key:- is a column in a table which has the
ability to become a primary key.
ex:
deptno and dname

Alternate Key or Unique Key is similar to PK ,except it


accepts null Values .So that the records can still be
entered submitting null values to this attribute
Alternate Key:- Any of the candidate keys that is not part
of the primary key is called an alternate key.

Composite key:- A primary key that consistsof two or more


attributes is known as composite key
A composite Key can be either Primay or Unique Key
More then One Key columns are said to be composite keys
COMPOSITE PRIMARY KEY:
Multiple columns set with single primary key constraint refers to Compos
ite Primary Key.
Composite Primary Key can be created only at columnlevel or Table Level.
Behaviour of Composite Primary Key is that it will allow to store duplic
ates at 1 column only when corresponding column contains unique data. It will no
t allow to store null values.
Composite primary key can be set to Min 2 Cols and Max of 16 Columns.
Installation Guide:
http://www.sqlserverclub.com/pdfs/how-to-install-sql-server-2008-a-step-by-stepguide.pdf
openrow set

SELECT * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0', 'DataSource=c:\book1.xls;Ext


ended Properties=Excel 8.0', Sheet1$)

TRANSACTION:-Collection of operation that forms a single logical unit of work ar


e called Transactions.

INTRODUCTION TO SQL SERVER


1.MS SQL Server is a fully web enable database.
2.SQL Server has strong support for XML, and HTTP, which are

two of th

e main infrastructure technologies for Dot Net.


Rdbms software
1.oracle -1979 - CUI,MORE SECURITY,HIGH PRICE RDBMS,PLATFORM INDEPENDENT.
1.SQL AND PLSQL
2.sqlserver
1.SQL AND TSQL(TRANSACT SQL)
1
3.mysql
SQL
4.sybase
5.ingres
6.teradata
7.db2

Some of the advantages of SQL client are:


1.Supports multiple hardware platforms
2. Supports multiple software platforms
SQL SERVER:
1.IT WAS Introduced in 1989.
2.it is GUI
3.IT IS LESS secured
4.it is low price RDBMS
5.sql server can be installed on windows os.
sqlserver clients can be on different platforms.
version of the
year
1989
1993 - 1995
1995 - 1997
1998
2000
2005
2008

sqlserver
name of the s/w
sqlserver 1.0
sqlserver 4.0
sqlserver 4.5
sqlserver6.0
sqlserver 6.5
sqlserver 7.0
sqlserver(2000) 8.0
sqlserver(2005) 9.0
sqlserver(2008) 10.0

System Database in SQL Server


Master Database
1.The Master database is the heart of SQL Server.
2, It basically records all the system level information.
3,Every instance of SQL Server will have an independent Master database;
4. The system and user databases related information such as name and location f
or user and system database are captured in Master database.

5.The Master database basically consists of two physical files, namely master.md
f (data file) and mastlog.ldf (log file). (DML Transaction command (insert,upd
ate,delete))
6.The database id is 1
Model Database
1.The Model database is basically used as a template when creating databases in
SQL Server.
2.The database id is 3
MSDB Database
1.SQL Server Agent uses MSDB database to store information related to the config
uration of SQL Server Agent Jobs, Job schedules, Alerts, Operators etc.
2. MSDB also stores information related to configuration of Service Broker, Log
Shipping, database backups and restore information, Maintenance Plan Configurati
on, Configuration of Database Mail.
3. This database also stores SSIS packages created in SQL Server 2005 & 2008.
4. The database id is 4.
TempDB Database
1.The TempDB is the only database in SQL Server which is recreated every time wh
en SQL Server restarts.
2.It basically stores all the temporary objects such as temporary tables, global
temporary tables, temporary stored procedures, cursors, table variables,Trigger
s.
3.The database id is 2.
Resource Database
1.The Resource database is a read only, hidden system database that contains all
the SQL Server system objects such as sys.objects which are physically availabl
e only in the Resource database, even though they logically appear in the SYS sc
hema of every database.
2, Resource Database does not contain any user data or any user metadata.
3. The database id is 32767.
SQLSERVER CONSISTS OF 2 TOPICS:
1.SQL
2.
- TRANSACT SQL

start-->run-->sqlwb(sql work bench) -->ok (sqlserver 2005)


start-->run->ssms --> ok(sqlserver 2008)
connect to server:
sqlserver provides 2 ways of connecting to server:
1.Windows Authentication
It connects to server with a support of login and password of
windows operating system. it is trusted connection.
2.Sqlserver Authentication
it connects to server with personal login and password of sqlserver.
sqlserver 2005 by default provides a login called sa to which we need to
set a password at installation process.
in sqlserver 2000 password is optional where as 2005 it is mandatory.
Example of RDBMS:
-SQL SERVER
-ORACLE
-MYSQL
-SYBASE
-INGNES
-INFORMIX
-TERADATA
-DB2
Difference between mysql and sqlserver
MySQL does not support Triggers, SQL Server does.
MySQL does not support User Defined Functions, SQL Server does.
MySQL does not have Cursor Support, SQL Server does.
MySQL does not support Stored Procedures, SQL Server does.
MySQL does not have FULL JOIN capabilities, SQL Server does.
MySQL has limited Import/Export capabilities, SQL Server has full support for Im
port/Export.
MySQL has limited Transaction Support while SQL Server offers full Transaction S
upport.
Query Execution Steps:
select * from emp
1.Compilation of the query
2.Identify the tablename
3.Lock the table.
4.QEP are created.
5.Query are executed
6.Results are displayed
7.Release the locks
sqlserver datatypes
char(20) - alphabets (a-z) fixedlength
varchar(20) -alphabets variant length char

nchar(20)
nvarchar(20)
tinyint -1 bytes
smallint -2 bytes
int - 4 bytes
bigint -8 bytes
float -4 bytes
decimal - 8 bytes
sql_variant (It allows any type of data ex strings,numbers....etc).
currency
smallmoney - 4
money - 8
date and time
smalldatetime - 4byte (01-01-1900 to 31-12-9999)
datetime - 8 byte (01-01-1753 to 31-12-9999)
xml datatype
-xml file
-textfile

create table <tablename>(fieldname1 fieldtype1,fieldname2 fieldtype2...)


create table employee(ename varchar(20),eno int,salary money)
syntax:
insert into <tablename> values('value1',value2,value3)
insert into employee values('aaa',101,2000)
insert into employee values('bbb',102,3000)
insert into employee values('ccc',103,4000)
select <fieldname1>,fieldname2... from <tablename> where <condition>
select ename,eno,salary from emp
select * from emp
select ename,eno from emp
SQLSERVER CONSISTS OF 2 TOPICS:
1.SQL
2.TSQL - TRANSACT SQL
start-->run-->sqlwb(sql work bench) -->ok
connect to server:
sqlserver provides 2 ways of connecting to server:
1.Windows Authentication
It connects to server with a support of login and password of
windows operating system. it is trusted connection.

2.Sqlserver Authentication
it connects to server with personal login and password of sqlserver.
sqlserver 2005 by default provides a login called sa to which we need to
set a password at installation process.
in sqlserver 2000 password is optional where as 2005 it is mandatory.
Example of RDBMS:
-SQL SERVER
-ORACLE
-MYSQL
-SYBASE
-INGRES
-INFORMIX
-TERADATA
-DB2
Difference between mysql and sqlserver
MySQL does not support Triggers, SQL Server does.
MySQL does not support User Defined Functions, SQL Server does.
MySQL does not have Cursor Support, SQL Server does.
MySQL does not support Stored Procedures, SQL Server does.
MySQL does not have FULL JOIN capabilities, SQL Server does.
MySQL has limited Import/Export capabilities, SQL Server has full support for Im
port/Export.
MySQL has limited Transaction Support while SQL Server offers full Transaction S
upport.
SQLSERVER MANAGEMENT STUDIO:
1.QUERY EDITOR
2.OBJECT EXPLORER
SQL COMMANDS:
1.DDL - CREATE,ALTER,TRUNCATE,DROP
2.DML- INSERT,UPDATE,DELETE
3.DCL- GRANT,REVOKE
4.TCL - COMMIT,ROLLBACK,SAVE TRANSACTION
5.DQL - SELECT
DDL
1.CREATE:
CREATE TABLE <TABLENAME>(FIELDNAME1 FILEDTYPE1,FIELDNAME2 FIELDTYPE2.......)
ALTER TABLE <TABLENAME> ADD/MODIFY(FIELDNAME1 FIELDTYPE1)
CREATE TABLE STUDENT(NAME VARCHAR(20), ROLLNO INT,SALARY MONEY)
CHAR (40)
RAJA
VARCHAR(20)
RAJA
RAJA
INSERT INTO <TABLENAME> VALUES('VALUE1',VALUE2,VALUE3......)

INSERT INTO STUDENT VALUES('AAA',101,20000)


INSERT INTO STUDENT VALUES('BBB',102,30000)
INSERT INTO STUDENT VALUES('CCC',103,40000)
SELECT <FILEDNAME> FROM <TABLENAME> WHERE <CONDITION>
SELECT * FROM STUDENT WHERE MARK>=200

CHAR -ALPHABET -ASCII(0-255 BYTES)


NCHAR - UNICODE(0-65535 BYTES)
VARCHAR -ASCII
NVARCHAR -UNICODE (IT IS CHAR.OF DIFF.LANGUAGE)
CHAR /VARCHAR - 1 BYTE OCCUPIES 1 CHAR
NCHAR/NVARCHAR - 2 BYTES OCCUPIES 1 CHAR
DCL COMMANDS:
GRANT - gives a user permission to perform certain tasks on database objects
DENY - denies any access to a user to perform certain tasks on database objects
REVOKE - removes a grant or deny permission from a user on certain database obje
cts

SQLSERVER OPERATORS:
1.ARITHMETICAL OPERATORS:
+ ADD
- SUB
* MULT
/ DIV
% MODULUS
RELATIONAL OPERATORS:
< > <= >= = <> OR !=
LOGICAL OPERATORS:
AND OR NOT
SPECIAL OPERATORS:
IN ,NOT IN ,BETWEEN ,NOT BETWEEN , LIKE NOT LIKE,
IS NULL,IS NOT NULL
SET OPERTORS:
UNION,UNIONALL INTERSECT,EXCEPT
INSERT
INSERT
INSERT
INSERT
SELECT
SELECT
SELECT
SELECT
SELECT
SELECT

INTO STUDENT VALUES('AAA',101,200)


INTO STUDENT VALUES('BBB',102,300)
INTO STUDENT VALUES('CCC',103,400)
INTO STUDENT VALUES('DDD',104,500)
* FROM STUDENT WHERE MARK>=300
* FROM STUDENT WHERE MARK IN(300,500)
* FROM STUDENT WHERE MARK NOT IN(300,500)
* FROM STUDENT
* FROM STUDENT WHERE MARK BETWEEN 200 AND 400
* FROM STUDENT WHERE MARK NOT BETWEEN 200 AND 400

SELECT * FROM STUDENT WHERE NAME LIKE 'A%'


SELECT * FROM STUDENT WHERE NAME LIKE '%D'
LIKE OPERATORS:
IT IS USED TO COMPARE COLUMN VALUE WITH CHARACTER PATTERNS.
SYNTAX: LIKE 'PATTERN'
NOT LIKE 'PATTERN'
WILD CARD PATTERNS:
% MULTI CHARACTER
_ SINGLE CHARACTER
[ ] - RANGE OF CHARACTER
DISPLAY EMPLOYEES RECORDS NAME STARTS BETWEEN A AND P.
SELECT * FROM EMP WHERE ENAME LIKE '[A-P]%'
WHOSE NAME DOESNOT START WITH A AND P.
SELECT * FROM EMP WHERE ENAME LIKE '[^A-P]%' OR NOT LIKE '[A-P]'
DISPLAY EMPLOYEE RECORDS NAMES STARTS WITH A OR B OR S OR T
SELECT * FROM EMP WHERE ENAME LIKE '[ABST]%'
UPDATE <TABLENAME> SET <COLNAME>=VALUE WHERE <CONDITION>

DELETE
DELETE
SELECT
DELETE
SELECT

FROM <TABLENAME> WHERE <CONDITION>


FROM STUDENT WHERE ROLLNO=101
* FROM STUDENT
FROM STUDENT WHERE ROLLNO=102
* FROM STUDENT

TRUNCATE TABLE <TABLENAME>


TRUNCATE TABLE STUDENT
SELECT * FROM STUDENT
DROP TABLE <TABLENAME>
DROP TABLE STUDENT
ALTER TABLE EMPLOYEE ADD DEDUCTION MONEY
SELECT * FROM EMPLOYEE
SP_HELP 'EMPLOYEE'
ALTER TABLE EMPLOYEE ALTER COLUMN ENAME VARCHAR(25)
ALTER TABLE EMPLOYEE DROP COLUMN DEDUCTION
SELECT * FROM EMPLOYEE
ALTER TABLE EMPLOYEE DROP COLUMN ALLOWANCE
TRUNCATE COMMAND:
IT IS USED TO DELETE ALL RECORDS.

DROP COMMAND:
IT IS USED TO DELETE WHOLE TABLE.
TRUNCATE TABLE EMPLOYEE
SELECT * FROM EMPLOYEE
DROP TABLE EMPLOYEE
SELECT * FROM EMPLOYEE
Differences between Delete and Truncate Commands;
What is difference between DELETE and TRUNCATE commands?
Delete command removes the rows from a table based on the condition that we prov
ide with a WHERE clause.
Truncate will actually remove all the rows from a table and there will be no dat
a in the table after we run the truncate command.
TRUNCATE:
TRUNCATE is faster and uses fewer system and transaction log resources than DELE
TE.
TRUNCATE removes the data by deallocating the data pages used to store the table
's data, and only the page deallocations are recorded in the transaction log.
TRUNCATE removes all rows from a table, but the table structure, its columns, co
nstraints, indexes and so on, remains. The counter used by an identity for new r
ows is reset to the seed for the column.
You cannot use TRUNCATE TABLE on a table referenced by a FOREIGN KEY constraint.
Because TRUNCATE TABLE is not logged, it cannot activate a trigger.
TRUNCATE cannot be rolled back.
TRUNCATE is DDL Command.
TRUNCATE Resets identity of the table
DELETE:
DELETE removes rows one at a time and records an entry in the transaction log fo
r each deleted row.
If you want to retain the identity counter, use
DELETE instead. If you want to remove table definition and its data, use the DRO
P TABLE statement.
DELETE Can be used with or without a WHERE clause
DELETE Activates Triggers.
DELETE can be rolled back.
DELETE is DML Command.
DELETE does not reset identity of the table.

DML:
SELECT
INSERT
UPDATE
DELETE
SELECT * FROM <TABLENAME>
INSERT INTO <TABLENAME> VALUES('VALUE1',VALUE2...);
UPDATE <TABLENAME> SET <COLNAME>=VALUE WHERE < CONDITION>;
DELETE FROM <TABLENAME> WHERE <CONDITION>;
UPDATE STUDENT SET MARK=250 WHERE ROLLNO=101
SELECT * FROM STUDENT
UPDATE
UPDATE
SELECT
DELETE
SELECT

STUDENT SET MARK=350 WHERE ROLLNO=102


STUDENT SET TOTAL=250 WHERE ROLLNO=101
* FROM STUDENT
FROM STUDENT WHERE ROLLNO=104
* FROM STUDENT

UPDATE STUDENT SET MARK=250 WHERE ROLLNO=101


SELECT * FROM STUDENT
UPDATE
UPDATE
SELECT
DELETE
SELECT

STUDENT SET MARK=350 WHERE ROLLNO=102


STUDENT SET TOTAL=250 WHERE ROLLNO=101
* FROM STUDENT
FROM STUDENT WHERE ROLLNO=104
* FROM STUDENT

update student set stot=s1+s2+s3, savg=(s1+s2+s3)/3


update by using case statement:
update emp set sres=
case
when savg>=90 then 'distinction'
when savg>=70 then 'first class'
when savg>=55 then 'second class'
when savg>=35 then 'third class'
else 'Fail'
end
Computed columns:
1.Computed columns are the columns for which value is automatically computed dur
ing insert.
2.To make a column as computer column, we have to specify a formula for that col
umn based on which value will be computed for that
column by using the keyword "AS".
3.It is not possible to specify datatype for computed columns.
create table student(sname varchar(20),sno int,s1 int,s2 int,s3 int,stot as s1+

S2+s3,
savg as (s1+s2+s3)/3,
sres as case
when (s1+s2+s3)/3 >=90
when (s1+s2+s3)/3 >=70
when (s1+s2+s3)/3 >=50
when (s1+s2+s3)/3 >=35
else 'fail'
end

then
then
then
then

'Distinction'
'first class'
'second class'
'third class'

Inserting rows from one table to another table:


syntax:
insert into <tablename> select * from <tablename>;
insert into emp1 select * from emp
select * into newtablename from oldtablename
Merge (DML)
* it is used to compare the 2 table contents and makes them equal.
* it supports only update and insert.
* sqlserver introduced MERGE command in 2008.
* It is also known as UPSERT (Insert and Update statement together).
* Using the MERGE command, we can write insert and update statement using single
SQL statement rather than coding two separate sets of SQLs, one for insert and
one for update.
* It contains two clauses, WHEN MATCHED THEN (used for updating existing record
s) and WHEN NOT MATCHED THEN (used for inserting new records).
Examples:
merge
into emp1 t
using emp e
on (t.empno=e.empno)
when matched then
update set t.sal=e.sal,
t.comm=e.comm,
t.deptno=e.deptno,
t.job=e.job,
t.mgr=e.mgr
when not matched then
insert values(e.empno,e.ename,e.job,
e.mgr,e.hiredate,e.sal,e.comm,e.deptno);

SQLSERVER

(Structured Query Language)


When SQL was introduced it was called by a name "SQUARE" (Specifications of Quer
y As Relational Expressions).
In the year 1973, SQUARE was modified and was released with a name SEQUEL. (Stru
ctured English Query Language),later was renamed to SQL.
SQL is a language which is used to communicate with database server.
SQL is a product of IBM, which later used by different companies and released SQ
L according to their standards.
SQL is called common database language, since it can get understand by any RDBM
S.
SQL is called command based language.
SQL is called non procedural language.
SQL consists of following Sub languages;
1. Data Definition Language (DDL):
This language will support to create, modify and remove database objects
like Tables, Views, Synonyms, Procedures, Functions,.........etc
It includes the following commands;
CREATE,ALTER,TRUNCATE,DROP
2. Data Manipulation Language (DML):
Insertion of new rows, modification of existing rows, and removing unwan
ted rows collectively known as DML.
It includes the following commands;
INSERT,UPDATE,DELETE,MERGE(introduced in SQL Server 2008)
3. Transaction Control Language (TCL):
today!
TRANSACTION:-Collection of operation that forms a single logical unit of work ar
e called Transactions.
In other words, Transactions are units or sequences of work accomplished in logi
cal order, whether in a manual fashion by a user or automatically by some sort o
f a database program. In a relational database using SQL, transactions are accom
plished using the DML commands
This language will support to make the transactions permanent in a datab
ase or supports to cancel the transactions.
It includes the following commands;
COMMIT,ROLLBACK,SAVE TRAN
4. Data Query or Retrieval Language (DQL or DRL):
This language will support to retrieve the data in different ways;
It includes SELECT command.
5. Data Control Language (DCL):
It supports to give rights on database objects created at one user to ge

t them access by other user. It also supports to cancel those given rights.
It includes the following commands;
GRANT, REVOKE, DENY
Representation of Data:
Data in SQL Server is represented with the help of following 3 key point
s;
1. Data name
2. Data type
3. Data size
1. Data name : It is often called as Column name or Identifier or Field or Attri
bute.
It is the one, which stores data.
Rules to be followed before using a Column name;
i. Column name can be of min 1 char and max of 127 chars.
ii. Column name should not contain keywords. In order to use keywords as columns
then it should be enclosed in Square brackets.
iii. Column name should not be enclosed with blank spaces. In order to enclose b
lank spaces then it should be placed in Square brackets.
iv. Column names in a table should always be unique.
v. Column names should not contain special characters.
Data type and Data Size:
Data type explains regarding type of data to be stored in a data name.
Integers:
BIGINT
INT
SMALLINT
TINYINT

8
4
2
1

Bytes
Bytes
Bytes (-32768 to 32767)
Byte (0 to 255)

Real Numbers:
FLOAT
DECIMAL

Varies
Varies

MONEY
SMALLMONEY

8 Bytes
4 Bytes

Date time:
DATETIME
SMALLDATETIME

8 Bytes (1st Jan 1753 - 31st Dec 9999)


4 Bytes (1st Jan 1900 - 6th Jun 2079)

CHAR :
It stores any type data.
It provides fixed memory or static memory, which results to wastage of m
emory.
Size can be specified with min of 1 character and maximum of 8000 charac
ters.
It stores the data using ASCII
VARCHAR :

It stores any type data.


It provides variable length memory or Dynamic memory, which results to s
aving of memory.
Size can be specified with min of 1 character and maximum of 8000 charac
ters.
It stores the data using ASCII code.
NCHAR :
It stores any type data.
It provides fixed memory or static memory, which results to wastage of m
emory.
Size can be specified with min of 1 character and maximum of 4000 charac
ters.
It stores the data using UNICODE code.
NVARCHAR :
It stores any type data.
It provides fixed memory or static memory, which results to wastage of m
emory.
Size can be specified with min of 1 character and maximum of 4000 charac
ters.
It stores the data using UNICODE code.
Some of the Advantages of SQL Server are:
1. Reliable
2. Fault tolerant
3. Centralized control
4. Concurrent
5. Sophisticated locking
TABLE : EMPLOYEE
ENAME
AAA
BBB
CCC

ENO
101
102
103

SALARY
20000 RECORD
30000
40000

FIELD :Each column in a table is called field. or collection related data is


called field.
Record : Each row in a table is called record. or collection of related field
is called record.
Table : collection of related records is called table.
database : collection of related table is called database.
DBMS : database management system
RDBMS : relational database management system.
ORDBMS : object oriented relational database managerment system.
oops concept
object
class
inheritance
polymorphism
dataabstraction
data encapsulation

dynamic binding
message passing.
SQL :
DDL: DATA DEFINATION LANGUAGE
DML: DATA MANIPULATION LANGUAGE
DCL : DATA CONTROL LANGUAGE
TCL : TRANSACTION CONTROL LANGUAGE
DQL : DATA QUERY LANGUAGE
DDL
DML
DCL
TCL
DQL

:
:
:
:
:

CREATE,ALTER,TRUNCATE,DROP
INSERT,UPDATE,DELETE
GRANT,REVOKE
COMMIT,ROLLBACK AND SAVEPOINT
SELECT

Microsoft SQL Server 2005 is a comprehensive, integrated


data management and analysis software that enables organizations
to reliably manage mission-critical information and confidently
run today s increasingly complex business applications.
SQL Server 2005 allows companies to gain greater insight from their
business information and achieve faster results for a competitive
advantage.
Microsoft Corp. today announced the release to
manufacturing of Microsoft SQL Server 2008,
the new version of the company s acclaimed data management
and business intelligence platform.
This version of SQL Server provides powerful
new capabilities such as support for policy-based management,
auditing, large-scale data warehousing, and advanced
reporting and analysis services.
SQL Server 2008 provides the trusted, productive and
intelligent platform necessary for business-critical applications.
More powerful Management
Improved Performance and Scalability
Better Security and Availability
Changes for deveolpers
Compress the database files with page level, row level mode
FileStream datatype
data security - Encryption - Extensible Key Management

DATABASE TRANSACTION:
1.A TRAnsaction is a unit of work, mainly consists of DML operation.
2.sqlserver runs in 3 types of transaction modes:
1.auto commit mode
2.implicit transaction mode
3.explicit transaction mode
1.auto commit mode:

1.in auto commit mode ,the transaction are starts with "DML OPEARTION"
2.After executing DML command the transaction ends automatically with
"commit".
3.In auto commit mode, user can't control transaction.
2.implicit transaction mode
implicit transaction mode
When a connection is operating in implicit transaction mode, the instance of the
SQL Server Database Engine automatically starts a new transaction after the cur
rent transaction is committed or rolled back. You do nothing to delineate the st
art of a transaction; you only commit or roll back each transaction. Implicit tr
ansaction mode generates a continuous chain of transactions.
After implicit transaction mode has been set on for a connection, the instance o
f the Database Engine automatically starts a transaction when it first executes
any of these statements:
Explicit Transaction:
In ADO, use the BeginTrans method on a Connection object to start an explicit tr
ansaction.
To end the transaction, call the Connection object's CommitTrans or RollbackTran
s methods.
In the ADO.NET SqlClient managed provider, use the BeginTransaction method on a
SqlConnection object to start an explicit transaction. To end the transaction, c
all the Commit() or Rollback() methods on the SqlTransaction object.
The ODBC API does not support explicit transactions, only autocommit and implici
t transactions.
Explicit transaction mode lasts only for the duration of the transaction.
When the transaction ends, the connection returns to the transaction
mode it was in before the explicit transaction was started,
either implicit or autocommit mode.

SELECT * FROM STUDENT


SET IMPLICIT_TRANSACTIONS ON
INSERT INTO STUDENT VALUES('AAA',201,300,300)
SELECT * FROM STUDENT
ROLLBACK
SELECT * FROM STUDENT
SET IMPLICIT_TRANSACTIONS OFF

3.EXPLICIT TRANSACTION
BEGIN TRANSACTION
INSERT INTO STUDENT VALUES('AAA',301,300,200)
SELECT * fROM STUDENT
ROLLBACK TRANSACTION
SELECT * FROM STUDENT
SAVE TRANSACTION:
1.THE SAVE TRANSACTION IS USED TO BREAK A LONG TRANSACTION INTO SMALL PARTS.
2.USING THIS WE CAN CANCEL PART OF THE TRANSACTION.
BEGIN TRANSACTION
INSERT INTO STUDENT VALUES('XXX',104,59,459)
SELECT * FROM STUDENT
SAVE TRANSACTION ST1
DELETE FROM STUDENT
SELECT * FROM STUDENT
ROLLBACK TRANSACTION ST1
SELECT * FROM STUDENT

SQL FUNCTION:
1.GROUP FUNCTION/MULTIPLE ROW FUNCTION/AGGREGATE FUNCTION
A.SUM()
B.AVG()
C.MAX()
D.MIN()
E.COUNT() - RETURN INT DATATYPE
F.COUNT_BIG() - RETURN BIGINT DATATYPE
How to know how many tables contains empno as a column in a database?
SELECT COUNT(*) AS Counter FROM syscolumns
WHERE (name = 'empno')
Find duplicate rows in a table?
SELECT ENAME,MGR, COUNT(*) AS Counter FROM
EMP GROUP BY ENAME, MGR HAVING (COUNT(*) > 1)
21.
How to find 6th highest salary
SELECT TOP 1 sal FROM (SELECT DISTINCT TOP 6
sal FROM emp ORDER BY sal DESC) a
ORDER BY sal

2.SINGLE ROW FUNCTION


1.STRING FUNCTION
2.DATE FUNCTION
3.MATHEMATICAL
4.CONVERSION FUNCTION

5.SPECIAL FUNCTION
6.OLAP(ON LINE ANALYTICAL PROCESSING) -RANK()
SELECT
SELECT
SELECT
SELECT
SELECT
SELECT
SELECT
SELECT

SUM(MARK) FROM STUDENT


SUM(MARK) TOTAL FROM STUDENT
AVG(MARK) FROM STUDENT
MAX(MARK) FROM STUDENT
MIN(MARK) FROM STUDENT
COUNT(*) FROM STUDENT
COUNT_BIG(*) FROM STUDENT
* FROM STUDENT

GROUP BY CLAUSE:
1.IT IS USED TO GROUP RECORDS BASED ON ONE OR MORE COLUMNS TO CALCULATE AGGREGAT
ES LIKE MAX,MIN,SUM,AVG,COUNT ETC.....
2.USING GROUP BY WE CAN PRODUCE SUMMAIRIZED DATA FROM DETAILED DATA.
3.The GROUP BY clause can be used in a SELECT statement to collect data across m
ultiple records and group the results by one or more columns.
The syntax for the GROUP BY clause is:
SELECT column1, aggregate_function (expression)
FROM table_NAME WHERE condition GROUP BY column1
Q: DISPLAY SUM OF SALARY FOR EACH DEPARTMENT
A: SELECT DEPTNO,SUM(SALARY) FROM EMP GROUP BY DEPTNO
Q: DISPLAY MAXIMUM SALARY FOR EACH DEPARTMENT
A: SELECT DEPTNO,MAX(SALARY) FROM EMP GROUP BY DEPTNO
Q: DISPLAY MINIMUM SALARY OF EACH DEPARTMENT
A: SELECT DEPTNO,MIN(SALARY) FROM EMP GROUP BY DEPTNO
Q: DISPLAY NO.OF EMPLOYEES WORKING FOR EACH DEPTNO
A: SELECT DEPTNO,COUNT(*) FROM EMP GROUP BY DEPTNO
Q: DISPLAY AVERAGE SALARY FOR EACH DEPARTMENT
A: SELECT DEPTNO,AVG(SALARY) FROM EMP GROUP BY DEPTNO
DISPLAY NO.OF EMPLOYEES JOINED IN EACH YEAR
SELECT YEAR(HIREDATE) YEAR,COUNT(*) NO.OF EMPS FROM EMP GROUP BY YEAR(HIREDATE)
DISPLAYS NO.OF EMPLOYEES JOINED IN EACH DAY
SELECT DATENAME(DW,HIREDATE) DAY,COUNT(*) NO.OF EMPLOYEES FROM EMP
GROUP BY DATENAME(DW,HIREDATE)
DISPLAY MAX.SALARY FOR EACH DEPARTMENT WHOSE DEPTMENT NUMBER IS EQUAL TO 10 OR 3
0.

SELECT DEPTNO,MAX(SAL) FROM EMP WHERE DEPTNO IN(10,30)


GROUP BY DEPTNO

ROLLUP CLAUSE:
The ROLLUP clause extends GROUP BY to return a row containing a subtotal for
each group along with a total for all groups ...
SELECT DEPTNO,SUM(SALARY) FROM EMP GROUP BY DEPTNO WITH ROLLUP
SELECT DEPTNO,SUM(SALARY),MAX(SALARY),MIN(SALARY),COUNT(SALARY),AVG(SALARY) FROM
EMP GROUP BY DEPTNO WITH ROLLUP
HAVING CLAUSE:
Having clause is used with the select clause to specify a search condition for a
group or aggregate.
What is the difference between where clause and having clause?
1. 'Where' clause applies to the individual rows whereas 'Having' clause is used
to test some condition on the group(usually aggregate methods) ...
2.To filter data before group by use where clause.
3.To filter data after group by use having clause.
4.In condition,if there is no aggregate function then use where clause.
5.In condition, if there is aggregate function,then use having clause.

* DISPLAY MAX.SALARIES FOR EACH DEPARTMENT WHERE DEPARTMENT NUMBER IS


EQUAL TO 10 (OR) 30 AND MAX.SAL>=3000
SELECT DEPTNO,MAX(SAL) MAXSAL FROM EMP
WHERE DEPTNO IN(10,30)
GROUP BY DEPTNO
HAVING MAX(SAL)>=3000
*DISPLAY NO.OF EMPLYOEES JOINED IN EACH YEAR WHEN YEAR=1981 OR 1982
AND NO.OF EMPLOYEES>2
SELECT YEAR(HIREDATE) YEAR,COUNT(*) NO.OF EMPS FROM EMP WHERE
YEAR(HIREDATE) IN(1981,1982)
GROUP BY YEAR(HIREDATE)
HAVING COUNT(*)>2
Finding Duplicates with SQL
SELECT MGR,COUNT(MGR) FROM EMP GROUP BY MGR

HAVING (COUNT(MGR)>1)
/

List out the department NO having atleast four employees.


SELECT DEPTNO,COUNT(*) FROM EMP GROUP BY DEPTNO HAVING COUNT(*)>=4
How many employees joined in January month.
SELECT DATENAME(MM,HIREDATE),COUNT(*) FROM EMP GROUP BY DATENAME(MM,HIREDATE)
HAVING DATENAME(MM,HIREDATE)='january'
How many employees who are joined in January or September month.
SELECT DATENAME(MM,HIREDATE),COUNT(*) FROM EMP GROUP BY DATENAME(MM,HIREDATE)
HAVING DATENAME(MM,HIREDATE)='january' or DATENAME(MM,HIREDATE)='september'
*How many employees who are joined in 1981.
SELECT YEAR(HIREDATE) YEAR ,COUNT(*) FROM EMP GROUP BY YEAR(HIREDATE)
HAVING YEAR(HIREDATE)=1981
How many employees joined each month in 1981.
SELECT DATENAME(MM,HIREDATE) MONTH,COUNT(*) COUNT FROM EMP
WHERE YEAR(HIREDATE) IN(1981)
GROUP BY DATENAME(MM,HIREDATE)
How many employees who are joined in DEC 1981
SELECT YEAR(HIREDATE) YEAR ,COUNT(*) FROM EMP
WHERE DATENAME(MM,HIREDATE) IN('DECEMBER')
GROUP BY YEAR(HIREDATE) HAVING YEAR(HIREDATE)=1981
ORDER BY CLAUSE :
IT IS USED TO arrange records either ascending order or descending order.
by default ascending order
ASC
Specifies that the values in the specified column should be sorted in ascending
order, from lowest value to highest value.
DESC
Specifies that the values in the specified column should be sorted in descending
order, from highest value to lowest value.
syntax:
SELECT column_name
FROM table_name
[WHERE condition]
ORDER BY column_name [ASC, DESC]

1.List out the employee id, ename in ascending order based on the employee id.
select empno,ename from emp order by empno asc
2.List out the employee id, name in descending order based on salary column
select empno,ename from emp order by sal desc
COMPUTE FUNCTION
select * from emp compute sum(sal),avg(sal),
max(sal),count(sal),min(sal)
ORDER OF DECLARATION :[ USER FOLLOWS]
1.SELECT
2.FROM
3.WHERE
4.GROUP BY
5.HAVING
6.ORDER BY
ORDER OF EXECUTION : [SYSTEM FOLLOWS]
1.FROM
2.WHERE
3.GROUP BY
4.HAVING
5.ORDER BY
6.SELECT

single row function


1.string function
2.date function
3.mathematical function
4.conversion
5.special function
6.OLAP(Online Analytical processing)
rank(),dense_rank(),row_number()
string function/character function
1.len('peers') => 5
2.upper('peers') =>PEERS
3.lower('PEERS') =>peers
4.reverse('rajesh') => hsejar
5.Replicate('raj ',5) => raj raj raj raj raj
6.left(string ,no.of char)
7.right(string,no.of char)
6.substring('string',starting,no.of char)
7.charindex(string1,string2)
8.replace(string,char1,char2)

9.space()
10.LTRIM('
PEERS')
11.RTRIM('PEERS ')
12.reverse('peers')
13.SELECT STUFF('NOTEPAD',1,4,'WORD') => WORDPAD
13.SELECT STUFF('NOTE BOOK',5,0,'IN A') => NOTE IN A BOOK

EXAMPLE:
SELECT LEN('PEERS')
SELECT UPPER('peers') result
select LOWER('PEERS AMEERPET')
SELECT LEFT('PEERS AMEERPET',5)
SELECT RIGHT('PEERS AMEERPET',8)
SELECT SUBSTRING('HAVE A NICE DAY',8,8)
SELECT REPLACE('HELLO','ELL','ABC')
SELECT CHARINDEX('O','HELLO WORLD',6)
SELECT 'HELLO'+SPACE(10)+'GOOD WORLD'
DATE FUNCTION
SELECT
SELECT
SELECT
SELECT
SELECT
SELECT
SELECT
SELECT
SELECT
SELECT
SELECT
SELECT
SELECT
SELECT
SELECT
SELECT
SELECT
SELECT

GETDATE()
YEAR(GETDATE())
MONTH(GETDATE())
DAY(GETDATE())
DATEPART(dd,GETDATE())
DATEPART(MM,GETDATE())
DATENAME(DW,GETDATE())
DATENAME(MM,GETDATE())
DATENAME(YY,GETDATE())
DATEDIFF(FORMAT,DATE1,DATE2);
DATEDIFF(DD,GETDATE(),'10-10-2010')
GETDATE() +100
DATEPART(HH,GETDATE())
DATEPART(MI,GETDATE())
DATEPART(SS,GETDATE())
DATEADD(FORMAT,N,DATE)
DATEADD(DD,5,GETDATE())
DATEADD(MM,5,GETDATE())

DATE FORMAT:
DD
MM
YY
HH
MI
SS
DW
WW
QQ

-DAY
- MONTH
- YEAR
-HOUR
- MINUTE
- SECONDS
- DAY OF WEEK
- WEEK OF YEAR
- QUARTER OF YEAR

1.FIND THE EMPLOYEES WHO ARE JOINED IN DECEMBER MONTH


SELECT * FROM EMP WHERE DATEPART(MM,HIREDATE)=12
2.FIND SINCE HOW MANY YEARS THE EMP IS WORKING IN THE COMPANY

SELECT EMPNO,ENAME,DATEDIFF(YY,HIREDATE,GETDATE()) WORKING_SINCE FROM EMP


MATHEMATICAL FUNCTION
SELECT ABS(-10) => 10
SELECT SIN(30)
SELECT COS(30)
select tan(30)
select power(10,3) => 1000
select sqrt(100) => 10
select square(5) => 25
select sign(-10) => -1
select sign(94)
=> 1
select sign(0)
=> 0
SELECT CEILING(8949.8949)
SELECT FLOOR(8949.8749084)
select radian(30.00)
select degrees(0.59959)
select log(2)
select exp(3)
select round(n,p,[t]) 3 rd argument 't' is specified as '1' then n will be trunc
ated.
select pi()
SELECT
SELECT
SELECT
SELECT
SELECT
SELECT
SELECT
SELECT
SELECT
SELECT
SELECT
SELECT
SELECT
SELECT
SELECT
SELECT
SELECT
SELECT
SELECT

ABS(-50)
SIN(30)
COS(30)
TAN(30)
POWER(10,3)
SQRT(100)
SQUARE(10)
SIGN(-8484)
SIGN(8494)
SIGN(0)
ASCII('A')
CHAR(65)
CEILING(8888.8888)
FLOOR(8888.8888)
ROUND(8888.8888,2)
ROUND(8888.8888,1)
ROUND(8888.8888,0)
ROUND(8888.8888,-1)
ROUND(8888.8888,-2)

Usage of OVER Clause:


----------------------------------* Over clause can be used in association with aggregate function and ranking fu
nction.
* The over clause determine the partitioning and ordering of the records before
associating with aggregate or ranking function.
* Over by clause along with aggregate function can help us to resolve many issue
s in simpler way.
CONVERSION FUNCTION
CAST()
CONVERT()
Both these functions are used to convert values from one datatype to another
But there are some differences between them

1 CAST is ANSI standard and CONVERT is specific to SQL Server


2 CAST can't be used for formating purposes.
But CONVERT can be used for formating purposes particularly on datetime and mone
y datatype
CAST(EXPR AS DATEYPE)
EX:
CAST(@C AS VARCHAR)
CONVERT(INT,8489.8484)
8489
SELECT CONVERT(INT,84894.74874)
SELECT CONVERT(VARCHAR,GETDATE())
SELECT ENAME,CONVERT(VARCHAR,HIREDATE,2) FROM EMP
1 to 14 (without century)
100 to 131 with century)
ex1:
select ename +'earns'+cast(sal as varchar) from emp
select ename +'joined on'+ cast(hiredate as varchar) from emp
select ename + 'joined on '+datename(dw,hiredate) from emp
SPECIAL FUNCTION
db_name() => database name
user_name() => username
host_name()=>hostname
ident_current() => current value of the identity
ident_seed() => starting value of the identity
ident_incr() => it retrun increment value
EX:
SELECT DB_NAME() => MASTER
SELECT USER_NAME() =>DBO
SELECT HOST_NAME() =>ONLINE01
SELECT IDENT_CURRENT()
EXAMPLE OF IDENTITY:
IDENTIY IS USED TO CREATE THE UNIQUE IDENTIY NUMBER
CREATE TABLE EMP1(ENAME VARCHAR(20),ENO INT IDENTITY(100,1))
INSERT INTO EMP1(ENAME) VALUES('AAA')
SELECT * FROM EMP1
How to create a Identity clause in existing table?
alter table emp add eno int identity
EXAMPLE
SELECT IDENT_CURRENT('EMP1')
SELECT IDENT_INCR('EMP1')
SELECT IDENT_SEED('EMP1')
How to change the identity starting value?

dbcc checkident('emp2',reseed,2000)
dbcc- database consistency checker

OLAP(ONLINE ANALYTICAL PROCESSING)


RANK() THIS FUNCTION GENERATES THE RANKS BY SKIPPING NEXT IMMEDIATE RANKS WHEN
MORE THAN ONE ROW SHARE THE SAME COLUMN.
DENSE_RANK() : THIS FUNCTION GENERATES A RANK WITHOUT SKIPPING NEXT IMMEDIATE RA
NKS EVEN MORE THAN ON ROW SHARE THE SAME RANK.
ROW_NUMBER() : THIS FUNCTION GENERATES SEQUENTIAL NUMBER FOR THE ROWS IN THE
SAME ORDER AS THEY ARE RETERIVED FROM THE TABLE.
TO GENERATES A RANK,DENSE_RANK,ROW_NUMBER() FOR THE EMPLOYEE BASESD ON SALARY DE
PTWISE
SELECT EMPNO,ENAME,DEPTNO,SAL,
OVER(PARTITION BY DEPTNO ORDER
DENSE_RANK() OVER(PARTITION BY
ROW_NUMBER() OVER(PARTITION BY

RANK()
BY SAL DESC) AS RANK,
DEPTNO ORDER BY SAL DESC) AS DENSERANK,
DEPTNO ORDER BY SAL DESC) AS SEQNO FROM EMP

SELECT * FROM STUDENT


INSERT
INSERT
INSERT
INSERT
SELECT
SELECT

INTO STUDENT VALUES('MMM',104,200,200)


INTO STUDENT VALUES('NNN',105,300,300)
INTO STUDENT VALUES('PPP',106,400,329)
INTO STUDENT VALUES('QQQ',107,89,48)
* FROM STUDENT
NAME,MARK,RANK() OVER(ORDER BY MARK DESC) AS RNK FROM STUDENT

COMPUTE FUNCTION:
1.FIND TOTAL SAL PAID TO EMPLOYEES WHILE DISPLAYING COMPLETE DETAILS OF EMPLOYEE
SELECT * FROM EMP COMPUTE SUM(SAL),AVG(SAL),MAX(SAL),MIN(SAL),COUNT(SAL)
2.FIND TOTAL SAL PAID TO EMPLOYEES DEPARTMENT WISE WHILE DISPLAYING
COMPLETE DETAILS OF EMPLOYEES.
SELECT * FROM EMP ORDER BY DEPTNO COMPUTE SUM(SAL) BY DEPTNO
3.FIND NO.OF EMPLOYEES AND HIGHEST AND LOWEST SALARIES PAID TO EMPLOYEES
JOBWISE WHILE DISPLAYING COMPLETE DETAILS OF EMPLOYEE
SELECT * FROM EMP ORDER BY JOB COMPUTE COUNT(SAL),MAX(SAL),MIN(SAL) BY JOB
OVER(PARTITION BY)
COMPUTE BY DISPLAYS THE RESULT OF AGGREGATE ONLY ONES AT THE END OF THE GROUP
BUT OVER() FUNCTION DISPLAYS AGGREATES WITH EVERY ROW IN THE GROUP.
1.FIND THE TOTAL SAL PAID TO EMPLOYEES WHILE DISPLAYING COMPLETE DETAILS OF EMPL
OYEES

SELECT *,SUM(SAL),OVER(PARTITION BY DEPTNO) FROM EMP


2. FIND TOTAL NO.OF EMPLOYEES HIGHEST,LOWEST SAL PAID TO EMPLOYEES, JOBWISE WILL
DISPLAYING COMPLETE DETAILS OF EMPLOYEES.
SELECT *,COUNT(SAL) OVER(PARTITION BY JOB),
MAX(SAL) OVER(PARTITION BY JOB),
MIN(SAL) OVER(PARTITION BY JOB)
FROM EMP

ORDER BY CLAUSE
IT IS USED TO arrange records either ascending order or descending order.by defa
ult ascending order
SELECT
SELECT
SELECT
SELECT

*
*
*
*

FROM
FROM
FROM
FROM

STUDENT
STUDENT ORDER BY MARK ASC
STUDENT ORDER BY ROLLNO DESC
STUDENT ORDER BY NAME

having clause
it is used to apply the condition in the group of records.
select sum(salary) from emp1
select deptno,sum(salary) from emp1 group by deptno
select deptno,sum(salary) from emp1 group by deptno having deptno not in(20)
distinct clause;
it is used to eliminates the duplicate records.
select distinct deptno from emp1
set operators;
1.union
2.union all
3.intersect
4.except
UNION OPERATORS:
1.IT COMBINES THE RESULT OF TWO SELECT STATEMENTS.
2.UNION OPERATORS ELIMINATES THE DUPLICATES.
3.THE RESULT IS SORTED ORDER (ASCENDING ORDER ONLY)
UNION ALL OPERATORS:
1.IT IS SIMILAR TO UNION.
2.HERE, DUPLICATEDS ARE INCLUDED AND RESULT IS NOT SORTED.
3.INTERSECT :

1.IT RETURNS COMMON VALUES FROM THE RESULT OF TWO SELECTION STATEMENTS.

4.EXCEPT :
1.IT RETURNS VALUES PRESENTING IN RESULT OF 1ST SELECT STATEMENT AND NOT IN 2nd
SELECT STATEMENT.

1.{101,102,103,104,105} union { 101,103,105,107,109}


=101,102,103,104,105,107,109
2.{101,102,103,104,105} union all { 101,103,105,107,109}
={101,102,103,104,105,101,103,105,107,109}
3.{101,102,103,104,105} intersect { 101,103,105,107,109}
={101,103,105}
4.{101,102,103,104,105} except { 101,103,105,107,109}
={102,104}
CREATE
INSERT
INSERT
INSERT
INSERT
INSERT
SELECT

TABLE EMP3(ENAME VARCHAR(20),ENO INT)


INTO EMP3 VALUES('AAA',101)
INTO EMP3 VALUES('BBB',103)
INTO EMP3 VALUES('CCC',105)
INTO EMP3 VALUES('DDD',107)
INTO EMP3 VALUES('EEE',109)
* FROM EMP3

SELECT
SELECT
SELECT
SELECT
SELECT
SELECT

ENO FROM EMP2


ENO FROM EMP2
ENO FROM EMP2
ENO FROM EMP2
* FROM EMP3
* FROM EMP2

UNION SELECT ENO FROM EMP3


UNION ALL SELECT ENO FROM EMP3
INTERSECT SELECT ENO FROM EMP3
EXCEPT SELECT ENO FROM EMP3

CTE (COMMAN TABLE EXPRESSION)


The recursive CTE structure must contain at least one anchor member and one recu
rsive member. The following pseudocode shows the components of a simple recursiv
e CTE that contains a single anchor member and single recursive member.
WITH cte_name ( column_name [,...n] )
AS
(
CTE_query_definition
UNION ALL

- Anchor member is defined.

CTE_query_definition

- Recursive member is defined referencing cte_name.

)
-- Statement using the CTE
SELECT *
FROM cte_name
The semantics of the recursive execution is as follows:
Split the CTE expression into anchor and recursive members.
Run the anchor member(s) creating the first invocation or base result set (T0).
Run the recursive member(s) with Ti as an input and Ti+1 as an output.
Repeat step 3 until an empty set is returned.
Return the result set. This is a UNION ALL of T0 to Tn.
EXAMPLE :
WITH cte
AS (
SELECT -- anchor member
1 AS n
UNION ALL
SELECT -- recursive member
n + 1
FROM
cte
WHERE
-- terminator
n < 50)
SELECT
*
FROM
cte

SPECIAL OPERATORS:
SELECT * FROM EMP2 WHERE SALARY IS NULL
SELECT * FROM EMP2 WHERE SALARY IS NOT NULL
1.FIND TOP 10% OF HIGHEST SALARY EMPLOYEES.
SELECT TOP 10 PERCENT * FROM EMP ORDER BY SAL DESC

constraints:
1.it is used to controlling the data in a table.
2.it is used to prevent the invalid data entry into table.
3.it also used to maintain the security of the table.
4.it is used to implement the business rule.
or
The Process or enforcing the business rules on database tables is called "Data I
ntegrity".
There are two types of data integrity:
1.Predefined integrity [constraints]
2.User defined integrity [ Database triggers]
Predefined Integrity:
a.Domain integrity constraints
b.Entity Integrity Constraints
c.Referentital Integrity constraints
Domain Inegrity Constraints:
a.Check constraints
b.not null constraints
c.Default constraints
Entity Integrity constraints
a.Primary key constraints
b.unique key constraints
Referential Integrity Constraints
a.Foreign key constraints

sqlserver 3 types of Integrirty constriants:


1.domain integrity constraints
a.check constraints (validates data based on a condition)
b.not null constraints - A column declared with not null into that colum
n null
values are not allowed.
c.default constraints - SQLSERVER INSERTS DEFAULT VALUE
student
name
rollno
aaa
101
bbb
101
2.entity integrity constriants
a. primary key constraints (UNIQUE +NOT NULL)
b.unique key constraints (UNIQUE)
3.Referential integrity constraints
a.foreign key constraints
PRIMARY KEY CONSTRAINTS:
1.A COLUMN DECLARED WITH PRIMARY KEY DOESNOT ALLOW DUPLICATES AND NULL VALUES.
2.A COLUMN DECLARED WITH PRIMARY KEY, UNIQUELY IDENTIFIES EACH RECORD IN A TABLE
.

3.A TABLE ALLOWS ONLY ONE PRIMARY KEY.


4. NUMERIC COLUMNS ARE PREFERED AS PRIMARY KEYS THAN CHARACTER COLUMNS.
UNIQUE KEY CONSTRAINTS:
1.UNIQUE DOESNOT ALLOW DUPLICATE VALUES.
2.it accepts only one null values.
3.A table allow more than one unique key.
FOREIGN KEY CONSTRAINTS:
1.A FOREIGN KEY REFERS PRIMARY KEY OR UNIQUE COLUMNS OF ANOTHER TABLE OR SAME TA
BLE.
2.IT IS USED TO ESTABLISH RELATIONSHIP BETWEEN TWO TABLES.
FOREIGN KEY:
Foreign key will allow to store valid values that are present in another
column.
Foreign key and reference key column names can be with same names or wit
h different names. If they are with different names, it is essential that their
data types and size should be same.
Foreign key can be referred to only those columns which is set with Prim
ary key or Unique key.
Foreign key is called Bi-Directional key since;
a. At insertion it works from Child to Parent
b. At deletion it works from parent to child.
Foreign key will allow to store duplicates and null values.
Foreign key and Reference key may exist in same table hence that table i
s called "Self Referenced Table" (or it is often called as "Reflexive Relation")
Foreign key can be created at Column level and can be created at Table o
r Entity level.
A table can have 253 Foreign keys (Recommended by Microsoft), but practi
cally more than 253 Foreign keys can be created in a table.
Foreign key is always created at Child table.
Foreign key will be referred to the data of other column by using REFERE
NCES clause. This clause can be followed by 2 options;
a. ON DELETE CASCADE : It will allow to delete a record from parent table direct
ly and the same record from child table gets deleted automatically.
b. ON DELETE SET NULL : It will allow to delete a record from parent table direc
tly and at child table Foreign key column data will be set to null values.
ONE - ONE
ONE - MANY

MANY - ONE
MANY - MANY

key: Key is a field on which condition is applied for a data reterival or data m
odifications.
CANDIDATE KEY:- is a column in a table which has the
ability to become a primary key.
ex:
deptno and dname
Alternate Key:- Any of the candidate keys that is not part
of the primary key is called an alternate key/Secondary key.
Composite key:- A primary key that consists of two or more
attributes is known as composite key
--EXCEPT SATURDAY AND SUNDAY
CREATE TABLE E11(ENAME VARCHAR(20),ENO INT,DOJ DATETIME CHECK(DATEPART(DW,DOJ) N
OT IN(1,7)))
INSERT INTO E11 VALUES('XXX',101,'03-13-2015')
CHECK CONSTRAINTS:
CREATE TABLE STUDENT(NAME VARCHAR(20),ROLLNO INT,
MARK INT CHECK (MARK <=100))
INSERT INTO STUDENT VALUES('AAA',1001,99)
INSERT INTO STUDENT VALUES('BBB',1002,100)
INSERT INTO STUDENT VALUES('CCC',1003,110)
The INSERT statement conflicted with the CHECK constraint "CK__STUDENT__MARK__51
BA1E3A". The conflict occurred in database "master", table "dbo.STUDENT", column
'MARK'.
The statement has been terminated.
NOT NULL
CREATE TABLE STUDENT (NAME VARCHAR(20),ROLLNO INT
NOT NULL,MARK INT)
INSERT INTO STUDENT VALUES('AAA',101,200)
INSERT INTO STUDENT VALUES('BBB',NULL,300)
Msg 515, Level 16, State 2, Line 1
Cannot insert the value NULL into column 'ROLLNO', table 'master.dbo.STUDENT'; c
olumn does not allow nulls. INSERT fails.
The statement has been terminated.

PRIMARY KEY CONSTRAINTS:

CREATE
INSERT
INSERT
INSERT
INSERT

TABLE STUDENT(NAME VARCHAR(20),ROLLNO INT PRIMARY KEY,MARK INT)


INTO STUDENT VALUES('AAA',101,200)
INTO STUDENT VALUES('BBB',102,300)
INTO STUDENT VALUES('CCC',NULL,300)
INTO STUDENT VALUES('CCC',101,394)

Msg 2627, Level 14, State 1, Line 1


Violation of PRIMARY KEY constraint 'PK__STUDENT__54968AE5'. Cannot insert dupli
cate key in object 'dbo.STUDENT'.
The statement has been terminated.
UNIQUE CONSTRAINTS:
CREATE TABLE STD1(NAME VARCHAR(20),ROLLNO INT UNIQUE,MARK INT)
INSERT
INSERT
INSERT
INSERT
INSERT

INTO
INTO
INTO
INTO
INTO

STD1
STD1
STD1
STD1
STD1

VALUES('AAA',101,200)
VALUES('BBB',102,300)
VALUES('CCC',103,400)
VALUES('DDD',NULL,40)
VALUES('EEE',101,200)

Msg 2627, Level 14, State 1, Line 1


Violation of UNIQUE KEY constraint 'UQ__STD1__567ED357'. Cannot insert duplicate
key in object 'dbo.STD1'.
The statement has been terminated.
DEFAULT CONSTRAITNS:
CREATE
INSERT
INSERT
INSERT
INSERT
SELECT
AAA
BBB
CCC
DDD

TABLE STD2(NAME VARCHAR(20),ROLLNO INT,DOJ DATETIME DEFAULT GETDATE())


INTO STD2 (NAME,ROLLNO) VALUES('AAA',101)
INTO STD2 (NAME,ROLLNO) VALUES('BBB',102)
INTO STD2 (NAME,ROLLNO) VALUES('CCC',103)
INTO STD2 (NAME,ROLLNO) VALUES('DDD',104)
* FROM STD2
101
102
103
104

2010-08-20
2010-08-20
2010-08-20
2010-08-20

11:27:00.763
11:27:12.187
11:27:23.153
11:27:29.950

FOREIGN KEY
DEPT (PARENT TABLE)
DNAME
ECE
EEE
MECH
C.S

DEPTNO
10
20
30
40

LOC (DEPTNO PRIMARY KEY)


HYD
CHE
BANG
NOIDA

EMP(CHILD TABLE)
ENAME

EMPNO

DEPTNO SALARY (DEPTNO FOREIGN KEY)

XXX

101

20

5000

YYY
ZZZ

102
103

10
30

2000
3499

CREATE TABLE DEPT(DNAME VARCHAR(20),DEPTNO INT PRIMARY KEY,LOC VARCHAR(20))


INSERT
INSERT
INSERT
INSERT
SELECT

ECE
EEE
MECH
C.S

INTO DEPT VALUES('ECE',10,'CHENNAI')


INTO DEPT VALUES('EEE',20,'HYDERABAD')
INTO DEPT VALUES('MECH',30,'BANG')
INTO DEPT VALUES('C.S',40,'NOIDA')
* FROM DEPT

10
20
30
40

CHENNAI
HYDERABAD
BANG
NOIDA

FOREIGHN KEY
CREATE
DEPTNO
INSERT
INSERT
INSERT
INSERT

TABLE EMP(ENAME VARCHAR(20),ENO INT PRIMARY KEY,


INT FOREIGN KEY REFERENCES DEPT (DEPTNO),SALARY INT)
INTO EMP VALUES('AAA',101,10,2000)
INTO EMP VALUES('BBB',102,30,3000)
INTO EMP VALUES('CCC',103,20,4004)
INTO EMP VALUES('DDD',104,50,4949)

Msg 547, Level 16, State 0, Line 1


The INSERT statement conflicted with the FOREIGN KEY constraint "FK__EMP__DEPTNO
__5D2BD0E6". The conflict occurred in database "master", table "dbo.DEPT", colum
n 'DEPTNO'.
The statement has been terminated.
Gettting list of constraints:
syntax:
sp_helpconstraint 'tablename'
ex:
sp_helpconstraint 'emp'
or
SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE TABLE_NAME='EMP1'
ALTER TABLE table_name ALTER COLUMN col_name data_type[(size)] NOT NULL
Syntax:(CHECK,UNIQUE,PRIMARY KEY,FOREIGN KEY)
ALTER TABLE table_name ADD [CONSTRAINT constraint_name] constraint_type(col1[,co
l2,col3,.......])

DROPING OF CONSTRAINTS:
Constraints which are created on different columns of different tables can be dr
opped using DROP option of ALTER TABLE command.
Syntax:
ALTER TABLE table_name DROP CONSTRAINT constraint_name
ALTER TABLE employ3 DROP CONSTRAINT pay_u
ALTER TABLE employ3 DROP CONSTRAINT dno_d
JOIN IS USED TO reterive the records from the MULTIPLE TABLES
OR MULTIPLE QUERYS
TYPE OF JOIN:
1.SIMPLE JOIN /INNER JOIN
A.EQUI JOIN (=)
B.NON EQUI JOIN(<,>,<=,>=,=,!=)
2.OUTER JOIN
LEFT OUTER JOIN
RIGHT OUTER JOIN
FULL OUTER JOIN
3.CROSS JOIN / CARTESIAN JOIN
4.SELF JOIN
TO PERFORM JOIN , THERE ARE TWO SYNTAXES :
1.ANSI SYNTAX ,INNER JOIN,LEFT OUTER JOIN ....
2.NON ANSI SYNTAX =,<,>........

SIMPLE JOINS:
CREATE TABLE EMP1(ENAME VARCHAR(20),ENO INT,SALARY INT)
CREATE TABLE EMP2(NAME VARCHAR(20),ENO INT,SAL INT)
INSERT
INSERT
INSERT
INSERT
INSERT

INTO
INTO
INTO
INTO
INTO

EMP1
EMP1
EMP1
EMP1
EMP1

VALUES('AAA',101,200)
VALUES('BBB',102,300)
VALUES('CCC',103,400)
VALUES('DDD',104,500)
VALUES('EEE',105,600)

INSERT
INSERT
INSERT
INSERT
INSERT

INTO
INTO
INTO
INTO
INTO

EMP2
EMP2
EMP2
EMP2
EMP2

VALUES('MMM',101,200)
VALUES('NNN',103,500)
VALUES('OOO',105,949)
VALUES('PPP',107,949)
VALUES('QQQ',109,844)

SELECT * FROM EMP1


SELECT * FROM EMP2

SELECT A.ENAME,A.ENO,A.SALARY,B.NAME,B.ENO,B.SAL
FROM EMP1 A,EMP2 B WHERE A.ENO=B.ENO
AAA
CCC
EEE

101
103
105

200
400
600

MMM
NNN
OOO

101
103
105

200
500
949

SELF JOIN
JOINING THE TABLE ITSELF
TABLE : EMP
ENAME
AAA
BBB
CCC
DDD
EEE

ENO
101
102
103
104
105

MGR
105
105
101
102
101

SALARY
2000
5999
4994
994
4949

QUERY:
ENAME
AAA
BBB
CCC
DDD
EEE
CREATE
INSERT
INSERT
INSERT
INSERT
INSERT

MGRNAME
EEE
EEE
AAA
BBB
AAA
TABLE EMP(ENAME VARCHAR(20),ENO INT, MGR INT,SALARY SMALLMONEY)
INTO EMP VALUES('AAA',101,105,2000)
INTO EMP VALUES('BBB',102,105,3000)
INTO EMP VALUES('CCC',103,101,4994)
INTO EMP VALUES('DDD',104,102,4994)
INTO EMP VALUES('EEE',105,102,9489)

SELECT * FROM EMP


SELECT A.ENAME,B.ENAME MGRNAME FROM EMP A,EMP B WHERE
A.MGR=B.ENO
AAA
BBB
CCC
DDD
EEE

EEE
EEE
AAA
BBB
BBB

outer join:
1.simple join returns only match records but not un-matching records.
2.outer join to get the un-matching records also.
outer join divided into 3 types:
1.left outer join
2.right outer join
3.full outer join.

Left outer join:


it returns all records from left side table and matching records
from right side table.
SELECT A.ENAME,A.ENO,A.SALARY,B.NAME,B.ENO,B.SAL FROM EMP1 A
LEFT OUTER JOIN EMP2 B ON A.ENO=B.ENO
AAA
BBB
CCC
DDD
EEE

101
102
103
104
105

200
300
400
500
600

MMM
NULL
NNN
NULL
OOO

101
NULL
103
NULL
105

200
NULL
500
NULL
949

right outer join:


it returns all records from right side table and matching recrods
from left side table.
SELECT A.ENAME,A.ENO,A.SALARY,B.NAME,B.ENO,B.SAL FROM EMP1 A RIGHT OUTER JOIN EM
P2 B
ON A.ENO=B.ENO
AAA
CCC
EEE
NULL
NULL

101
103
105
NULL
NULL

200
400
600
NULL
NULL

MMM
NNN
OOO
PPP
QQQ

101
103
105
107
109

200
500
949
949
844

full outer join:


it returns all records from both table.

SELECT A.ENAME,A.ENO,A.SALARY,B.NAME,B.ENO,B.SAL FROM EMP1 A FULL OUTER JOIN EMP


2 B
ON A.ENO=B.ENO
AAA
BBB
CCC
DDD
EEE
NULL
NULL

101
102
103
104
105
NULL
NULL

200
300
400
500
600
NULL
NULL

MMM
NULL
NNN
NULL
OOO
PPP
QQQ

101
NULL
103
NULL
105
107
109

200
NULL
500
NULL
949
949
844

CREATESIAN JOIN OR CROSS JOIN


SELECT NAME,BANKNAME,AMOUNT, (AMOUNT * 5* INTEREST)/100 "SI" FROM BANK,CUSTOMER
AAA
AAA
AAA
BBB

ICICI
SBI
SBH
ICICI

10000
10000
10000
20000

6000
5000
4000
12000

BBB
BBB
CCC
CCC
CCC

SBI
SBH
ICICI
SBI
SBH

20000
20000
30000
30000
30000

10000
8000
18000
15000
12000

JOINS
Joins in SQL Server are used to select the data from multiple tables
using a single select statement.
T-SQL provides the join concept, which allows retrieval of data
from more than one table. This concept is probably the most important
for RDBMS, because it allows data to be spread over many tables.
In SQL Server there existed three types of joins which includes
1.
2.
3.

INNER JOIN
OUER JOIN
CROSS JOIN

Sample Tables
EMP
EMPNO
----------11
22
33
44
55
66

ENAME
---------RAGHU
RAZ
AMAR
MANI
CHARN
ANIL

SAL
--------------------10000.0000
20000.0000
10000.0000
15000.0000
15000.0000
20000.0000

DEPTNO
----------10
20
10
20
40
50

DEPT
DEPTNO
----------10
20
30

DNAME
LOC
---------- ---------SALES
HYD
HR
CHE
IR
BAN

1.INNER JOIN: Inner join selects the data from multiple


tables based on the equality condition It means it selects only matched
records from the multiple tables. For doing this Inner join operation
we should have to maintain one common valued column in the multiple
tables.
Syntax:

SELECT TABLE1.COLUMN1, TABLE1.COLUMN2,


,
TABLE2.COLUMN1, TABLE2.COLUMN2,
FROM TABLE1 INNER JOIN TABLE2
ON TABLE1.COMMON COLUMN=TABLE2.COMMON COLUMN
E.g.:
SELECT EMP.EMPNO, EMP.ENAME,
DEPT.DEPTNO, DEPT.DNAME FROM EMP INNER JOIN DEPT
ON EMP.DEPTNO=DEPT.DEPTNO
EMPNO
----------11
22
33
44

ENAME
DEPTNO
DNAME
---------- ----------- ---------RAGHU
10
SALES
RAZ
20
HR
AMAR
10
SALES
MANI
20
HR

2. OUTER JOIN: It is the extension of Inner Join operation because Inner selects
only matched records from multiple tables where Outer join selects matched reco
rds as well as unmatched records. It includes
a.
b.
c.

Left Outer Join


Right Outer Join
Full Outer Join

a.
Left Outer Join: It selects matched records from both the
tables as well as unmatched records from Left side table.
For doing this operation we have to keep a special symbol * at the
left side of the equality condition.
Syntax:
SELECT TABLE1.COLUMN1, TABLE1.COLUMN2, ,
TABLE2.COLUMN1, TABLE2.COLUMN2,
FROM TABLE1 LEFT OUTER JOIN TABLE2
ON TABLE1.COMMON COLUMN =TABLE2.COMMON COLUMN
E.g.:
SELECT EMP.EMPNO, EMP.ENAME,
DEPT.DEPTNO, DEPT.DNAME
FROM EMP LEFT OUTER JOIN DEPT
ON EMP.DEPTNO =DEPT.DEPTNO
EMPNO
----------11
22
33
44
55
66

ENAME
DEPTNO
DNAME
---------- ----------- ---------RAGHU
10
SALES
RAZ
20
HR
AMAR
10
SALES
MANI
20
HR
CHARN
NULL
NULL
ANIL
NULL
NULL

b.Right Outer Join: It selects matched records from both the tables as
well as unmatched records from Right side table. For doing this
operation we have to keep a special symbol * at the right side of the

equality condition.
Syntax:
SELECT TABLE1.COLUMN1, TABLE1.COLUMN2,
,
TABLE2.COLUMN1, TABLE2.COLUMN2,
FROM TABLE1 RIGHT OUTER JOIN TABLE2
ON TABLE1.COMMON COLUMN = TABLE2.COMMON COLUMN
E.g.:
SELECT EMP.EMPNO, EMP.ENAME,
DEPT.DEPTNO, DEPT.DNAME
FROM EMP RIGHT OUTER JOIN DEPT
ON EMP.DEPTNO = DEPT.DEPTNO

EMPNO
----------11
22
33
44
NULL

ENAME
DEPTNO
DNAME
---------- ----------- ---------RAGHU
10
SALES
RAZ
20
HR
AMAR
10
SALES
MANI
20
HR
NULL
30
IR

c.
Full Outer Join: It is just combination of Left outer Join + Right outer
join. It selects matched records as well as unmatched records from the given ta
bles.
Syntax:
SELECT TABLE1.COLUMN1, TABLE1.COLUMN2,
,
TABLE2.COLUMN1, TABLE2.COLUMN2,
FROM TABLE1 FULL OUTER JOIN TABLE2
ON TABLE1.COMMON COLUMN =TABLE2.COMMON COLUMN
E.g.:
SELECT EMP.EMPNO, EMP.ENAME,
DEPT.DEPTNO, DEPT.DNAME
FROM EMP FULL OUTER JOIN DEPT
ON EMP.DEPTNO =DEPT.DEPTNO
EMPNO
----------11
22
33
44
55
66
NULL

ENAME
DEPTNO
DNAME
---------- ----------- ---------RAGHU
10
SALES
RAZ
20
HR
AMAR
10
SALES
MANI
20
HR
CHARN
NULL
NULL
ANIL
NULL
NULL
NULL
30
IR

CROSS-JOIN:
It is also known as CROSS PRODUCT or CARTESIAN PRODUCT because
it produces the product of multiple tables.
Every row from first table is multiplied with all rows of another table.

Simply it is the multiplication of two tables.


Syntax:
SELECT TABLE1.COLUMN1, TABLE1.COLUMN2, .
TABLE2.COLUMN1,TABLE2.COLUMN2,
FROM TABLE1 CROSS JOIN TABLE2

Ex:
SELECT EMP.EMPNO, EMP.ENAME,
DEPT.DEPTNO, DEPT.DNAME
FROM EMP CROSS JOIN DEPT

EMPNO
----------11
22
33
44
55
66
11
22
33
44
55
66
11
22
33
44
55
66

ENAME
DEPTNO
DNAME
---------- ----------- ---------RAGHU
10
SALES
RAZ
10
SALES
AMAR
10
SALES
MANI
10
SALES
CHARN
10
SALES
ANIL
10
SALES
RAGHU
20
HR
RAZ
20
HR
AMAR
20
HR
MANI
20
HR
CHARN
20
HR
ANIL
20
HR
RAGHU
30
IR
RAZ
30
IR
AMAR
30
IR
MANI
30
IR
CHARN
30
IR
ANIL
30
IR

SELF JOIN:
Join a table with itself by providing two table alias names is called SELF-JOIN.
Select * from DEPT, DEPT
The above statement shows an error message because it not possible to multiply a
table by itself with the same name, so that we have to project the same table D
EPT as two tables to the SQL Server. To show a single DEPT table as two tables t
o server we have to use the concept of table Alias Names.
SELECT * FROM DEPT A, DEPT B
In the above example we provided two table alias names for the single table DEPT
those are A and B. Then server identifies that there are two tables available a
nd it performs join operation in a normal way. According user point of view ther
e existed only one table but according to Server point of view there are two tab
les available those are A and B.

DEPTNO
DNAME
LOC
DEPTNO
DNAME
LOC
----------- ---------- ---------- ----------- ---------- ---------- --------------10
SALES
HYD
10
SALES
HYD
20
HR
CHE
10
SALES
HYD
30
IR
BAN
10
SALES
HY
D
10
SALES
HYD
20
HR
CHE
20
HR
CHE
20
HR
CH
E
30
IR
BAN
20
HR
CHE
10
SALES
HYD
30
IR
BAN
20
HR
CHE
30
IR
B
AN
30
IR
BAN
30
IR
BAN
ANY OPERATORS:
TO FIND ALL EMPLOYEES WHO ARE NOT WORKING IN DEPT 30 AND WHOSE SALARY IS MORE TH
AN THE
SALARY OF ANY ONE EMPLOYEE WORKING IN DEPTNO 30.
SELECT * FROM EMP WHERE DEPTNO!=30 AND SAL >ANY(SELECT DISTINCT SAL FROM EMP WHE
RE DEPTNO=30)
SUB-QUERIES
A Sub Query is also a query, which is defined under a main query.
First Query is also called as outer query or main query and second query is als
o called as inner query or subquery.
It always sends values to its nearest main query.
Server first sub query executed based on the sub query value main query will get
executed.
If a sub query send single value to its nearest main query then that sub query i
s called Single-Valued-Sub query.
If a sub query sends multiple values to its nearest main query then that sub que
ry is called Multi-Valued-Sub query.
Note: If a sub query sends multiple values to its nearest main query then we hav
e to use IN or NOT IN operator between Main query and Sub query.
Syntax:
SELECT * FROM TABLENAME
WHERE COLUMNNAME = (SELECT STATEMENT WHERE CONDITION)

E.g.: WAQ To display employee details, who are working under SMITH dept.
SELECT * FROM EMP
WHERE DEPTNO= (SELECT DEPTNO FROM EMP WHERE ENAME= RAM )
E.g.: WAQ To display employee details, whose salary is greater than highest sala
ry of 30th department
SELECT * FROM EMP
WHERE SAL> (SELECT MAX (SAL) FROM EMP WHERE DEPTNO=10)
E.g.: WAQ To display employee details, whose salary is greater than average sala
ry of SMITH department
SELECT * FROM EMP
WHERE SAL> (SELECT AVG (SAL) FROM EMP WHERE DEPTNO=
SELECT DEPTNO FROM EMP WHERE ENAME= SMITH )
Nested Queries:
* A subquery embedded in another subquery is called "Nested SUB Query"
Select query1(Select query2(Select query3)))
*List the name of the employee whose earnings 2nd Maximum Salary
* select ename from emp where sal=(select max(sal) from emp where sal<(
select max(sal) from emp))
* List name of the department employees earning 2nd maximum salary
* select dname from dept where deptno in(select deptno from emp) where sal=(
select max(Sal) from emp where sal<(select max(sal) from emp)))
SELECT DNAME FROM DEPT WHERE DEPTNO IN(
SELECT DEPTNO FROM EMP WHERE SAL=(SELECT
MAX(SAL) FROM EMP WHERE SAL<(
SELECT MAX(SAL) FROM EMP)))
*SUB-Queries with Update command:
* Update the employee salary to max-salary whose eno=7369
* update emp set sal=(select max(sal) from emp) where empno=101
* UPDATE THE EMPLOYEE SALARY TO MAX-SALARY AND CHANGE JOB 'FORD' WHERE EMPNO=756
6

UPDATE EMP SET SAL=(SELECT MAX(SAL) FROM EMP),


JOB=(SELECT JOB FROM EMP WHERE ENAME='FORD')
WHERE EMPNO=7566
SELECT * FROM EMP

*Sub-Queries with Delete command:


*Delete all employee records whose job of "SMITH".
delete from emp where job=(select job from emp where ename='smith')
CORRELATED SUB QUERIES:
These queries provide different execution to nested query, where it firs
t executes Outer query and then executes inner query.
Nested query is called uni-directional query whereas Corelated Sub Query
is called bi-directional query.
Corelated Sub Query will always gets executed in the following way;
"First outer query gets executed, extracts 1 row at a time(candidate row
) and that row is given to inner query for processing, inner query will provide
its output to outer query and based on the condition outer query will display th
e extracted record".
Display all those employees whose salary is more than the average
salary of their respective departments?
SELECT ENAME,JOB,SAL,DEPTNO
FROM EMP E WHERE SAL>(SELECT AVG(SAL) FROM EMP WHERE DEPTNO=E.DEPTNO)
Write a query to display 1st 3 Maximum Salary Earning Employees(Empno,Ename,Job,
Sal,Deptno)
SELECT EMPNO,ENAME,JOB,SAL,DEPTNO
FROM EMP E
WHERE 3>(SELECT COUNT(DISTINCT SAL) FROM EMP WHERE SAL>E.SAL)
Write a query to display Nth maximum salary earning employee details?
Note: To find Nth Maximum salary condition should be n-1.
SELECT EMPNO,ENAME,JOB,SAL,DEPTNO
FROM EMP E
WHERE 1=(SELECT COUNT(DISTINCT SAL) FROM EMP WHERE SAL>E.SAL)

How to Eliminate the duplicate records from table:


delete from EMP1 where %%physloc%% not in
(select min(%%physloc%%) from emp1 group by
eno having count(*)>=1)
How to identify the duplicate records:
select eno from emp group by eno having count(*)>1

EXISTS AND NOT EXISTS Operator:

EXISTS operator:
This operator will return Boolean value i.e. TRUE or FALSE.
If condition at inner query is satisfied it returns TRUE else returns wi
th FALSE.
Display deptno,dname and loc of all those departments where atleast 1 employee i
s working?
SELECT DEPTNO,DNAME,LOC
FROM DEPT D
WHERE EXISTS(SELECT 1 FROM EMP WHERE DEPTNO=D.DEPTNO)
NOT EXISTS operator:
This operator will also return Boolean value i.e. TRUE or FALSE.
If condition at inner query is not satisfied it returns TRUE else return
s with FALSE.
Display deptno,dname and loc of all those departments where no employees are wor
king?
SELECT DEPTNO,DNAME,LOC
FROM DEPT D
WHERE NOT EXISTS(SELECT 1 FROM EMP WHERE DEPTNO=D.DEPTNO)

EX :
FIND THE EMPLOYEES WHOSE SALARY IS MORE THAN AVG SALARY OF SAME DEPT IN WHICE EM
PLOYEE IS WORKING
SELECT * FROM EMP E WHERE SAL >(SELECT AVG(SAL) FROM EMP S WHERE S.DEPTNO=M.DEPT
NO)
EX 2:
FIND THE HIGHEST SALARY EMPLOYEE DEPT.WISE
SELECT * FROM EMP E WHERE SAL=(SELECT MAX(SAL) FROM EMP S WHERE S.DEPTNO=E.DEPTN
O)
eg:
Write a query to display 1st 3 Maximum Salary Earning Employees(Empno,Ename,Job,
Sal,Deptno)
SELECT EMPNO,ENAME,JOB,SAL,DEPTNO
FROM EMP E
WHERE 3>(SELECT COUNT(DISTINCT SAL) FROM EMP WHERE SAL>E.SAL)
Write a query to display Nth maximum salary earning employee details?
Note: To find Nth Maximum salary condition should be n-1.
SELECT EMPNO,ENAME,JOB,SAL,DEPTNO
FROM EMP E

WHERE 1=(SELECT COUNT(DISTINCT SAL) FROM EMP WHERE SAL>E.SAL)


Examples:
SELECT * FROM (SELECT ENAME,JOB,SAL FROM EMP) E
SELECT ENAME,JOB,SAL FROM (SELECT EMPNO,ENAME,JOB,SAL FROM EMP) E
Display Ename,job,sal of all those employees who are earning First 3 Maximum Sal
aries?
SELECT RN,ENAME,JOB,SAL
FROM (SELECT EMPNO,ENAME,JOB,SAL,ROW_NUMBER() OVER(ORDER BY SAL DESC) RN FROM EM
P) E
WHERE RN<=4
Display ename,job,sal of all those employees whose row positions are at ODD posi
tions in ascending order of salary?
SELECT RN,ENAME,JOB,SAL
FROM (SELECT EMPNO,ENAME,JOB,SAL,ROW_NUMBER() OVER(ORDER BY SAL) RN FROM EMP) E
WHERE RN%2=1
Display ename,job,sal of all those employees whose row positions are at EVEN pos
itions in ascending order of salary?
SELECT RN,ENAME,JOB,SAL
FROM (SELECT EMPNO,ENAME,JOB,SAL,ROW_NUMBER() OVER(ORDER BY SAL) RN FROM EMP) E
WHERE RN%2=0
Display ename,job,sal of all those employees w.r.to every 4th row in ascending o
rder of salary?
SELECT RN,ENAME,JOB,SAL
FROM (SELECT EMPNO,ENAME,JOB,SAL,ROW_NUMBER() OVER(ORDER BY SAL) RN FROM EMP) E
WHERE RN%4=0

CREATING A NEW TABLE FROM EXISTING TABLE:

A new table when gets created from existing table


it will allow to copy meta data + actual data or it supports to
copy only meta data.
To copy only meta data, it is must that condition
at where clause should be false.
When new table is created from existing table,
it does not copy the constraints of source table.
If column aliases or derived columns are specified
in a query then they become original columns in a target table.

SELECT * INTO E1 FROM EMP


SELECT * INTO E2 FROM EMP WHERE 1=2
SELECT EMPNO,ENAME,JOB,SAL,DEPTNO INTO E3 FROM EMP
SELECT EMPNO,ENAME,JOB,DEPTNO INTO E4 FROM EMP WHERE DEPTNO=30
SELECT EMPNO,ENAME,JOB,SAL,SAL*12 ASAL,SAL*8/100 TAX INTO E5 FROM EMP
SELECT EMPNO ECODE,ENAME EN,SAL PAY,DEPTNO DNO INTO E6 FROM EMP WHERE DEPTNO=10
SELECT * FROM E1
ALTER TABLE E1 ADD CONSTRAINT C1 PRIMARY KEY(EMPNO)
ALTER TABLE E1 ADD CONSTRAINT C2 UNIQUE(ENAME)
ALTER TABLE E1 ADD CONSTRAINT C3 CHECK(SAL BETWEEN 800 AND 8000)
SELECT * INTO E7 FROM E1
SP_HELP E7
CREATING TEMPORARY TABLES:
These tables are created for temporary in TempDB system database.
These tables will allow to perform operations similar to
user defined tables.
These tables will be deleted automatically whenever a user
comes out of SQL Server.
These tables are classified into 2 types.
1.
It
2.
It

Local Temporary Table : It works at single connection.


is represented by #
Global Temporary Table : It works at multiple connections.
is represented by ##

These tables are found at TempDB System database, at Temporary Tables.


Examples:
CREATE TABLE #STUD
(RNO INT,SNAME VARCHAR(12))
INSERT #STUD VALUES(1,'X')
INSERT #STUD VALUES(2,'Y')
SELECT * FROM #STUD
CREATE TABLE ##STUD1
(RNO INT,SNAME VARCHAR(12))
INSERT ##STUD1 VALUES(1,'A')
INSERT ##STUD1 VALUES(2,'B')

SELECT * FROM ##STUD1


DROP TABLE #STUD
DROP TABLE ##STUD1
Table variables:
DECLARE @Table TABLE(
name varchar(30) NOT NULL,
location varchar(30) NOT NULL
);
insert @Table values('guna','hyd')
select * from @table

How to create user define type:


EXEC sp_addtype telephone, 'varchar(24)', 'NOT NULL'
EXEC sp_addtype fax, 'varchar(24)', 'NULL'
CREATE TABLE TELE(NAME VARCHAR(20),NO TELEPHONE)
SP_HELP 'TELE'
How to drop user defined type:
USE master
EXEC sp_droptype 'telephone'
STYLES OF DISPLAYING THE OUTPUT
In SQL Server, we can display the out in two different styles, this we can achi
eve through
1.
2.

ORDER BY CLAUSE
XML Format

1. ORDER BY Clause:
It is used to display the table data in sorted order. The order may be either as
cending (or) descending order depending on the specified column. it always appea
rs at the and of select statement
it always appears at the and of select statement
Syntax:
SELECT {*/Columns List} FROM TABLE NAME [WHERE CONDITION]
ORDER BY COLUMN NAME {ASC/DESC}
The default order is ascending order. It means if we does not specify any specif
ic order then it automatically takes ascending order.
E.g.: W.A.Q to display employ details in ascending order based on their departme
nt numbers (DEPTNO).
SELECT * FROM EMP ORDER BY DEPTNO ASC
E.g.: W.A.Q to display employ details in descending order based on their employ
numbers (EMPNO).

SELECT * FROM EMP ORDER BY EMPNO DESC


E.g.: W.A.Q to display employ details in descending order based on their salarie
s (SAL)
SELECT * FROM EMP ORDER BY SAL DESC
E.g.: W.A.Q to display employ names and their salaries in descending order based
on their salaries (SAL).
SELECT ENAME, SAL FROM EMP ORDER BY SAL DESC
E.g.: W.A.Q to display 10th department employs in ascending order based on their
employ names (ENAME)
SELECT * FROM EMP WHERE DEPTNO=10 ORDER BY ENAME

3.

XML Format

It is new feature in SQL Server 2005 version which will display the table data i
n
XML format which in between open tag < and closed tag /> .
This format basically useful to the .Net developers
Syntax : SELECT {*/ Columns list} FROM TABLENAME FOR XML AUTO
Ex: SELECT * FROM EMP FOR XML AUTO
The above select statement will generate a file preceded by xml, if you click on
that file then automatically emp table data will be converted into XML format
NORMALIZATION:
-------------It is a process of splitting a single table into
2 or more sub tables to avoid redundancy and promote integrity.
OR
It is a process of deciding number of
tables required in a database,
columns in each table and relationships
among the tables is known as Normalization.
Noramlization is used to store the data in simple forms.
Advantages of Normalization:
1.
2.
3.
4.

Minimizes Redundancy
Reduces Complexity
Easy Maintainance
Making tables ready to perform joins and sub queries.

A table can be normalized in different ways often called Normal Forms;


Real form

1. First Normal Form (1NF)


2. Second Normal Form (2NF)
3. Third Normal Form (3NF)
Ideal form
4.Fourth normal form
5.Fifth normal form
6.Sixth normal form
7.Seventh normal form
insert/update/delete
delete from invoice where part2=nut
1. First Normal Form (1NF):
Tables are said to be in 1st Normal form
only when it satisfies the following rules;
i. Isolate repeating groups to other table by adding a common column.
ii. Every Column should be atomic(very small).
2. Second Normal Form (2NF):
---------------------------i. Tables should be in 1NF.
ii. All Non key columns should be made dependent on whole key
but not part of a key.

3. Third Normal Form (3NF)


i. Tables should be in 2NF.
ii. No Transitive Dependency.
dept
deptno
10
20
30
40

dname
admin
per
it
sys

loc
che
hyd
hyd
che

key and non key cols


--------------------Key is a column in a table on which condition applied to reterive the data or ma
nipulation.
Types of key:
-----------1.primary key
2.unique key
3.candidate key
4.alternate key
5.foreign key

6.Composite primary key

Boyce -codd normal forms:


1.In a Relation R, if we have multiple candidate key in that if we have multiple
composite primary key combination should not overlap.
overlap:
1.c.p.k combinations should not have a common field.
2.individual candidate keys should not be common in c.p.k combination.

DATABASE OBJECT:
----------------1.VIEW OBJECT
2.INDEX OBJECT
3.SYNONYM OBJECT
4.TABLE OBJECT
5.STORED PROCEDURE OBJECT
6.STORED FUNCTION OBJECT
7.STORED TRIGGER OBJECT OR DATABASE OBJECT.
VIEWS:
---------A View is nothing but an image table or virtual table,
which is created for a base table. A view can be created by
taking all values from the base table or by taking only selected values from bas
e table. There are two types views available in SQL Server.
1.

Simple Views(Updateable view)

2.

Complex Views (Non -Updateable View)

Note: If we perform any modifications in base table, then those modifications au


tomatically effected in view and vice-versa.
1.Simple Views: Creating View by taking only one single base table.
Syntax:
CREATE VIEW VIEWNAME [WITH ENCRYPTION]
[WITH SCHEMABINDING]
AS SELECT * FROM TABLENAME [WHERE CONDITION]
[WITH CHECK OPTION]
E.g.:
CREATE VIEW V1 AS SELECT * FROM EMP

INSERT INTO V1 VALUES (55, RAVI , 10000,10)


The above insert statement inserts the values into base table EMP as well as int
o view V1.
E.g.:
CREATE VIEW V2 AS SELECT * FROM EMP WHERE DEPTNO=10
INSERT INTO V2 VALUES (66, BABBU , 25000,10)
The above insert statement inserts the values into base table EMP as well as int
o view
V2.
INSERT INTO V2 VALUES (77, AMAR , 15000, 20)
The above insert statement inserts the values into only base table EMP but not i
nto view
V2 because according to the definition of V2 user supplied values are invalid va
lues. It means invalid values are inserting into base table EMP. To stop this ki
nd of operations we have to create the view with WITH CHECK OPTION .
E.g.:
CREATE VIEW V3 AS SELECT * FROM EMP WHERE DEPTNO=10
WITH CHECK OPTION
INSERT INTO V3 VALUES (88, TEJA , 25000,20)
The above insert statement cannot inserts the values into base table EMP as well
as into view V3.

SP_HELPTEXT: This stored procedure is used to display the definition of a specif


ic view.
Syntax: SP_HELPTEXT
VIEWNAME
E.g.: SP_HELPTEXT
V1
Output: CREATE VIEW V1 AS SELECT * FROM EMP
WITH ENCRYPTION: Once we create any view with WITH ENCRYPTION then we cannot find
the definition of that particular view using SP_HELPTEXT stored procedure becaus
e this encryption option hides the definition.
E.g.:
CREATE VIEW V4 WITH ENCRYPTION
AS SELECT * FROM EMP WHERE DEPTNO=20
SP_HELPTEXT V4
Output :The text for object v4 is encrypted
To decrypt the definition of view V4 we have to follow the below approach
1.
Replace CREATE with ALTER
2.
Remove WITH ENCRYPTION keyword
3.
Select the query and press F5.
E.g.:
ALTER VIEW V4
AS SELECT * FROM EMP WHERE DEPTNO=20
SP_HELPTEXT V4

CREATE VIEW V4
AS SELECT * FROM EMP WHERE DEPTNO=20
2.Complex Views:
Creating View by taking multiple base tables.
Ex:
CREATE VIEW EMP_DEPT_VIEW
AS SELECT EMP.EMPNO, EMP.ENAME, DEPT.DEPTNO, DEPT.DNAME
FROM EMP, DEPT WHERE EMP.DEPTNO=DEPT.DEPTNO

Syntax To Create view based on another views:


SQL SERVER enables users to create views based on another view.
We can create view based on another view up to 32 levels
Syntax:
CREATE VIEW VIEWNAME [WITH ENCRYPTION][with scehmabinding]
AS SELECT * FROM VIEWNAME [WHERE CONDITION]
[WITH CHECK OPTION]
E.g.: CREATE VIEW V5 AS SELECT * FROM V1 WHERE DEPTNO=10
Syntax To Drop the Views:
DROP VIEW VIEWNAME [ N]
E.g.: DROP VIEW V1, V2, V3, V4, V5
Schema Binding :
a. when view created by schemabinding then view becomes dependent object on base
table.
b. The base table cannot be dropped without dropping view.
c. When schemabinding is used then tablename prefixed by username/schemaname.
ex:
create view v8 with schemabinding
as select empno,ename,sal,job from dbo.emp;
ex: drop table emp
Invalid , because view is dependent object so we first drop the view after t
hat table.

Advantages of view:
1. To hide the complexity of the underlying database schema, or customize the
data and schema for a set of users.
2. Restrict access to specific rows in a table
3. Restrict access to specific columns in a table
4. Join columns from multiple tables and present them as though they are part o
f a single table
5 Present aggregate information (such as the results of the COUNT function)

VIEW OBJECT IS USED TO CREATE THE VIRTUAL TABLE.


CREATE VIEW <VIEWNAME> AS SELECT * FROM <TABLENAME>
CREATE
SELECT
CREATE
SELECT
SELECT

VIEW V1 AS SELECT * FROM EMP


* FROM V1
VIEW V2 AS SELECT * FROM EMP1 WHERE ENO>=103
* FROM V2
* FROM INFORMATION_SCHEMA.VIEWS

CREATE VIEW V3 AS SELECT SUM(SALARY) "TOTAL" FROM EMP


SELECT * FROM V3
SELECT * FROM INFORMATION_SCHEMA.VIEWS
DROP VIEW V1
SELECT * FROM V1
master
master
NONE
master
NONE

dbo
dbo
NO
dbo
NO

V1
V2

CREATE VIEW V1 AS SELECT * FROM EMP


NONE
NO
CREATE VIEW V2 AS SELECT * FROM EMP1 WHERE ENO>=103

V3

CREATE VIEW V3 AS SELECT SUM(SALARY) "TOTAL" FROM EMP

SYNONYM OBJECT:
SYNONYM OBJECT IS USED TO CREATE THE permanent ALIAS NAME for single base table.
IT IS USED TO HIDE THE ORIGINAL NAME OF AN OBJECT.
IT IS USED TO CREATE THE SECURITY OF THE TABLE.
it supports DML AND DQL OPERATIONS.(select,insert,update,delete)
Note if any changes in the synonym automatically reflected into base table and v
ice versa.
organization_master om

SYNTAX:
CREATE SYNONYM <SYNONYMNAME> FOR <TABLENAME>
SELECT
CREATE
SELECT
DELETE

* FROM EMP
SYNONYM S1 FOR EMP
* FROM S1
FROM S1 WHERE ENO=101

DELETE FROM S1 WHERE ENO=101


DROP SYNONYM S1
SELECT * FROM S1
select * from sys.synonyms
where base_object_name='[emp]'
create
create
select
select
select

synonym fm for fuzzylookupmatchindex


synonym fm1 for fuzzylookupmatchindex
* from fm
* from fm1
* from sys.synonyms where base_object_name='[fuzzylookupmatchindex]'

SELECT * FROM INFORMATION_SCHEMA.VIEWS


DIFFERENCE BETWEEN VIEW AND SYNONYM:
VIEW
1.VIEW IS A SUBSET OF TABLE
2.VIEW CAN BE BASED ON MORE
THAN ONE TABLE

SYNONYM
1.SYNONYM IS A MIRROR OF A TABLE.
2.SYNONYM IS ALWAYS BASED ON
ONLY ONE TABLE.

INDEXES
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 is always a time
consuming process or it leads to wastage of time.
When data is searched with sequential search technique,
first it arranges the data in ascending order of that column and
then starts searching. Wherever it finds the value,
it stops the searching process.
Again and again sorting 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 and index always stores the d
ata in ascending order for permanent.

When search operation is made first it searches for the data in a relate
d index and then from there it will transfer the control to a database.
A table can be associated with 250 Indexes.(sqlserver 2005)
1000 index(sqlserver 2008)
1 clustered index,249 non clustered index.
1 clustered index ,999 non clustered index.
Indexing is classified into the following types;
1. Clustered Index
2. Non Clustered Index
3. Unique Index
SYNTAX:
CREATE [UNIQUE]/[CLUSTERED]/[NONCLUSTERED] INDEX index_name
ON TABLE_NAME(COL1[,COL2,COL3,.......])
When index is created on multiple columns, it is called Composite Index.
I) Clustered Index:
* Clustered index will alter the physical representation of rows in a table.
* A table can have only 1 clustered index.
* It will always arrange the data in sorted order.
* Data Pages and Index pages will be stored at one level.
* This index should be created for a column where more than 1
search value is available.
eno
110
101
105
102
130
102
103
clustered index
dat index
101-1
102-2
102-3
103-4
105-5
110-6
130-7
index page - 8kb
1500
0-750

750-1500

200
500 records reorganize /rebuild
alter index i1 on emp(empno) reorganize/rebuild
reoraganize only exeucted in online
rebuild only executed in offline
5-30% fragementation - reoraganize
above 30% - rebuild
in sqlserver 2005 - 250 index
1-clustered index
249 - nonclusted index
in sqlserver 2008 -1000 index
1 -clustered index
999 - nonclustered index
by default index : nonclustered index
How to check fragmentation on sqlserver 2008?
* Fragmentation is a "natural process" in the db life cycles.
* if the db is frequently updated via insert,update,delete statement we can expe
ct it to become fragmeted over the time.
* There are two types of fragmentation?
1 Internal

2.External

* Internal fragmentation is the result of index pages taking up more space than
needed.
* External fragmentation occurs when the pages are not continuous on the index.
* sqlserver 2008 introduces a new DMV (Dynamic management view).
* sys.dm_db_index_physical_stats
* DBCC SHOWCONTIG
EX1:
use peers
go
dbcc showcontig
go
ex2:
select OBJECT_ID,index_id,avg_fragmentation_in_percent,
page_count from sys.dm_db_index_physical_stats(db_id('gunasekar'),object_id('emp
'),
null,null,null)

null - index id
null - partition no
null - mode
* In order to reduce the fragmentation
* we have to reorganize or rebuild the indexes.
* Heavily fragmentated index (above 30%)=> rebuild
* Moderate fragmented index ( 5 to 30 %) => reorganize
* Reorganize statement is always executed online.
* Rebuild statement is always executed in offline.
syntax:
alter index i1 on emp rebuild / reorganize
Update stats: Whenever insert,update,delete by default stats created.
sp_updatestats
* updatestats ensures that queries compile with up-to-date statistics.
* updates query optimization statistics on a table or indexed view.
* In some cases we can improve query performance by using update statistics.
* sp_updatestats to update statistics more frequently than the default updates.
* update statistics causes query to recompile.
* update statistics can use tempdb to sort the sample rows for building statisti
cs.

index_page
object_id index_id avg_fragmentation_in_percent page_count
Example:
CREATE CLUSTERED INDEX i1 ON EMP(EMPNO)
0- 30 % reorgainze ( on line rebuild)

1000 500

>30% rebuild (offline rebuild)


II) Non Clustered Index:
This index will not alter the physical representation of rows in a table.
A table can have 249 Non clustered indexes.(sqlserver 2005)
A table can have 999 Non Clustered indexes(sqlserver 2008)
Data is not arranged in order.

It is a default index created.


Data pages and Index pages are stored at different levels.
data index
110
- 5
101
- 2
102
- 3
100
- 1
105
- 4
Example:
CREATE NONCLUSTERED INDEX i2 ON EMP(ENAME)
CREATE INDEX i3 ON EMP(JOB)
III) UNIQUE INDEX:
This index can be created only on those columns which contains
unique data.This index is automatically created
when unique constraint or primary key is created on a column.
Example:
CREATE UNIQUE INDEX i4 ON EMP(EMPNO)
NOTE:
SQL Server will automatically create an index for 2 constraints,
Primary key and unique.
TO REBUILD AN INDEX:
SYNTAX:
ALTER INDEX index_name ON object_name REBUILD/REORAGANIZE
EXAMPLE:
ALTER INDEX I1 ON emp10 REBUILD
TO DROP AN INDEX:
SYNTAX:
DROP INDEX table_name.index_name
EXAMPLE:
DROP INDEX Emp10.I1
TO VIEW THE INFORMATION ABOUT INDEXES:
SP_HELPINDEX 'table_name'
This predefined procedure will display all the
indexes which are created on a table.
SP_HELPINDEX 'EMP'

How many columns are availabe in each and every table?


select table_name,COUNT(*) no_of_cols from INFORMATION_SCHEMA.COLUMNS
group by table_name
how many deptno columns available in the database?
select COUNT(name) from sys.columns
where name='DEPTNO'
BACKUP AND RESTORE DATABASE:
1.TO TAKE BACKUP OF THE DATABASE.

backup
BACKUPS :
* Due to H/W problem or S/W problem database may not be
accessible so for every db backup has to be maintained.
* Backup media
Storage device [Hard disk or Tape]
*Backup File :
Physical locations on backup media [extension name .bak]
* Backup Device :
A logical Container which points to physical locations.
* Backupset
Combination of backup media/file/device is called backup set.
Preparing Backup Devices:
* A Backup device can store multiple backups of one or more
database [ Different types of backup also ]
*
*
*
*
*

open object Explorer


connect to the database engine
select server objects
select backup devices
Right click new backup device
device name='test device'
destination file = 'c:\demo.bak'
Click ok

Types of Backups :
Sqlserver supports 4 types of backups
1.Full backup [default ]
2.Differential backup
3.Transactional backup

4.File and FileGroup backup


Note:
* First Backup for every database is fullBackup.
* Every day total objects will take backup.
* Recommended option is over write all existing backups.

1.FULL BACKUP
2.INCREMENTAL BACKUP
3.DIFFERENTIAL BACKUP
MON

TUE

WED

THU

FRI

SAT

SUN

INC

INC

INC

INC

INC

FULL

DIFF

FULL

BACKUP :
SYNTAX:
BACKUP DATABASE <DATABASE_NAME> TO DISK='c:\mydata\back1.bak'
BACKUP DATABASE mydbtest to DISK='C:\MYDATA\BACK1.BAK'

RESTORE DATABASE VIKRAM FROM DISK='C:\MYDATA\GUNA.BAK'


Bulk insert commands:
BULK INSERT PEERS.DBO.DEPT1
FROM 'C:\CUST.TXT'
WITH
(
FIELDTERMINATOR =',',
ROWTERMINATOR ='\n'
)
Bulk copy program:
The bcp utility (Bcp.exe) is a command-line tool that uses the Bulk Copy Program
(BCP) API.
The bcp utility performs the following tasks:
Bulk exports data from a SQL Server table into a data file.
Bulk exports data from a query.
Bulk imports data from a data file into a SQL Server table.

Exporting
ex:
c:\>bcp PEERS.DBO.EMP out C:\CUST.TXT -T -c
-T - Trusted connection If
you need to specify U and

T is not specified,
P to successfully log in.

-c Performs the operation using a character data type. This option does not pro
mpt for each field; it uses char as the storage type, without prefixes and with
\t (tab character) as the field separator and \n (newline character) as the row
terminator
Importing
bcp peers.dbo.emp in c:\cust.txt -T -c
--merge command
merge into employee1 as t
using employee s
on(s.empno=t.empno)
when matched then
update set t.ename=s.ename
when not matched by target then
insert values(s.empno,s.ename)
when not matched by source then
delete;
Where are SQL server users names and passwords are stored in sql server?
They get stored in master db in the sysxlogins table.
-- pivot
select 'total_salary' as dept_num,[10],[20],[30]
from (select deptno ,sal from emp) as s
pivot
(
sum(sal) for deptno in([10],[20],[30])) as t
--GROUPING SETS
select job,deptno,SUM(sal)
from emp
group by job,DEPTNO with rollup
select job,deptno,SUM(sal)
from emp
group by job,DEPTNO with CUBE
-- sparse columns
create table sparse_table
(
empno int sparse null,

ename varchar(10)
)
create table test_table
(
a date,
b time
)
select * from test_table
insert into test_table values('2011-01-01','01:50:50:250')
sp_help test_table

common table expression


The recursive CTE structure must contain at least one anchor member and one recu
rsive member. The following pseudocode shows the components of a simple recursiv
e CTE that contains a single anchor member and single recursive member.
WITH cte_name ( column_name [,...n] )
AS
(
CTE_query_definition

- Anchor member is defined.

UNION ALL
CTE_query_definition - Recursive member is defined referencing cte_name.
)
-- Statement using the CTE
SELECT *
FROM cte_name
The semantics of the recursive execution is as follows:
Split the CTE expression into anchor and recursive members.
Run the anchor member(s) creating the first invocation or base result set (T0).
Run the recursive member(s) with Ti as an input and Ti+1 as an output.
Repeat step 3 until an empty set is returned.
Return the result set. This is a UNION ALL of T0 to Tn.
example :

with xx(ename,eno)
as
(select ename,eno from EMP1)
select * from xx

USE peersnew
GO
-- Define the CTE expression name and column list.
WITH Sales_CTE (empno,ename,doj)
AS
-- Define the CTE query.
(
SELECT empno,ename,YEAR(hiredate) doj
FROM emp
)
-- Define the outer query referencing the CTE name.
SELECT empno, COUNT(empno) AS Total, doj
FROM Sales_CTE
GROUP BY doj,empno
ORDER BY doj,empno
GO
COMPUTE FUNCTION:
1.FIND TOTAL SAL PAID TO EMPLOYEES WHILE DISPLAYING COMPLETE DETAILS OF EMPLOYEE
SELECT * FROM EMP COMPUTE SUM(SAL),AVG(SAL),MAX(SAL),MIN(SAL),COUNT(SAL)
2.FIND TOTAL SAL PAID TO EMPLOYEES DEPARTMENT WISE WHILE DISPLAYING
COMPLETE DETAILS OF EMPLOYEES.
SELECT * FROM EMP ORDER BY DEPTNO COMPUTE SUM(SAL) BY DEPTNO
3.FIND NO.OF EMPLOYEES AND HIGHEST AND LOWEST SALARIES PAID TO EMPLOYEES
JOBWISE WHILE DISPLAYING COMPLETE DETAILS OF EMPLOYEE
SELECT * FROM EMP ORDER BY JOB COMPUTE COUNT(SAL),MAX(SAL),MIN(SAL) BY JOB
OVER(PARTITION BY)
COMPUTE BY DISPLAYS THE RESULT OF AGGREGATE ONLY ONES AT THE END OF THE GROUP
BUT OVER() FUNCTION DISPLAYS AGGREATES WITH EVERY ROW IN THE GROUP.
1.FIND THE TOTAL SAL PAID TO EMPLOYEES WHILE DISPLAYING COMPLETE DETAILS OF EMPL
OYEES
SELECT *,SUM(SAL),OVER(PARTITION BY DEPTNO) FROM EMP
2. FIND TOTAL NO.OF EMPLOYEES HIGHEST,LOWEST SAL PAID TO EMPLOYEES, JOBWISE WILL
DISPLAYING COMPLETE DETAILS OF EMPLOYEES.
SELECT *,COUNT(SAL) OVER(PARTITION BY JOB),
MAX(SAL) OVER(PARTITION BY JOB),
MIN(SAL) OVER(PARTITION BY JOB)

FROM EMP
sqlserver
1.SQL(non procedural language)
2.TSQL(Procedural language)

(TRANSACT SQL)
T-SQL deals with set of statements that are
block and submitted to server at once for execution.

grouped in the form of a

T-SQL (Transact-SQL) is a set of programming Language including transaction cont


rol, exception and error handling, row processing, control structure and declare
d variables.
Microsoft's SQL Server and Sybase's SQL server support T-SQL statements.
select * from emp
Difference between SQL and T-SQL
"SQL is non-procedural language
T-SQL is a procedural language
SQL was developed by IBM.
T-SQL was developed by Microsoft.
T-SQL supports to submit a block to
Server for execution in 2 ways;
1. Anonymous Block : It supports to store a block in .sql file
2. Stored Block
: It stores the block in database server.
a) Stored Procedures
b) Stored Functions
c) Stored Triggers/Database Triggers

Global Variables:
These variables
These variables
These variables
operations performed by
These variables

are provided by software.


cant be used to initialize the value manually.
will be stored with the data automatically based on the
SQL statements.
are preceeded by @@.

1. @@SERVERNAME : Returns name of the server


SELECT @@SERVERNAME

2. @@SERVICENAME : Returns name of the service(instance name)


SELECT @@SERVICENAME
3. @@VERSION : Returns version of SQL Server
SELECT @@VERSION
4. @@ROWCOUNT : Returns number of rows affected by last
executed SQL statement.
SELECT @@ROWCOUNT
5. @@ERROR : Returns 0 if there is no errors in the
last executed SQL statement OR returns Error number.
SELECT @@ERROR
SELECT @@IDENTITY
SELECT @@FETCH_STATUS

Local Variables:
These variables are created by a user.
These variables are provided with memory for temporary, hence they are c
alled as Buffer Variables.
These variables should be declared before they are used.
These variables will allow to store only 1 value.
These variables will be preceeded by @.
How to declare the variable?
SYNTAX:
DECLARE @VAR1 DATATYPE1,@VAR2 DATATYPE2,@VAR3 DATATYPE3,.......
EX:
DECLARE @A INT,@B VARCHAR(20),@C DATETIME
HOW TO ASSING A VALUE?
SYNTAX:
SET
EX:
SET
SET
SET

@VAR=VALUE
@A=100
@B=200
@C=@A+@B

HOW TO DISPLY THE OUTPUT ?


PRINT @VAR/VALUE

Syntax:
DECLARE @var1 data_type[(size)],.......
SET : These command is used to set a value for a variable.
Syntax: SET @var1=value/expr/function
PRINT : It is an output statement of T-SQL,
which performs 2 tasks;
1. Displays Messages
2. Displays Memory Values
Syntax:
PRINT 'MESSAGE'/@VARIABLES
DIFFERENCE BETWEEN ANONYMOUS BLOCKS AND NAMED BLOCKS
ANONYMOUS
1.BLOCKS WITHOUT NAME

NAMED/STORED
1.BLOCKS WITH NAME

2.ANNONYMOUS BLOCKS ARE


2. BUT THE NAMED BLOCKS ARE SAVED IN
SAVED IN "OPERATING SYSTEM FILE"
"DATABASESERVER".
3.THESE BLOCKS ARE NOT SECURED. 3.BUT NAMED BLOCKS ARE SECURED.
4.THESE BLOCKS CAN'T BE REUSED. 4.BUT NAMED BLOCKS CAN BE REUSED.
5.EVERY TIME COMPILE & EXECUTED.5.NAMED BLOCKS ARE ONE TIME
COMPILATION AND EVERY TIME EXECUTION.
ANONYMOUS BLOCKS:
1.DECLARTION STATEMENT:
DECLARE @VARNAME DATATYPE
EX:
DECLARE @A INT,@B INT,@C DATETIME
2.SET STATEMENT:
IT IS USED TO ASSIGN VALUE TO A VARIABLE

SET
SET
SET
SET

@VARIABLENAME=VALUE
@A=10
@B=20
@NAME='ARUNA'

3.PRINT STATEMENT
PRINT 'VALUE'
PRINT '@VARIABLE'
WRITE A TSQL PROGRAM TO CALCULATE THE ADDITION OF TWO NUMBERS
DECLARE @A INT,@B INT,@C INT
SET @A=100
SET @B=200
SET @C=@A + @B
PRINT 'ADD TWO VALUES=' + CAST(@C AS VARCHAR)
ADD TWO VALUES=300
WRITE A TSQL PROGRAM TO CALCULATE THE ALL ARITHMETICAL OPERATORS
DECLARE @A INT,@B INT,@C INT,@D
SET @A=100
SET @B=20
SET @C=@A + @B
SET @D=@A - @B
SET @E=@A * @B
SET @F=@A / @B * 100
PRINT 'ADD TWO VALUES='+CAST(@C
PRINT 'SUB TWO VALUES='+CAST(@D
PRINT 'MUL TWO VALUES='+CAST(@E
PRINT 'QUTIENT VALUES='+CAST(@F
ADD TWO
SUB TWO
MUL TWO
QUTIENT

INT,@E INT,@F INT

AS
AS
AS
AS

VARCHAR)
VARCHAR)
VARCHAR)
VARCHAR)

VALUES=120
VALUES=80
VALUES=2000
VALUES=5

DECLARE @A INT,@B INT,@C INT,@D INT,@E INT,


@F INT,@G INT
SELECT @A=100,@B=20,@C=@A+@B,@D=@A-@B,@E=@A*@B,@F=@A/@B,@G=@A%@B
PRINT 'ADDITION='+CAST(@C AS VARCHAR)
PRINT 'SUBTRACTION='+CAST(@D AS VARCHAR)
PRINT 'MULTIPLICATION='+CAST(@E AS VARCHAR)
PRINT 'QUOTIENT='+CAST(@F AS VARCHAR)
PRINT 'REMAINDER='+CAST(@G AS VARCHAR)

CONTROL STRUCTURE:
* Control structrure refers to the order in which the various instruction in a p
rograms are to be executed.
* The other name for control sturcture "flow of control"
control structrue classified into three types:

1.SEQUENTIAL CONTROL STRUCTURE - ONE BY ONE


2.SELECTIVE CONTROL STURCUTRE - TO ALLOWS TO CREATE THE CONDITION
3.REPETATIVE CONTROL STRUCUTRE - TO ALLOWS TO CREATE THE LOOP
SELECTIVE CONTROL STRUCTURE:
IF STATEMENT
IF ELSE STATEMENT
IF ELSE IF STATEMENT
NESTED IF STATEMENT
case statement
IF STATEMENT SYNTAX:
1.IF CONDTION
BEGIN
STATEMENT1
STATEMENT2
END

2.IF CONDITION
BEGIN
STATEMENT1
END
ELSE
BEGIN
STATEMENT2
END
or
IF CONDITION
STATEMENT1
ELSE
STATEMENT2
3.IF CONDITION1
BEGIN
STATEMENT1
END
ELSE IF CONDITION2
BEGIN
STATEMENT2
END
ELSE
BEGIN
STATEMENT3
END
4.CASE
WHEN 1
WHEN 2
WHEN 3

VARIABLE
THEN 'ST1'
THEN 'ST2'
THEN 'ST3'

ELSE
STX
END
DECLARE @Count int
SET @Count = 0
do_it_again:
IF @Count < 5
BEGIN
PRINT 'Hello World'
SET @Count = @Count + 1
END
IF @Count < 5
GOTO do_it_again

WRITE A TSQL PROGRAM TO FIND THE GIVEN YEAR IS LEAP OR NOT LEAP YEAR
DECLARE @Y INT
SET @Y=2012
IF @Y % 4 =0
BEGIN
PRINT 'THE GIVEN YEAR IS LEAP YEAR='+CAST(@Y AS VARCHAR)
END
ELSE
BEGIN
PRINT 'THE GIVEN YEAR IS NOT LEAP YEAR='+CAST(@Y AS VARCHAR)
END
if db_name() = 'master'
begin
Print 'We are in the Master Database'
Print ''
Print 'So be careful what you execute'
End
BIGGEST OF THREE NUMBERS:
DECLARE @A INT,@B INT,@C INT
SET @A=10000
SET @B=2000
SET @C=300
IF @A > @B AND @A > @C
PRINT 'A IS BIGGER='+CAST(@A AS VARCHAR)
ELSE IF @B > @C
PRINT 'B IS BIGGER='+CAST(@B AS VARCHAR)
ELSE
PRINT 'C IS BIGGER='+CAST(@C AS VARCHAR)
--WRITE A TSQL PROGRAM TO CONVERT THE NUMBER INTO DAY OF WEEK

1-sunday
2- monday
3- tuesday
4- wednesday
7- saturday
>7 invalid day
declare @d int
declare @res varchar(20)
set @d=5
select @res=
case @d
when 1 then 'sunday'
when 2 then 'monday'
when 3 then 'tuesday'
when 4 then 'Wednesday'
when 5 then 'Thursday'
when 6 then 'Friday'
when 7 then 'Saturday'
else 'invalid day'
end
print @res

SELECT TOP 10 ENO, Position =


CASE ENO % 10
WHEN 1 THEN 'First'
WHEN 2 THEN 'Second'
WHEN 3 THEN 'Third'
WHEN 4 THEN 'Fourth'
ELSE 'Something Else'
END
FROM Emp2

SYNTAX OF THE SELECT STATEMENT:


SELECT @VARIABLE=COL1,@VARIABLE=COL2... FROM <TABLENAME> WHERE<CONDITION>
SELECT @ENO=ENO,@ENAME=ENAME FROM EMP WHERE ENO=101

DECLARE @A INT,@B VARCHAR(20),@C INT,@D VARCHAR(20)


SET @A=102
SELECT @A=STUDENTID,@B=NAME,@C=MARKS,@D=GRADE FROM STUDENTS WHERE STUDENTID=@A
PRINT 'STUDENTID NAME MARKS GRADE'
PRINT CAST(@A AS VARCHAR)+' ' + @B+'
' + CAST(@C AS VARCHAR) + ' '+ @D

UDPATE THE SALARY


DECLARE @NO INT,@SAL INT
SET @NO=102
SET @SAL=2000
UPDATE EMP SET SALARY=SALARY+ @SAL WHERE ENO=@NO
SELECT * FROM EMP
DELETE THE RECORDS
DECLARE @NO INT
SET @NO=102
DELETE FROM EMP WHERE ENO=@NO
PRINT '1 ROW DELETED'
SELECT * FROM EMP
INSERTING RECORDS
DECLARE @NAME VARCHAR(20),@NO INT,@SAL INT
SET @NAME='GUNA'
SET @NO=104
SET @SAL=4500
INSERT INTO EMP VALUES(@NAME,@NO,@SAL)
SELECT * FROM EMP
REPETATIVE CONTROL STRUCTURE:
WHILE LOOP
WHILE CONDTION
BEGIN
STATEMENT1
STATEMENT2
END
DECLARE @I INT,@N INT
SET @I=1
SET @N=10
WHILE @I < = @N
BEGIN
PRINT CAST(@I AS VARCHAR)
SET @I= @I + 1
END

MULTIPLICATION TABLE:
1 X 15 = 15
2 X 15 = 30
3 X 15 =45

20 X 15 =300
DECLARE @I INT,@N INT,@R INT
SET @I=1
SET @N=15
WHILE @I < = 20
BEGIN
SET @R= @I * @N
PRINT CAST(@I AS VARCHAR) +'
ARCHAR)
SET @I= @I + 1
END

'+ CAST(@N AS VARCHAR)+'

'+CAST(@R AS V

CURSOR:
1.A CURSOR IS A POINTER TO RESULTSET WHICH CONTAINS SET OF RECORDS RETURN BY THE
SELECT STATEMENT.
2.USING THE CURSOR WE CAN PROCESS THE MULTIPLE RECORDS IN RESULTSET.
3.CURSOR WILL REDUCE NO.OF TRIPS TO DATABASE SERVER.
4.cursor memory alloted using "tempdb" database.
TO USE CURSOR FOLLOW BELOW STEPS:
1.DECLARE CURSOR
2.OPEN CURSOR
3.FETCH RECORDS FROM CURSOR
4.CLOSE CURSOR
5.DEALLOCATE CURSOR.
1.DECLARE THE CURSOR:
SYNTAX:
DECLARE <CURSORNAME> CURSOR[OPTIONS] FOR SELECT STATEMENT
EX:
DECLARE C1 CURSOR FOR SELECT * FROM EMP
2.OPEN CURSOR
OPEN <CURSORNAME>
OPEN C1
3.FETCH RECORDS FROM CURSOR
FETCH NEXT|PRIOR|FIRST|LAST|ABSOLUTE N | RELATIVE N FROM
<CURSORNAME> INTO <VARIABLE>
EX:
FETCH NEXT FROM C1 INTO @ENAME,@ENO,@SAL
4.CLOSE CURSOR
SYNTAX:
CLOSE <CURSORNAME>
CLOSE C1

5.DEALLOCATE CURSOR
SYNTAX:
DEALLOCATE <CURSORNAME>
DEALLOCATE C1
@@fetch_status either 0(true) or -1(false)
NOTE:
1. Any number of cursors can be created in a single program
but with unique names.
2. Global variable @@FETCH_STATUS plays an important role,
where it returns boolean value i.e. returns 0
if it makes a fetch operation successfull over a cursor
else returns -1.

WRITE A PROGRAM TO DISPLAY ALL EMPLOYEE NAMES AND SALARIES:


DECLARE C1 CURSOR FOR SELECT ENAME,SALARY FROM EMP
DECLARE @ENAME VARCHAR(20)
DECLARE @SAL INT
OPEN C1
FETCH NEXT FROM C1 INTO @ENAME,@SAL --START THE LOOP
WHILE(@@FETCH_STATUS=0)
BEGIN
PRINT @ENAME +'
'+CAST(@SAL AS VARCHAR)
FETCH NEXT FROM C1 INTO @ENAME,@SAL -- CONTINUE THE LOOP
END
CLOSE C1
DEALLOCATE C1
WRITE A TSQL PROGRAM TO DISPLAY ALL DEPT DETAILS FROM THE DEPT TABLE.
DECLARE @S1 INT,@S2 VARCHAR(13),@S3 VARCHAR(14)
DECLARE C1 CURSOR FOR SELECT * FROM DEPT
OPEN C1
FETCH NEXT FROM C1 INTO @S1,@S2,@S3 --START THE LOOP
WHILE (@@FETCH_STATUS=0)
BEGIN
PRINT CAST(@S1 AS VARCHAR)+' '+@S2+' '+@S3
FETCH NEXT FROM C1 INTO @S1,@S2,@S3 --CONTINUE THE LOOP
END
CLOSE C1
DEALLOCATE C1
WRITE A TSQL PROGRAM TO DISPALY ENAME AND DNAME
DECLARE @ENAME VARCHAR(20),@DNAME VARCHAR(20)
DECLARE C1 CURSOR FOR SELECT EMP.ENAME,

DEPT.DNAME FROM EMP,DEPT WHERE EMP.DEPTNO=


DEPT.DEPTNO
OPEN C1
FETCH NEXT FROM C1 INTO @ENAME,@DNAME
WHILE(@@FETCH_STATUS=0)
BEGIN
PRINT @ENAME+' '+@DNAME
FETCH NEXT FROM C1 INTO @ENAME,@DNAME
END
CLOSE C1
DEALLOCATE C1

STUDENT

RESULT

SNO SNAME S1 S2 S3

SNO STOT SAVG SRES

DECLARE C1 CURSOR
FOR SELECT SNO,S1,S2,S3 FROM STUDENT
DECLARE @SNO INT,@S1 INT,@S2 INT,@S3 INT
DECLARE @STOT INT ,@SAVG INT
DECLARE @SRES VARCHAR(4)
OPEN C1
FETCH NEXT FROM C1 INTO @SNO,@S1,@S2,@S3
WHILE (@@FETCH_STATUS=0)
BEGIN
SET @STOT=@S1+@S2+@S3
SET @SAVG=CEILING((@STOT)/3)
IF @S1 >35 AND @S2 >35 AND @S3 > 35
SET @SRES='PASS'
ELSE
SET @SRES='FAIL'
INSERT INTO RESULT VALUES(@SNO,@STOT,@SAVG,@SRES);
FETCH NEXT FROM C1 INTO @SNO,@S1,@S2,@S3
END
CLOSE C1
DEALLOCATE C1

SCROLL OPTION
NEXT - the default cursor fetch option.
FETCH NEXT returns the next row after the current row.
PRIOR - returns the prior row before the current row.
FIRST - returns the first row in the cursor.
LAST - returns the last row in the cursor.
ABSOLUTE N - returns the nth row in the cursor first position.
RELATIVE N - returns the nth row in the cursor current row.

EX:
DECLARE C1 CURSOR SCROLL
FOR SELECT ENAME FROM EMP
DELCARE @ENAME VARCHAR(20)
OPEN C1
FETCH FIRST FROM C1 INTO @ENAME
PRINT @ENAME
FETCH NEXT FROM C1 INTO @ENAME
PRINT @ENAME
FETCH ABSOLUTE 5 FROM C1 INTO @ENAME
PRINT @ENAME
FETCH RELATIVE 5 FROM C1 INTO @ENAME
PRINT @ENAME
FETCH LAST FROM C1 INTO @ENAME
PRINT @ENAME
FETCH PRIOR FROM C1 INTO @ENAME
PRINT @ENAME
CLOSE C1
DEALLOCATE C1
Types of Cursor:
1.Static cursor
2.Dynamic cursor (by default)
Static cursor:
* If the cursor is declared with static, any changes make to the base table chan
ges are not reflected to result set.
Dynamic cursor :
* If the cursor is declared with dynamic so any changes make to the base table a
utomatically reflected to result set.
declare @sal int
declare c1 cursor static/ dynamic for select sal from emp
where empno=7788
open c1
update EMP set SAL=SAL+1000 where EMPNO=7788
fetch next from c1 into @sal
print @sal
close c1
deallocate c1

UPDATE STUDENT SET STOT=S1+S2+S3,SAVG=


(S1+S2+S3)/3,SRES=
CASE
WHEN S1>=40 AND S2>=40 AND S3>=40 THEN 'PASS'
ELSE
'FAIL'
END
DROP TABLE STUDENT

COMPUTED COLUMN :
CREATE TABLE STUDENT(NAME VARCHAR(20),
SNO INT,
S1 INT,
S2 INT,
S3 INT,
STOT AS S1+S2+S3,
SAVG AS (S1+S2+S3)/3,
SRES AS CASE
WHEN S1>=40 AND S2>=40 AND S3>=40 THEN 'PASS'
ELSE
'FAIL'
END)

UPDATE STUDENT SET STOT=S1+S2+S3,


SAVG=(S1+S2+S3)/3,
SRES =
CASE
WHEN S1>=40 AND S2>=40 AND S3>=40 THEN 'PASS'
ELSE
'FAIL'
END
SELECT * FROM STUDENT
INSERT INTO STUDENT VALUES('CCC',103,89,90,23)
SELECT * FROM STUDENT
SELECT * FROM STUDENT
STUDENT
SNAME
XXX
YYY
ZZZ

SNO
101
102
103

RESULT
SNO
STOT

S1
89
67
78

S2
78
56
67

SAVG

SRES

S3
67
67
78

Advantage of Cursor:
1.Row-by-row operations:
2.Efficiency: The query optimizer automatically selects the
appropriate query plan, so the developer does not need to
design a complex algorithm to access the required data.
3.Adaptability: As data changes or indexes are added or
dropped, the query optimizer automatically adapts its
behavior by using alternative plans.

execution method:
1.compile the query.
2.identify the table/object
3.QEP is created.(query execution plan)
4.Lock the table
5.Querys are executed.
6.Results are displayed.
7.Realse the lock.

STRUCTURED EXCEPTION HANDLING:


In SQL Server 2008 exception handling is carried out using Strucuted Exc
eption, which supports to write 2 blocks.
1. TRY : It is used to monitor all those instructions
in which run time errors are expected.
2. CATCH : It is used to catch the thrown exceptions. This block is executed onl
y when a exception is raised.
Syntax:
BEGIN TRY
statements
END TRY
BEGIN CATCH
statements
END CATCH
Note:
Following are the functions is used to display information about errors.
ERROR_NUMBER() -returns the number of the error.
ERROR_STATE()
-returns the error state number.
ERROR_PROCEDURE()- returns the name of the stored procedure or trigger where the
error occurred.
ERROR_LINE()
- returns the line number inside the routine that caused the er
ror.
ERROR_MESSAGE() - returns the complete text of the error message.
Example 1:
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_STATE()
END CATCH
PRINT 'THANX'
EXAMPLE 2:
CREATE PROCEDURE PROC3
AS
SELECT * FROM EMP3
BEGIN TRY
EXECUTE PROC3
END TRY
BEGIN CATCH
SELECT
ERROR_NUMBER() as ErrorNumber,
ERROR_MESSAGE() as ErrorMessage;
END CATCH

Sub Programs:
It is a process of splitting a large application program into small modu
les or blocks. SQL Server supports to write a sub program based on the followin
g concepts;
1. Stored Procedures
2. Stored Functions
3. Stored Triggers
Advantages of Sub programs:
1. Provides security
2. It improves performance
3. Reduces Network Traffic
4. Readability gets increases
5. Code Reusability
6. Error Detection and modification is quite easy
7. Extensibility - It will allow a user to
increase or decrease the code.
Stored Procedures:
Procedure is a self contained program or predefined program, which does
not return value.
SQL server supports to work with the
following types of procedures;
i. Predefined Procedures (only db level functions)
sp_help

sp_helpdb
sp_spaceused
sp_renamedb
sp_rename
sp_helptext
ii. User Defined Procedures
iii.Extended_procedures (xp_)
xp_fixedrives (mail server and os level)

User Defined Procedures:


It is a stored block database object, which resides in database server.
It is a self contained program or predefined program which does not return value
.
It can be created with and without arguments.
Data can be sent to procedures to process it using Input Arguments and few value
s can be taken back to the main program using OUTPUT arguments.
A procedure can be set with 1024 Input and 1024 Output Arguments.
When a procedure is set with OUTPUT arguments then it is essential
that at sending argument OUTPUT should be specified.
Procedure set with input arguments will work for call by value and output argume
nts will work for call by reference.
Syntax:
CREATE PROC / PROCEDURE proc_name([list_of_args])
[WITH ENCRYPTION]
AS
BEGIN
[declaration block]
execution block
END
A Procedure can be executed in 2 ways;
1. using EXEC command
Syntax:
EXEC proc_name [list_of_args]
EXECUTE proc_name [list_of_args]
EXAMPLES:
1. Create a procedure with no arguments and retrieve the data of emp table?
CREATE PROC ERET

AS
BEGIN
SELECT * FROM EMP
END
EXEC ERET
2. Create a procedure with 2 input arguments and find sum of 2 values?
CREATE PROC ADDT(@A INT,@B INT)
AS
BEGIN
DECLARE @C INT
SET @C=@A+@B
PRINT 'SUM IS.....'+CAST(@C AS VARCHAR(5))
END
EXEC ADDT 17,38
DECLARE @X INT,@Y INT
SET @X=89
SET @Y=56
EXEC ADDT @X,@Y
3. Create a procedure with 2 input arguments and 1 output argument that finds su
m of 2 values?
CREATE PROC SUMT(@A INT,@B INT,@C INT OUTPUT)
AS
BEGIN
SET @C=@A+@B
END
DECLARE @X INT,@Y INT,@Z INT
SET @X=92
SET @Y=84
EXEC SUMT @X,@Y,@Z OUTPUT
PRINT 'ADDITION IS ....'+CAST(@Z AS VARCHAR(5))
4. Create a procedure that takes empno as input and displays ename,job,sal,deptn
o of that employee?
CREATE PROC ERET1(@ENO INT)
AS
BEGIN
SELECT ENAME,JOB,SAL,DEPTNO FROM EMP WHERE EMPNO=@ENO
END
EXEC ERET1 7788
EXEC ERET1 7369

OR
CREATE PROC ERET2(@ENO INT)
AS
BEGIN
DECLARE @EN VARCHAR(12),@J VARCHAR(14),@PAY INT,@DNO INT
SELECT @EN=ENAME,@J=JOB,@PAY=SAL,@DNO=DEPTNO FROM EMP WHERE EMPNO=@ENO
PRINT @ENO
PRINT @EN
PRINT @J
PRINT @PAY
PRINT @DNO
END
EXEC ERET2 7788
OR
CREATE PROC ERET3(@ENO INT,@EN VARCHAR(12) OUTPUT,@J VARCHAR(12) OUTPUT,@PAY INT
OUTPUT,@DNO INT OUTPUT)
AS
BEGIN
SELECT @EN=ENAME,@J=JOB,@PAY=SAL,@DNO=DEPTNO FROM EMP WHERE EMPNO=@ENO
END
DECLARE @EC INT,@N VARCHAR(12),@D VARCHAR(12),@P INT,@DC INT
SET @EC=7902
EXEC ERET3 @EC,@N OUTPUT,@D OUTPUT,@P OUTPUT,@DC OUTPUT
PRINT @EC
PRINT @N
PRINT @D
PRINT @P
PRINT @DC
SET NOCOUNT ON STATEMENT:
SET NOCOUNT ON statement into your stored procedures to stop the message indicat
ing the number of rows affected by a T-SQL statement.
5. Create a procedure to insert a new record into emp table for empno,ename,sal
and deptno by checking all validations?
EMPNO= NULL
EMPNO DUPLICATE VALUE
SAL > 800
DEPTNO : DEPT
CREATE PROC INSREC(@ENO INT,@EN VARCHAR(12),@PAY INT,@DNO INT)
AS
BEGIN
SET NOCOUNT ON
DECLARE @I INT,@J INT
SELECT @I=COUNT(*) FROM EMP WHERE EMPNO=@ENO
SELECT @J=COUNT(*) FROM DEPT WHERE DEPTNO=@DNO
IF @ENO IS NULL
PRINT 'CANT INSERT NULL VALUE INTO EMPNO'

ELSE
IF @I>0
PRINT 'EMPLOYEE ALREADY EXISTS'
ELSE
IF @J=0
PRINT 'INVALID DEPTNO'
ELSE
IF @PAY<800
PRINT 'INVALID PAY'
ELSE
BEGIN
BEGIN TRAN
INSERT EMP(EMPNO,ENAME,SAL,DEPTNO) VALUES(@ENO,@EN,@PAY,@DNO)
COMMIT
PRINT 'RECORD INSERTED SUCCESSFULLY'
END
END
EXEC INSREC 7788,'AHMED',2500,30 -- EMPLOYEE ALREADY EXISTS
EXEC INSREC NULL,'AHMED',2500,30 -- CANT INSERT NULL VALUE IN EMPNO
EXEC INSREC 1001,'AHMED',700,20 -- INVALID PAY
EXEC INSREC 1001,'AHMED',3400,80 -- INVALID DEPTNO
EXEC INSREC 1001,'AHMED',3400,30 -- Record inserted successfully
EXEC INSREC 1002,'HARISH',4500,20 -- Record inserted successfully
EXEC INSREC 1003,'RAJ',2300,30 -- Record inserted successfully

6. Create a procedure to Update the salary of employee if it is valid increment


of more than 500?
CREATE PROC 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

-- INVALID INCREMENT

EXEC UPDROW 2001,1200


EXEC UPDROW 7788,1000

-- EMPLOYEE DOES NOT EXIST


-- ROW UPDATED SUCCESSFULLY

7. Create a procedure to delete the rows from a table based on deptno?


CREATE PROC DELREC(@DNO INT)
AS
BEGIN
SET NOCOUNT ON
DECLARE @I INT,@J INT
SELECT @J=COUNT(*) FROM DEPT WHERE DEPTNO=@DNO
SELECT @I=COUNT(*) FROM EMP WHERE DEPTNO=@DNO
IF @J=0
PRINT 'INVALID DEPTNO'
ELSE
IF @I=0
PRINT 'EMPLOYEES DOES NOT EXIST'
ELSE
BEGIN
BEGIN TRAN
DELETE FROM EMP WHERE DEPTNO=@DNO
COMMIT
PRINT CAST(@I AS VARCHAR(5))+' ROWS ARE DELETED'
END
END
EXEC DELREC 10
EXEC DELREC 80
EXEC DELREC 10
8. Create a procedure that performs transactions related to bank for depostis, w
ithdrawls of amount with necessary validations.
CREATE TABLE BANK
(ACNO INT,AHN VARCHAR(12) CONSTRAINT ACNO_PK PRIMARY KEY,ADDRESS VARCHAR(15),BAL
INT)
INSERT
INSERT
INSERT
INSERT
INSERT

BANK
BANK
BANK
BANK
BANK

VALUES(1001,'HARI','AMRPT',12340)
VALUES(1007,'KIRAN','BHEL',12900)
VALUES(1002,'RAJ','ECIL',15400)
VALUES(1009,'KARAN','AMRPT',23800)
VALUES(1004,'SUNIL','ABIDS',34900)
BANK

ACNO
1001
1007
1002
1009
1004

AHN
HARI
KIRAN
RAJ
KARAN
SUNIL

ADDRESS
AMRPT
BHEL
ECIL
AMRPT
ABIDS

BAL
12340
12900
15400
23800
34900

CREATE TABLE TRANS


(ANO INT,TT VARCHAR(5),AMOUNT INT,DAT SMALLDATETIME)

TRANS
ANO

TT

AMOUNT

DAT

CREATE PROC BTRAN(@ACC INT,@TRTY VARCHAR(5),@AMT INT)


AS
BEGIN
SET NOCOUNT ON
DECLARE @I INT,@B INT
SELECT @I=COUNT(*) FROM BANK WHERE ACNO=@ACC
SELECT @B=BAL FROM BANK WHERE ACNO=@ACC
IF @I=0
PRINT 'INVALID ACCOUNT NUMBER'
ELSE
IF @TRTY='D'
BEGIN
BEGIN TRAN
INSERT TRANS VALUES(@ACC,@TRTY,@AMT,GETDATE())
UPDATE BANK SET BAL=BAL+@AMT WHERE ACNO=@ACC
COMMIT
PRINT 'ROW INSERTED AND UPDATED SUCCESSFULLY'
END
ELSE
BEGIN
IF @TRTY='W'
BEGIN
IF @AMT>@B
PRINT 'OVER DRAFT OF AMOUNT'
ELSE
IF @AMT>@B-500
PRINT 'INVALID TRANS - MIN BAL SHOULD BE 500'
ELSE
IF @AMT<100
PRINT 'INVALID AMOUNT'
ELSE
BEGIN
BEGIN TRAN
INSERT TRANS VALUES(@ACC,@TRTY,@AMT,GETDATE())
UPDATE BANK SET BAL=BAL-@AMT WHERE ACNO=@ACC
COMMIT
PRINT 'ROW INSERTED AND UPDATED SUCCESSFULLY'
END
END
ELSE
PRINT 'INVALID TRANSACTION TYPE'
END
END
7. Create a procedure to extract only 10 digit phone number?
create PROCEDURE P1(@A BIGINT)
AS
BEGIN
declare @result varchar(20)
set @result=RIGHT(cast(@a as varchar),10)
print @result
end

DYNAMIC QUERIES:
A query in 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.
select * from emp
7 steps :
1.compilation of the query
2.identify the table names
3.QEP is created.(Query Execution Plan)
4.tables are locked.
5.Queries are executed
6.Results are displayed
7.Relase the lock.

1. 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
2. Create a table using procedure with passing table names at runtime:
CREATE PROC CT(@TN VARCHAR(12))
AS
BEGIN
EXEC ('CREATE TABLE '+@TN+'(ENO INT,EN VARCHAR(12))')
END
EXEC CT E1
EXEC CT E2
3. Creating a table with table names, column names, data types dynamically?
CREATE PROC CT1(@TN VARCHAR(12),@COL VARCHAR(12),@DT VARCHAR(12))
AS
BEGIN
EXEC ('CREATE TABLE '+@TN+'('+@COL+' '+@DT+')')
END
EXEC CT1 'T1','ENO','INT'
EXEC CT1 'T2','RNO','SMALLINT'
4. Adding a new column in a table?
CREATE PROC AT1(@TN VARCHAR(12))
AS
BEGIN
EXEC ('ALTER TABLE '+@TN+' ADD NAME VARCHAR(12)')
END

EXEC AT1 T1
5. Altering the size of existing column:
CREATE PROC AT2(@TN VARCHAR(12))
AS
BEGIN
EXEC ('ALTER TABLE '+@TN+' ALTER COLUMN NAME VARCHAR(20)')
END
EXEC AT2 T1
6. Droping a table:
CREATE PROC DT(@TN VARCHAR(12))
AS
BEGIN
EXEC ('DROP TABLE '+@TN)
END
EXEC DT E1
EXEC DT E2
MODIFYING THE PROCEDURE:
ALTER PROC/PROCEDURE PROC_NAME([list_of_Args])
[WITH ENCRYPTION]
AS
BEGIN
STATEMENTS
END
DROPING THE PROCEDURE:
DROP PROC / PROCEDURE PROC_NAME
declare @a int,@b int,@c int,@d int
select @a=100,@b=20,@c=20,@d=@a*@b*@c
print @d

Here are some instruction when creating a store procedure to increase speed
Here are the some good tips when creating a store procedure
* Use SQL keyword in capital letters to increase readability.
* Use few possible variables to increase cache memory.
* Try to avoid dynamic queries if we are not using dynamic query
there is no recompilation of execution plan but on the other side

if we are using dynamic query every time we need recompile of plan.


* Use SET NOCOUNT ON this will helps us to get number of row effected without n
etwork traffic.

* In Select and Set use select to assign value to variable


it is much faster than multiple set statement.
* In CAST and CONVERT always try to use CAST
* Avoid Distinct and Order by clause.
These class needs extra space.
* Try to avoid cursor.
* Avoid correlated sub queries.
* Avoid select * into for large tables it locks the system objects.
* Avoid temporary tables because it will recompile the procedure.
* Use schema name with object name: The object name is qualified if used with sc
hema name. Schema name should be used with the stored procedure name and with al
l objects referenced inside the stored procedure. This help in directly finding
the complied plan instead of searching the objects in other possible schema.
Modify the procedure
alter procedure <procedure_name>(list of args)
as
begin
declaration statement
executable statement
end
To display all predefined, userdefined stored procedures:
SP_STORED_PROCEDURES
To display all the created user defined procedure names:
SELECT NAME FROM SYSOBJECTS WHERE XTYPE='P'
C = CHECK constraint
D = Default or DEFAULT constraint
F = FOREIGN KEY constraint
L = Log
P = Stored procedure
PK = PRIMARY KEY constraint
RF = Replication filter stored procedure
S = System table
TR = Trigger
U = User table
UQ = UNIQUE constraint
V = View
X = Extended stored procedure
FN = FUNCTION

To display the code of a user defined stored procedure:


SP_HELPTEXT 'proc_name'
To display the information about procedure:
SP_HELP 'proc_name'
sp_depends 'tablename' (Real time usage)
Extended Stored Procedures:
A stored procedure contains T-SQL statements and C/C++ code compiled int
o .dll (Dynamic link library) file is called extended stored procedure.
Every extended stored procedure starts with XP_
All extended stored procedures are stored in MASTER database.
Extended procedures are used to perform operations in OS and Mail Server
.
XP_CMDSHELL 'os command' ---- It is used to communicate
with operating system to execute commands.
To work with this extended procedure, it is essential that it should be
enabled with the following procedure;
Example:
EXEC XP_CMDSHELL 'MD C:\SQLS'
EXEC XP_CMDSHELL 'DIR C:\'
EXEC XP_SENDMAIL |
EXEC XP_READMAIL |

to interact with mail server.

xp_cmdshell 'dir c:\'


xp_cmdshell 'md c:\peers'
how to check the drive free space?
xp_fixeddrives
STORED FUNCTIONS
(USER DEFINED FUNCTIONS)
Function is defined as "self contained or predefined
program which returns max of 1 value".
Returned value can of int, varchar, datetime.
User defined functions are classified into 2 types;

I. Scalar valued functions (which returns 1 value)


II. Table valued functions (which returns multiple rows)
difference between procedure and function:
1)Procedure can return zero or n values whereas function can return one value wh
ich is mandatory.
2)Procedures can have input,output parameters for it whereas functions can have
only input parameters.
3)Procedure allow select as well as DML (Insert,update,delete) statement in it w
hereas function allow only select statement in it.
4)Functions can be called from procedure whereas procedures cannot be called fro
m function.
5)Exception can be handled by try-catch block in a procedure whereas try-catch b
lock cannot be used in a function.
6)We can go for transaction management in procedure whereas we can't go in funct
ion.
7)Procedures can not be utilized in a select statement whereas function can be e
mbedded in a select statement.

I. 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 argument
s 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
examples:
create a function that takes 2 values as input and returns sum of 2 values?
CREATE FUNCTION sumnos1(@a INT,@b INT)
RETURNS INT
AS
BEGIN
DECLARE @c INT
SET @c=@a+@b
RETURN @c
END
CALLING A USER DEFINED FUNCTION:

A user defined function is


called thru SELECT statement,
where function name should be preceeded by Schema name
i.e. dbo.
SELECT dbo.func_name(list_of_args)
SELECT dbo.sumnos1(12,23)
A user defined function
can be called thru a main program, where
function name should be preceeded by schema name.
SET var=dbo.func_name(list_of_args)
DECLARE @x INT,@y INT,@z INT
SET @x=78
SET @y=94
SET @z=dbo.sumnos1(@x,@y)
PRINT @z
2. create a function that takes empno as an argument and returns ename?
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)
3. create a function called fact that takes 1 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 -- loop end
RETURN @f
END -- function end
1!=1
2!=1x2=2
3!=1x2x3=6
4!=1x2x3x4=24
5!=1x2x3x4x5=120
n!=1x2x3....n-1xn

How to convert starting letter of each word to capital? using sql server
ex: hello hai how are you
output: Hello Hai How Are You
create FUNCTION InitCap ( @Input varchar(4000) )
RETURNS VARCHAR(4000)
AS
BEGIN
DECLARE
DECLARE
DECLARE
DECLARE

@I
INT
@Char
CHAR(1)
@PrevChar
CHAR(1)
@Output VARCHAR(255)

SET @Output = LOWER(@Input)


SET @I = 1
WHILE @I <= LEN(@Input)
BEGIN
SET @Char
= SUBSTRING(@Input, @I, 1)
SET @PrevChar = CASE WHEN @I = 1 THEN ' '
ELSE SUBSTRING(@Input, @I - 1, 1)
END
IF @PrevChar IN (' ', ';', ':', '!', '?', ',', '.', '_', '-', '/', '&', ''''
, '(')
BEGIN
IF @PrevChar != '''' OR UPPER(@Char) != 'S'
SET @Output = STUFF(@Output, @I, 1, UPPER(@Char))
END
SET @I = @I + 1
END
RETURN @Output
END
SELECT dbo.fact(5)
6.create a function that takes countryname as an argument and returns capital na
me?
CREATE FUNCTION Capital (@Country nvarchar(15))
RETURNS varchar(30)
AS BEGIN
declare @Return varchar(30)
select @return = case @Country
when 'Argentina' then 'South America'
when 'Belgium' then 'Europe'
when 'Brazil' then 'South America'
when 'Canada' then 'North America'
when 'Denmark' then 'Europe'
when 'Finland' then 'Europe'
when 'France' then 'Europe'

else 'Unknown' end


return @return
end
create FUNCTION DecimalToBinary(@a int)
RETURNS varchar(20)
AS
BEGIN
DECLARE @b varchar(20) =' '
WHILE @a > 0
BEGIN
SET @b= @b + CAST((@a % 2) AS varchar)
SET @a = @a / 2
END
RETURN REVERSE(@b)
END
select dbo.decimaltobinary(20)
Create a function to Convert lower case to uppercase after a full stop/period
Create FUNCTION Test1(@val varchar(40))
RETURNS varchar(40)
AS
BEGIN
DECLARE @len int, @i int
DECLARE @res varchar(40)
SET @res = ''
SET @len = LEN(@val)
SET @i=1
WHILE(@i <= @len)
BEGIN
IF @i=1
BEGIN
SET @res = @res + UPPER(SUBSTRING(@val,@i,1))
END
ELSE
BEGIN
IF SUBSTRING(@val,@i,1) = '.' AND SUBSTRING(@val,@i+1,1) <> ' '
BEGIN
SET @res = @res + SUBSTRING(@val,@i,1) + UPPER(SUBSTRING(@val, @i+1,1))
SET @i = @i+1
END
ELSE IF SUBSTRING(@val,@i,1) = '.' AND SUBSTRING(@val,@i+1,1) = ' '
BEGIN
SET @res = @res + SUBSTRING(@val,@i,2) + UPPER(SUBSTRING(@val, @i+2,1))
SET @i = @i+2
END
ELSE
BEGIN
SET @res = @res + SUBSTRING(@val,@i,1)
END
END
SET @i=@i+1

END
RETURN @res
END

select dbo.test1('hello how are u. i am fine')


II) TABLE VALUED FUNCTIONS :
These functions will return multiple rows.
When these functions are created Begin and End blocks should not be mentioned.
A function should be provided with return type as TABLE, since it is returning m
ultiple rows.
Syntax:
CREATE FUNCTION func_name(list_of_args)
RETURNS TABLE
AS
RETURN (SELECT query)
Calling a Table Valued Functions:
syntax:
SELECT * FROM dbo.func_name(list_of_args)
example:
1.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)
2.Write a function to return entire dept table?
create function dept_table()
returns table
as
return(select * from dept)

calling table valued function :


------------------------------select * from dbo.dept_table()

viewing the code related to stored functions:

-- table valued function


select name from sysobjects where xtype='IF'
sp_helptext func_name : this predefined procedure will display the complete co
de of a function which is created in a databas.
sp_helptext fact
Droping a function:
DROP FUNCTION func_name
DROP FUNCTION sumnos1
To display all the user created functions:
SELECT NAME FROM SYSOBJECTS WHERE XTYPE='FN'
Database Trigger:
Database trigger is a stored procedure that is fired when an insert,update or de
lete statement is issued against the associated table.
uses:
1.To generate data automatically.
2.To enforce complex integrity constraints(checking with sysdate,checking with d
ata in another table)
3.To customize complex security authorization
4.To maintain replicate tables.
5.To audit data modification.
bank_master
accno
1001
1002
1003
1004
1005

balance
10000
20000
26500
40000
35555
bank_transaction

cname accno
praveen 1005

ttype
cr

amount
25000

two types of trigger:


1.table level trigger (only one time firing) => after
2.row level trigger ( 100 row deleted => 100 time firing) => for
syntax:
create/alter trigger <trigger_name>
on <tablename> / <viewname>
after/instead of/for insert,update,delete
as

begin
statements
end
CREATE TRIGGER T11 ON BANK_TRANSACTION AFTER INSERT
AS
BEGIN
DECLARE C1 CURSOR FOR SELECT * FROM BANK_TRANSACTION
DECLARE @CNAME VARCHAR(20),@ACCNO INT,@TTYPE VARCHAR(2),@AMOUNT INT
OPEN C1
FETCH NEXT FROM C1 INTO @CNAME,@ACCNO,@TTYPE,@AMOUNT --START THE LOOP
WHILE(@@FETCH_STATUS=0)
BEGIN
FETCH NEXT FROM C1 INTO @CNAME,@ACCNO,@TTYPE,@AMOUNT -- CONTINUE THE LOOP
END
IF @TTYPE='CR'
UPDATE bank_MASTER SET BALANCE=BALANCE +@AMOUNT WHERE ACCNO=@ACCNO
ELSE
UPDATE bank_MASTER SET BALANCE=BALANCE -@AMOUNT WHERE ACCNO=@ACCNO
CLOSE C1
DEALLOCATE C1
END
2. Create a trigger tr2 For INSERT,DELETE Triggering
event where trigger should be fired if the transaction
is performed before 10AM and After 4PM?
CREATE TRIGGER tr2
ON bank_master
FOR INSERT,DELETE
AS
BEGIN
IF DATEPART(HH,GETDATE()) not in(10,11,12,13,14,15,16)
BEGIN
ROLLBACK
RAISERROR('INVALID TIME',1,1)
END
END

3 create a trigger tr1 for INSERT,DELETE triggering


event where trigger should be fired if the transactions are
performed on SUNDAY?
CREATE TRIGGER tr1
ON bank_master
FOR INSERT,DELETE
AS
BEGIN
IF DATENAME(DW,GETDATE())='Sunday'
BEGIN
ROLLBACK
RAISERROR('CANT INSERT OR DELETE THE DATA ON SUNDAY',1,1)
END
END
4.Create a trigger t12 For INSERT Triggering

event where trigger should be fired if the input amount is more than balance.
CREATE TRIGGER T12 ON BANK_TRANSACTION AFTER INSERT
AS
BEGIN
SET NOCOUNT ON --STOP THE SERVER MSG
DECLARE C1 CURSOR FOR SELECT * FROM BANK_TRANSACTION
DECLARE @CNAME VARCHAR(20),@ACCNO INT,@TTYPE VARCHAR(2),@AMOUNT INT,@BALANCE INT
OPEN C1
FETCH NEXT FROM C1 INTO @CNAME,@ACCNO,@TTYPE,@AMOUNT --START THE LOOP
WHILE(@@FETCH_STATUS=0)
BEGIN
FETCH NEXT FROM C1 INTO @CNAME,@ACCNO,@TTYPE,@AMOUNT -- CONTINUE THE LOOP
END
SELECT @BALANCE=BALANCE FROM BANK_MASTER WHERE ACCNO=@ACCNO
IF @AMOUNT > @BALANCE
BEGIN
ROLLBACK
RAISERROR('INVALID AMUONT',1,1)
END
ELSE IF @TTYPE='CR'
UPDATE bank_MASTER SET BALANCE=BALANCE +@AMOUNT WHERE ACCNO=@ACCNO
ELSE
UPDATE bank_MASTER SET BALANCE=BALANCE -@AMOUNT WHERE ACCNO=@ACCNO
CLOSE C1
DEALLOCATE C1
END

4.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 TR7
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

Difference between procedures and Triggers:


procedures

Triggers

1.called Explicitly
2.can be created without a table.
table.

1.called implicitly
2.can't be created without a

3.it accepts parameters


4.it returns a value

3.it won't accept parameters


4.it won't return a value.

VIRTUAL TABLES (MAGIC TABLES)


SQL SERVER provides 2 virtual tables
which can be used only in triggers.
These tables are provided by TempDB(System database).
These tables play major role to have backup of data.
Tables are Identified as INSERTED , DELETED
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 virtual table.
Data avaiable 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 INSERTED table and old value is transfered 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 at once in a single trigger.

INSTEADOF TRIGGERS:
1
These triggers is used to make the modifications
into base table thru a complex view.(Non updateable 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, grou
p functions, distinct operator.
example:
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

create a database trigger do not allow to enter more than four employees in a em
p4 table.
create trigger tr1 on
emp4
instead of insert
as
begin
declare @cnt int
declare @ename varchar(20),@eno int,@salary int,@deptno int
select @ename=ename,@eno=eno,@salary=salary,@deptno=deptno from
inserted
select @cnt=count(*) from emp4 where deptno=@deptno
if @cnt=4
raiserror('max 4 employees',15,1)
else
insert into emp4 values(@ename,@eno,@salary,@deptno)
end
select * from emp4
* 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

* Create a trigger for DDL triggering event that restricts the droping and alter
ing of a table in a database?
CREATE TRIGGER tr5
ON DATABASE
FOR DROP_TABLE,ALTER_TABLE,CREATE_TABLE,TRUNCATE_TABLE
AS
BEGIN
ROLLBACK --cancel the transaction
RAISERROR('CANT ALTER OR DROP THE TABLES',15,16)
END

Nested Trigger:
---------------------Trigger Recursion and Nesting
----------------------------* Trigger events can be fired within another trigger action.
* One Trigger execution can trigger event on another table or same table.
* This trigger is called NESTED TRIGGER or RECURSIVE TRIGGER.
* Nested triggers SQL Server supports the nesting of triggers up to a maximum of
32 levels.
* Nesting means that when a trigger is fired, it will also cause another trigger
to be fired.
create table t1(a int)
go
create table t2(a int)
go
create trigger tr11 on t1
for insert as
print 'begin tr11 firing'
insert t2 values(1)
print 'end tr11'
go
create trigger t2it on t2 for insert as
print 'begin t2it'
print 'end t2it'

go
insert t1 values (1)

select * from t1
select * from t2
To display list of triggers created in a database:
* SELECT NAME FROM SYSOBJECTS WHERE XTYPE='TR'
* select * from sys.all_objects where type='tr'
VIEWING TRIGGER INFORMATION:
SP_HELPTEXT trigger_name
SP_HELPTEXT tr2
DISABLE / ENABLE THE TRIGGERS:
ALTER TABLE table_name DISABLE/ENABLE TRIGGER trigger_name
DROPING A TRIGGER:
DROP TRIGGER trigger_name

SECURITY
SQL SERVER 2012 provides a connection to a database server in 2 ways;
1. Windows Authentication : At this authentication a user connects to database s
erver using windows accounts i.e. users existing at windows operating system. It
is called trusted connection.
2. SQL SERVER Authentication : At this authentication a user connects to databas
e server using the SQL SERVER accounts. By default SQL SERVER provides a login c
alled 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='passwd'
DEFAULT_DATABASE='db name'
CHANGING THE PASSWORD:
To change the password of existing login, the following command is used
in that database which has got Administration privileges.
Syntax:
ALTER LOGIN <login_name> WITH PASSWORD='passwd'
DROPING A LOGIN:
To drop a login user should be in a database
which has got administration privileges.
Syntax:
DROP LOGIN <login_name>
Examples:
To create a login:
USE MASTER
CREATE LOGIN GUNA WITH PASSWORD='123' DEFAULT_DATABASE='Batch2'
To Change the password:
USE MASTER
ALTER LOGIN GUNA WITH PASSWORD='123'
To Drop the Login:
USE MASTER
DROP LOGIN GUNA
CREATING A LOGIN WITH GUI:
From view menu click on Object explorer--->
Databases-->Security--->
Right click on Logins--->click on new login
Login Name : Rambabu
Select SQL SERVER Authentication

Password : 123
Confirm Password : 123
Deselect Enforce Password Ploicy
Default Database : Practice
From SELECT A PAGE window,
select User Mapping, and Select the database,
where in that user it creates a user(Peers)
Click OK.
Changing the password and properties of Login:
From View menu click on object explorer--->
Databases---->Security--->Logins--->
Select the login and right click properties
Change the necessary options and then click ok.
Creating a Batch and Script Files:

Batch is nothing but set of transact SQL statements


executed under single execution plan. Every batch is followed by
GO (which makes a separate execution plan).
Creation of any object, setting any property
should be presented in different batches.
Script is nothing but collection of batches saved in a file
with .sql extension
Advantages:
1. Script files are reusable
2. Script files are used to copy database objects from one system to another sys
tem.
Generating T-SQL scripts for existing database:
SQL Server provides Script wizard to generate Scripts for existing datab
ase and other objects.
Object Explorer ----> Connect to Database Engine ----> Expand databases ----> Se
lect the database----> right click Tasks---->Generate Scripts
STEP 1:
Click next
STEP 2:
Select the database
Check script all objects in Selected Database
Click next
STEP 3:
Provide Scripting options
Append to File = false / true

If true ----- Select existing file


If false ---- new file is created
Script database create = True / False
If true ---- Create db statement generated
If false --- Create db statement will not be generated
Script for server version ---- SQL Server 2005
STEP 4:
Script to File = d:\TEST.sql
STEP 5:
Click Finish
Example: (Creating User Defined Script File)
CREATE DATABASE TESTING
GO
USE TESTING
CREATE TABLE EMPT
(EMPNO INT PRIMARY KEY,EN VARCHAR(12))
GO
CREATE VIEW V1
AS
SELECT * FROM EMPT
GO
FROM file menu click on save and specify the file name with .SQL extension.

SQL SERVER INTEGRATION SERVICES (SSIS)

In SQL Server 2000 we have DTS packages, which are based on COM technology (Comp
onent Object Model)
In SQL Server 2005 and 2008 it is introduced with SSIS packages which is based o
n .net technology.
To Import or Export database objects and data from one data source to another da
ta source, we can use SSIS packages.
SSIS package will support to import or export the database and data between the
following softwares;
SQL
SQL
SQL
SQL

Server <------------>
Server <------------>
Server <------------>
Server <------------>
..... etc

MS-Access
Oracle
SQL Server
Text File/XML Files/Excel Files

DTS or SSIS communicates with any data source with the help of ODBC or OLEDB or
.net data providers.

_______________ ODBC_____________ Data Src


|
DTS/SSIS------ ______ OLEDB_________ Data Source
|
______ .net data providers______Data Source
Data source can be Oracle,SQL Server,..........etc
SQL NATIVE CLIENT interface can be used to communicate with only SQL Server
ODBC --- Open database Connectivity
OLEDB --- Object Linking Embedding Databases
Working Procedure:
Open Object Explorer
|
Connect to Database Engine
|
Select the Server
|
Select any database (Batch5)
|
Right Click and select Import or Export Data.
Example 1: Exporting data from SQL Server to Excel Sheet
Right click on Database and then select Export;
STEP 1: click Next
STEP 2: Specify Source Data
Data Source : SQL Native Client
Server Name : PEERS\SQLEXPRESS
Database
: Batch5
Click Next
STEP 3: Specify Destination
Destination : Microsoft Excel
Excel File Path : c:\empdetails.xls
Check First row has column names
Click Next
STEP 4: Select Copy data from one or more tables or views
Click Next
STEP 5: Select Tables or Views whose data is to be copied into excel sheet.
SELECT EMP,DEPT,SALGRADE,STUDENT tables,v3(view).
Click Next
STEP 6: Check Execute Immediately

Click Next
STEP 7: Click Finish

Example 2: Copy data from SQL Server to SQL Server


Importing the data from one database to the other database.
Select database into which objects should be imported from other database.
Select database (Test)---->Right click tasks---->click on Import data
STEP 1 : Click Next
STEP 2 : Specify Data source
Data Source

: SQL Native Client

Server Name

: PEERS\SQLEXPRESS

Database

: Batch5

Click Next
STEP 3 : Specify Destination
Destination

: SQL Native Client

Server Name

: PEERS\SQLEXPRESS

Database

: Test

Click Next
STEP 4 : Select copy data from one or more tables or
Click Next
STEP 5 : Select tables and views to be copied
After selecting
Click Next
STEP 6 : Check Execute Immediately
Click Next
STEP 7 : Click Finish
NOTE:
SSIS packages will be stored in MSDB database.
Browsing SSIS packages:

views

Object Explorer
|
Connect to Integration Services
|
Select Stored Packages
|
MSDB (System Database)
|
Select package & Right click Run Package
SQL Server Reporting Services
SQL Server Reporting Services (SSRS) is a server-based report generation
software system from Microsoft. It can be used to prepare and deliver a variety
of interactive and printed reports. It is administered via a web interface. Rep
orting services features a web services interface to support the development of
custom reporting applications.
SSRS competes with Crystal Reports and other business intelligence tools
, and is included in Express, Workgroup, Standard, and Enterprise editions of Mi
crosoft SQL Server as an install option. Reporting Services was first released i
n 2004 as an add-on to SQL Server 2005. The second version was released as a par
t of SQL Server 2005 in November 2005. The latest version was released as part o
f SQL Server 2008 in August 2008.
Reporting Services framework contains 3 Components;
1. Report Server
2. Report Manager
3. Report Temporary Database
Architecture Of Reporting Services
______________ _______________
|Report Builder| |Report Designer|
--------------- --------------^
^
|
|
V
V
______________
_____________
|Report Manager|<------------>|Report Server|
-------------------------^
^
|
|
V
V
_____________
_________
|Report Server| | Data |
| Database | | Sources |
---------------------Report Server :
It compiles and executes client requests, Connecting to
the different data sources and loads the required data into temporary databases.

Report manager :
tion of client.

It will verify security information, connections informa

Report Temporary Database : To store the reporting data temporary for processing
purpose.
Generating Sample Report
Start the reporting services;
Start--->programs--->Microsoft SQL Server 2005---> Configuration Tools-->SQL Server Configuration Manager---> Select SQL Server Reporting Services (cli
ck on start)
Start--->Programs--->Microsoft SQL Server 2005---> Business Intelligence
Development Studio
From File Menu---->New--->Project--->Select Report Server Project Wizard
Name : UserReport
Location : c:\Mydata
Click Ok
Click Next
STEP 1:
New data Source
Name

DataSource1

Type

Microsoft SQL Server

Connection String
Click on Edit
Server Name : PEERSTEC
Select database name
Click Test Connection
Click Ok
click Next
STEP 2:
Query String:
SELECT * FROM EMP
Click Next
STEP 3:

ARCHANA

Select Report Type


Select Tabular
click Next
STEP 4:
Select the columns for Groups and details;
Groups : Deptno
Details : Empno,Ename,Job,Sal,Comm
Click Next
STEP 5:
Select Stepped
Check Include Subtotals
Click Next
STEP 6:
Select Table Style (Bold)
Click Next
STEP 7:
Report Server : http://localhost/ReportServer
Deployment Folder : UserReport
Click Next
STEP 8:
Report Name

Report1

Check Preview Report


Click On Finish
SQL SERVER AGENT :
In SQL Server 2012 SQL Server Agent is a service.
It supports to create Jobs, Schedules, Alerts And Operators.
job: job is nothing but a task.
schedule : timing schedule
alert is nothing but a predefined condition.

operator is nothing but a responsible person who will receive the notification.
It provides automatic execution of jobs and tasks associated with differ
ent steps based on system date and time.
To work with SQL Server Agent it is essential that services should get s
tart.
--Example1:
--Every 1 minutes to insert the records into emp1 table automatically
step1 : Create the table
create table emp1(eno int identity,doj datetime)

To start the service the following steps should be used.

start--->programs--->Microsoft SQL Server 2005---> Configuration Tools--->SQL Se


rver Configuration Manager---> Select SQL Server Agent (double click on the serv
ices and click on start)

To work with SQL Server Agent;


creating a table:
CREATE TABLE EMP1
(ENO INT IDENTITY,DOJ SMALLDATETIME)
Object Explorer
|
Expand SQL Server Agent
Creating a job, Steps and Schedules:
STEP 1:

Select the jobs, right click and new job


Name

ins_rec_job

Owner

sa

Category:

[Uncategorized [lOCAL]]

STEP 2:
select "steps" from "select a page window"
Click on New
Step Name

ins_rec

Type

Transact-SQL script (T-SQL)

Database

praveen

Command

INSERT EMP1 VALUES(getdate())

Click Ok
STEP 3:
Select "Schedules" from "Select a page window"
Click New
Name

sch_ins_rec

Schedule Type

Recurring

Frequency
Occurs :

Daily

Recurrs Every : 1 Day


Daily Frequency
Occurs Every : 1 Min
Click Ok
Click Ok
NOTE:
To execute the created procedure automatically based on a created schedule.
CREATE PROCEDURE insrow
AS
BEGIN
INSERT EMP1 VALUES(getdate())
END

Under steps window, create a new step and provide the command used to execute th
e procedure;
EXEC insrow
SP_RENAMEDB: Here SP stands for Stored Procedure. This stored procedure is used
to change the name of the existing database.
Syntax: SP_RENAMEDB

OLD DATABASENAME ,

E.g.: SP_RENAMEDB

NRSTT ,

NEW DATABASENAME
NRSTTS

The above statement renames (changes the database name) NRSTT to NRSTTS
SP_RENAME: This stored procedure is used for changing the name of the table and
for changing the name of the column
i. Syntax to change the name of the table
SP_RENAME
E.g.

OLD TABLENAME , NEW TABLENAME

SP_RENAME

EMP , EMPLOY

The above stored procedure changes the name of EMP table to EMPLOY
ii. Syntax to change the name of the column
SP_RENAME
E.g.

TABLE.OLDCOLUMN NAME ,

SP_RENAME

NEW COLUMNNAME

STUDENT.ADR , ADDRESS

The above stored procedure changes the name of ADR column to ADDRESS in STUDENT
table.
SP_HELP: This stored procedure is used to display the description of a specific
table.
Syntax: SP_HELP TABLENAME
E.g.: SP_HELP EMP
The above stored procedure displays the description of EMP table
SP_DATADASES: This Stored procedure displays the list of databases available in
SQL Server.
Syntax: SP_DATABASES

SP_TABLES: This stored procedure displays the list of tables available in the cu
rrent database.
Syntax: SP_TABLES
SP_HELPDB: This stored procedure is used to display the description of master a
nd log data file information of a specific database

Syntax: SP_HELPDB Database-Name


Ex: SP_HELPDB SAMPLE
SP_SPACEUSED: This stored procedure is used to find the memory status of the cur
rent database

SQL Server Analysis Services (SSAS):


SQL Server supports to get data into a SQL Server database and then later gettin
g the same data out of the database. We are provided with how to create tables,
insert data, and use SQL statements, views, and stored procedures to retrieve th
e data. This pattern of activity, where individual actions deal with small piece
s of the database, is often called as online transaction processing, or OLTP.
The another use of databases, specially large databases. Suppose you run an onli
ne book store and have sales records for 50 million book sales.
Searching for the data and summarizing them is called online analytical processi
ng, or OLAP. Microsoft SQL Server 2005 includes a separate program called Micros
oft SQL Server 2005 Analysis Services to perform OLAP analysis.
The basic idea of OLAP is fairly simple. For Example assume book ordering data t
hru online book store, if you want to know how many people ordered a particular
book during each month of the year. It is quite simple to query to get the infor
mation which we require. It may take a long time for SQL Server to extract the d
ata since it should go thru many rows. If data is scattered in various databases
thruout the organization. SQL Server can handle distributed heterogenous querie
s but they are slower.
This is where OLAP comes in. The basic idea is to trade off increased storage sp
ace for speed of querying later. OLAP does this by precalculating and storing ag
gregates. When you identify the data that you want to store in OLAP database, An
alysis Services analyzes it in advance and figures out those yearly, quarterly,
monthly, weekly, and daily numbers
The basic concepts of OLAP include:
Cube
Dimension table
Dimension
Level
Fact table
Measure
Schema
DEPLOYMENT OF DATABASE:

The process of copying database objects structure with data from one ser
ver to another server is called Deployment of database.
Method 1:
Copy backup file (.bak) to destination system.
Restore it on destination system
Method 2:
Copy data files and log files to destination system
1. Detach the database on Source System
sp_detach_db database_name
2. Copy the database files to same location on destination System
3. Attach these files to a database on destination system.
Syntax:
CREATE DATABASE database_name
ON
(FILENAME='path of a file')
FOR ATTACH
To detach a database thru GUI:
Object Explorer
|
Databases
|
Batch3
|
Right click, Tasks, Detach.
After Detaching the database, goto the path of .mdf file of that databas
e
Copy that file to external device or to any other required location.
To Attach the database on Destination System:
Copy that .mdf file on destination system
Object Explorer
|
Databases
|
Right click, click on Attach Database
|
Click on Add, to specify the location of .mdf file
Click ok.

NORMALIZATION

It is a process of splitting a single table into


2 or more sub tables to avoid redundancy and promote integrity.
OR
It is a process of deciding number of
tables required in a database,
columns in each table and relationships
among the tables is known as Normalization.
Noramlization is used to store the data in simple forms.
Advantages of Normalization:
1.
2.
3.
4.

Minimizes Redundancy
Reduces Complexity
Easy Maintainance
Making tables ready to perform joins and sub queries.

A table can be normalized in different ways often called Normal Forms;


1. First Normal Form (1NF) I/U/D OPERATION
2. Second Normal Form (2NF)I/U/D OPERATION
3. Third Normal Form (3NF) I/U/D OPERATION
1. First Normal Form (1NF):
Tables are said to be in 1st Normal form
only when it satisfies the following rules;
i. Isolate(to separate from others) repeating
groups to other table by adding a common column.
ii. Every Column should be atomic(very small).

EMP
EID
E1
E1
E2
E3
E4

DEPTNAME
ADMIN
ADMIN
PERSONAL
SYSTEM
SYSTEM

PROJID
P1
P3
P1
P1
P2

HOURS
450
450
400
500
400

DELETE FROM EMP WHERE EID=E1


DELETE FROM EMP WHERE PROJID=P1
UPDATE EMP SET PROJID=P4 WHERE EID=E1
INSERT/UPDATE/DELETE
DEPT

EID
E1
E2
E3
E4

DEPTNAME
ADMIN
PERSONAL
SYSTEM
SYSTEM

EMPLOYEE
EID
E1
E1
E2
E3
E4

PROJID
P1
P2
P1
P3
P1

HOURS (C.P.K= EID AND PROJID)


450
250
400
450
400

I/U/D

2. Second Normal Form (2NF):


i. Tables should be in 1NF
ii. All Non key columns should be made dependent on whole key
but not part of a key.
SNAME

SNO

S1

S2

S3

bhanu

101

78

67

56

student
sname sno

s1

s2

s3

result
sno
stot

savg

sres

STOT

SAVG

3. Third Normal Form (3NF)


i. Tables should be in 2NF
ii. No Transitive Dependency.
eno
101
102
103

ename
aaa
bbb
aaa

salary
20000
30000
30000

deptno
10
20
20

ename
aaa
bbb

salary deptno
20000 10
30000 20

emp
eno
101
102

dname
ECE
EEE
eee

loc
Chennai
noida
bangalore

SRES

dept
deptno dname
10
ECE
20
EEE

loc
CHENNAI
NOIDA

boyce-codd normal form:


1.c.p.k combinations should not have common field.
2.Individual candidate keys should not be common in c.p.k combination.
EMP
EID
E1
E1
E2
E3
E4

DEPTNAME
ADMIN
ADMIN
PERSONAL
SYSTEM
SYSTEM

PROJID
P1
P3
P1
P1
P2

HOURS
450
450
400
500
400

eid+projid
eid+dname+projid
dept
deptno
10
20
30

dname
ECE
EEE
mech

loc
CHENNAI
NOIDA
noida

deptno ,dname (candidate key)


deptno is primary key
dname is alternate key /secondary key

Composite primary key


CREATE TABLE track(
album CHAR(10),
disk INTEGER,
posn INTEGER,
song VARCHAR(255),
PRIMARY KEY (album, disk, posn)
)

Locking :
Locking resolves problems of concurrent access.
It means accessing same data by the no.of users at same time.
Lock types:
1.shared Lock : is placed when ever user to trying read the database(select)
2.Exclusive Lock : is placed when ever you have to trying update
the database (Update)
3.Deadlocks:
Deadlock occurs when two users have locks on separate objects
and each user wants a lock on the other's object.
For example, User1 has a lock on object "A"
and wants a lock on object "B" and User2 has a lock on object
"B" and wants a lock on object "A". In this case, SQL Server 6.5 ends a deadloc
k by choosing the user, who will be a deadlock victim. After that, SQL Server ro
lls back the breaking user's transaction, sends message number 1205 to notify th
e user's application about breaking, and then allows the nonbreaking user's proc
ess to continue.
You can decide which connection will be the candidate for deadlock victim by usi
ng SET DEADLOCK_PRIORITY. In other case, SQL Server selects the deadlock victim
by choosing the process that completes the circular chain of locks.
So, in a multiuser situation, your application should check for message 1205 to
indicate that the transaction was rolled back and if so, to restart the transact
ion.
Note. To reduce the chance of a deadlock, you should minimize the size of transa
ctions and transaction times.

Viewing locks (sp_lock)


sp_lock
This is the result set of sp_lock stored procedure:
spid
------11
11

locktype
table_id
page
dbname
----------------------------------- ----------- ----------- ------------Sh_intent
Ex_extent

example :

688005482
0

0
336

master
tempdb

begin transaction
declare c2 cursor for select * From employee for update
select * from employee
update employee set eno=1100 where eno=1010
commit transaction
Locking optimizer hints
SQL Server 2005 supports the following Locking optimizer hints:
ROWLOCK
PAGLOCK
NOLOCK
HOLDLOCK
UPDLOCK
TABLOCK
ROWLOCK
Use row-level locks when reading or modifying data.
syntax:
SELECT au_fname FROM pubs..authors (rowlock)
PAGLOCK
Use page-level locks when reading or modifying data.
TABLOCK
Use a table lock when reading or modifying data.
DBLOCK
Use a database lock when reading or modifying data.
UPDLOCK
UPDLOCK reads data without blocking other readers, and update it later with the
assurance that the data has not changed since last read.
XLOCK
Use exclusive locks instead of shared locks while reading a table, and use hold
locks until the end of the statement or transaction.
HOLDLOCK
Use a hold lock to hold a lock until completion of the transaction, instead of r
eleasing the lock as soon as the required table, row, or data page is no longer
required.
NOLOCK
This does not lock any object. This is the default for SELECT operations. It doe
s not apply to INSERT, UPDATE, and DELETE statements.
Examples:
SELECT OrderID
FROM Orders (WITH ROWLOCK)
WHERE OrderID BETWEEN 100
AND 2000
UPDATE Products (WITH NOLOCK)
SET ProductCat = 'Machine'
WHERE ProductSubCat = 'Mac'

example 2:
BEGIN TRAN
SELECT * FROM test1
WITH (HOLDLOCK, ROWLOCK)
WHERE Name = Rahul4'
update test1 set Name =
where Name= Rahul5'

Rahul6'

COMMIT TRAN
Replication is a set of technologies
for copying and distributing data and database objects
from one database to another and then synchronizing
between databases to maintain consistency.
Using replication, you can distribute data to different
locations and to remote or mobile users over local and
wide area networks, dial-up connections, wireless connections,
and the Internet.
Replication Types
Microsoft SQL Server 2005 supports the following types of replication:
Snapshot Replication
Transactional Replication
Merge Replication
Snapshot Replication
Snapshot replication is also known as static replication.
Snapshot replication copies and distributes data and database objects
exactly as they appear at the current moment in time.
Subscribers are updated with complete modified data and not by
individual transactions, and are not continuous in nature.
This type is mostly used when the amount of data to be
replicated is small and data/DB objects are static
or does not change frequently.
Transactional Replication
Transactional replication is also known as dynamic replication.

In transactional replication, modifications to the publication


at the publisher are propagated to the subscriber incrementally.
Publisher and the subscriber are always in synchronization
and should always be connected.
This type is mostly used when subscribers always need the
latest data for processing.
Merge replication
It allows making autonomous(self-governing) changes to replicated data on the
Publisher and on the Subscriber. With merge replication,
SQL Server captures all incremental data changes in the source
and in the target databases, and reconciles conflicts according to
rules you configure or using a custom resolver you create.
Merge replication is best used when you want to support
autonomous changes on the replicated data on the Publisher
and on the Subscriber.

replication tools:
Publisher is a server that makes the data available for
subscription to other servers.
In addition to that, publisher also identifies
what data has changed at the subscriber during the synchronizing process. Publis
her contains publication(s).
Subscriber is a server that receives and maintains the published data.
Modifications to the data at subscriber can be propagated back to the
publisher.

Distributor is the server that manages the flow of data through


the replication system. Two types of distributors are present,
one is remote distributor and the other one local distributor.

Remote distributor is separate from publisher and is configured as


distributor for replication.
Local distributor is a server that is configured as publisher
and distributor.
Agents are the processes that are responsible for
copying and distributing data between publisher and subscriber.

TRIGGERS
1. Triggers are stored T-SQL program unit in a database as stored block object,
which is associated to a specific table.
2. Triggers are executed(fired) automatically when invalid operations are perfor
med over a table.
3. Triggers will not take any arguments like procedures and functions.
4. Triggers will not be executed manually as of Procedures and functions.
5. Triggering statement will be responsible for the execution of triggers.
ADVANTAGES OF TRIGGERS:
1.
2.
3.
4.

It
We
we
It

can
can
can
can

audit the transactions


provide high security for the data and database objects.
provide complex business rules that cant be possible with constraints.
have backup of data without the notice of a user.

TYPES OF TRIGGERS:
1. FOR/AFTER Triggers
i. DML triggers
ii. DDL triggers
2. INSTEADOF Triggers (These triggers are fired instead of DML operation).
DDL Triggers are introduced in
SQL SERVER 2005 and it is used for performing administration 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
VIRTUAL TABLES (MAGIC TABLES)
SQL SERVER provides 2 virtual tables
which can be used only in triggers.

These tables are provided by TempDB(System database).


These tables play major role to have backup of data.
Tables are Identified as INSERTED , DELETED
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 avaiable 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 transfered 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 at once in a single trigger.
1. create a trigger tr1 for INSERT,DELETE triggering
event where trigger should be fired if the transactions are
performed on SUNDAY?
CREATE TRIGGER tr1
ON emp
FOR INSERT,DELETE
AS
BEGIN
IF DATENAME(DW,GETDATE())='Sunday'
BEGIN
ROLLBACK
RAISERROR('CANT INSERT OR DELETE THE DATA ON SUNDAY',1,1)
END
END
2. Create a trigger tr2 For INSERT,DELETE Triggering
event where trigger should be fired if the transaction
is performed before 10AM and After 5PM?
CREATE TRIGGER tr2
ON EMP
FOR INSERT,DELETE
AS
BEGIN
IF LEFT(CONVERT(VARCHAR(12),GETDATE()),2) NOT BETWEEN 10 AND 17
BEGIN
ROLLBACK

RAISERROR('INVALID TIME',1,1)
END
END
3. create a trigger tr3 for UPDATE triggering event where trigger should be fire
d to store the updated and old data into a separated table?
ENO

EMPB
OSAL

NSAL

DOT

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
4. 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
5. create a trigger for DDL triggering event that restricts the droping and alte
ring 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 is 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, group
functions, distinct operator.
example:

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
To display list of triggers created in a database:
SELECT NAME FROM SYSOBJECTS WHERE XTYPE='TR'
VIEWING TRIGGER INFORMATION:
SP_HELPTEXT trigger_name
SP_HELPTEXT tr2
DISABLE / ENABLE THE TRIGGERS:
ALTER TABLE table_name DISABLE/ENABLE TRIGGER trigger_name
To disable database or dml triggers:
DISABLE/ENABLE TRIGGER trigger_name [ALL] ON DATABASE / object_name
DROPING A TRIGGER:
DROP TRIGGER trigger_name

CURSORS
1. It creates memory at database server to store result set of a query.
2. It is created at a system database TempDB
3. Cursors will create a memory to store multiple rows that are returned by a SE
LECT query.
4. Cursors will workd based on the following 5 steps:
I. Declaring a cursor
II. Opening a cursor
III. fetching the data from a cursor
IV. closing a cursor
V. deallocating a cursor
I. 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 typ
es;
1. STATIC : When this cursor type is specified
it will not make the changes in the cursor when the table is changed
in a database.
2. 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.
3. FAST FORWARD : When this cursor type is specified
it will work similar to KEYSET and provides fast performance.
4. DYNAMIC : When this cursor type is specified it also
makes the changes in cursor when the table is changed in a database but performa
nce gets decreases.

LOCKS provided on cursor:


1. READ ONLY (Shared Lock): When this lock is provided
cursor will not accept any changes into it.
2. SCROLL LOCK (Exclusive Lock) : It will allow to make
modification but only by one user.
3. OPTIMISTIC : It will allow to make modification
but only by multiple user.
II) OPENING A CURSOR :
A cursor which is created when gets opened, the query which is associate
d gets executed and makes the data available in a cursor.
Syntax:
OPEN cursor_name
III) FETCHING DATA FROM A CURSOR:
Data from a cursor gets fetched in different ways into temporary or buff
er variables. It supports to fetch only 1 row at a time.
Syntax:
FETCH {FIRST/LAST/NEXT/PREV}
ABSOLUTE POS=position
RELATIVE POS=position
FROM cursor_name
INTO temporary variables
IV) CLOSING A CURSOR:
The created cursor when gets closed it does not support to fetch the dat
a from a cursor.
The operations can be performed over that cursor when it gets reopened.
Syntax:
CLOSE cursor_name
V) 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:
1. Any number of cursors can be created in a single program
but with unique names.
2. Global variable @@FETCH_STATUS plays an important role,

where it returns boolean value i.e. returns 0


if it makes a fetch operation successfull over a cursor
else returns -1.

EXAMPLE:
1. 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
2. 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
3. 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
4. Write a program to display required record from a cursor using absolute posit
ion?
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 pointe
r 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 take
s the control to the next record.
connection level properties:
------------------------- these are applied only to the current connection
set <property> on/off
eg: nocount,ansi_nulls,implicit_transactions,concat_null_yields_null

set ansi_nulls off


if null=null
print 'matched'
else
print 'not matched'
output -> matched
set ansi_nulls on
if null=null
print 'matched'
else
print 'not matched'
output -> not matched
from the tools menu click on options
expand query execution -> expand sql-server
--> use the general,advanced and ansi options to change the connection level pro
perties

SECURITY

SQL SERVER 2005 provides a connection to a database server in 2 ways;


1. Windows Authentication : At this authentication a user connects to database s
erver using windows accounts i.e. users existing at windows operating system. It
is called trusted connection.
2. SQL SERVER Authentication : At this authentication a user connects to databas
e server using the SQL SERVER accounts. By default SQL SERVER provides a login c
alled 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='passwd'
DEFAULT_DATABASE='db name'
CHANGING THE PASSWORD:
To change the password of existing login, the following command is used
in that database which has got Administration privileges.

Syntax:
ALTER LOGIN <login_name> WITH PASSWORD='passwd'
DROPING A LOGIN:
To drop a login user should be in a database
which has got administration privileges.
Syntax:
DROP LOGIN <login_name>
Examples:
To create a login:
USE MASTER
CREATE LOGIN GUNA WITH PASSWORD='123' DEFAULT_DATABASE='Batch2'
To Change the password:
USE MASTER
ALTER LOGIN GUNA WITH PASSWORD='123'
To Drop the Login:
USE MASTER
DROP LOGIN GUNA
CREATING A LOGIN WITH GUI:
From view menu click on Object explorer--->
Databases-->Security--->
Right click on Logins--->click on new login
Login Name : Rambabu
Select SQL SERVER Authentication
Password : 123
Confirm Password : 123
Deselect Enforce Password Ploicy
Default Database : Practice
From SELECT A PAGE window,
select User Mapping, and Select the database,
where in that user it creates a user(Peers)
Click OK.
Changing the password and properties of Login:
From View menu click on object explorer--->
Databases---->Security--->Logins--->
Select the login and right click properties
Change the necessary options and then click ok.
Bulk copy program:

The bcp utility (Bcp.exe) is a command-line tool that uses the Bulk Copy Program
(BCP) API.
The bcp utility performs the following tasks:
Bulk exports data from a SQL Server table into a data file.
Bulk exports data from a query.
Bulk imports data from a data file into a SQL Server table.
Exporting
ex:
c:\>bcp PEERS.DBO.EMP out C:\CUST.TXT -T -c
-T - Trusted connection If
you need to specify U and

T is not specified,
P to successfully log in.

-c Performs the operation using a character data type. This option does not pro
mpt for each field; it uses char as the storage type, without prefixes and with
\t (tab character) as the field separator and \n (newline character) as the row
terminator
Importing
bcp peers.dbo.emp in c:\cust.txt -T -c
Sqlserver 2012 Feature
---------------------*
*
*
*

Sequence objects
Column store indexes
Pagination
Error handling

Database objects:
---------------* Table
* View
* Synonyms
* Index
* Stored Procedure
* Stored Function
* Stored Trigger
* Sequence object (From sqlserver 2012)

*
*
*
*

Sequence objects
Column store indexes
Pagination -OFFSET KEYWORD
Error handling -RETHROW (from sqlserver 2012)

SEQUENCE is one of the new feature introduced in Sql Server 2012.

* Sequence is a user-defined object and as name suggests it generates sequence o


f numeric values according to the properties with which it is created.
* It is similar to Identity column, but there are many difference between them.
syntax:
CREATE SEQUENCE Sequence_name
[ AS [built_in_integer_type | user-defined_integer_type ] ]
[ START WITH ]
[ INCREMENT BY ]
[ { MINVALUE [ ] } | { NO MINVALUE } ]
[ { MAXVALUE [ ] } | { NO MAXVALUE } ]
[ CYCLE | { NO CYCLE } ]
[ { CACHE [ ] } | { NO CACHE } ]
[ ; ]

CREATE SEQUENCE [SequenceExample] AS INT


START WITH 1
INCREMENT BY 1
GO
CREATE TABLE dbo.Employee(ID INT,Name VARCHAR(100))
GO
--INSERT RECORDS to the Employee table with Sequence object
INSERT INTO
(NEXT VALUE
(NEXT VALUE
(NEXT VALUE
GO

dbo.Employee VALUES
FOR DBO.SequenceExample,'BASAVARAJ BIRADAR'),
FOR DBO.SequenceExample,'SHREE BIRADAR'),
FOR DBO.SequenceExample,'PRATHAM BIRADAR')

-- CHECK THE RECORDS INSERTED IN THE TABLE


SELECT * FROM dbo.Employee WITH(NOLOCK)
GO
create SEQUENCE seq1
as int
start with 100
increment by 1
create table emp1(ename varchar(20),
eno int,salary int)
insert
insert
insert
insert

into
into
emp1
emp1

emp1 values('preethu',next value for seq1,5000)


emp1 values('savya',next value for seq1,5000)
values('kumar',next value for seq1,3500)
values('sanjay',next value for seq1,2500)

select * from emp1


Column store Index:
-----------------------------

There are two kind of storage in database. Row Store and Column Store.
Row store does exactly as the name suggests
stores rows of data on a page
lumn store stores all the data in a column on the same page.

and co

These columns are much easier to search instead of a query searching all the dat
a in an entire row whether the data is relevant or not,
column store queries need only to search much lesser number of the columns.
This means major increases in search speed and hard drive use.
The column store indexes are heavily compressed, which translates to even greate
r memory and faster searches.

example :
CREATE NONCLUSTERED COLUMNSTORE INDEX [IX_MySalesOrderDetail_ColumnStore]
ON [MySalesOrderDetail]
(UnitPrice, OrderQty, ProductID)
GO

Error handling:
--------------------SQL Server 2005 introduced TRY CATCH block to handle exception in T-SQL.
The TRY CATCH block is similar to whatever in C# language except you need always
raise a new exception after catching it.
There is no way to simply re-throw it.

BEGIN TRY
BEGIN TRANSACTION -- Start the transaction
-- Delete the Customer
DELETE FROM Customers
WHERE EmployeeID = CACTU
-- Commit the change
COMMIT TRANSACTION
END TRY
BEGIN CATCH
-- There is an error
ROLLBACK TRANSACTION
-- Re throw the exception
THROW
END CATCH
Page Data
SELECT * FROM (
SELECT *,ROW_NUMBER() OVER(ORDER BY EMPNO ASC) AS RN FROM EMP) E
WHERE RN BETWEEN 5 AND 10

--FROM SQLSERVER 2012


SELECT *
FROM EMP
ORDER BY EMPNO
OFFSET 4 ROWS --STARTING ROW POSITION
FETCH NEXT 6 ROWS ONLY;
SQL DBA:
Replication:
----------------Replication :
* Replication is nothing but the concept of Automatic migration of database obje
ct from one server database into other server database.
* Replication always allows you to maintain multiple copies of same database obj
ects on multiple servers.
Advantages:
* Replication allows you to maintain copies of particular database objects.
* Replication increases Data Availability.
* Replication improves performance.
to implement replication we require 3 servers
(i) PUBLISHER:
-- the server which provides the source data is called as the publisher.
-- the articles which are replicated are called as the publications.
(ii) SUBSCRIBER:
----------------- the server which receives the source data from the publisher is called as th
e subscriber.
--the articles which are receving the replicated data are called as the subscrip
tions
(iii) DISTRIBUTOR:
------------------- it is responsible for distributing the data from the publisher to the subscri
ber.
-- it maintains the history of the replication process.

XML Integration

In SQL SERVER 2005 XML integration is introduced, which supports to stor


e and access the data in XML format.

I) 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 <mode>,ROOT(name)
Mode can be classified like RAW, AUTO, PATH
EXAMPLES:
SELECT empno,ename,deptno FROM emp
FOR XML RAW/auto/path
OUTPUT:
<row empno="1001" ename="RAJ" deptno="20" />
<row empno="1010" ename="JAMES" deptno="10" />
SELECT empno,ename,deptno FROM emp
FOR XML AUTO,ROOT('EMPINFO')
OUTPUT:
<EMPINFO>
<emp empno="1001" ename="RAJ" deptno="20" />
<emp empno="1010" ename="JAMES" deptno="10" />
</EMPINFO>
SELECT empno,ename,deptno FROM emp
FOR XML PATH,ROOT('EMPINFO')
OUTPUT:
<EMPINFO>
<row>
<empno>1001</empno>
<ename>RAJ</ename>
<deptno>20</deptno>
</row>
<row>
<empno>1010</empno>
<ename>JAMES</ename>
<deptno>10</deptno>
</row>
</EMPINFO>

II) Storing XML data into table:


1. Data which is represented in XML format, can be stored into a table in the fo
rm of rows and columns using OPENXML()
2. XML data is converted in table format by creating a temporary memory and it i
s 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 tha
t table. It can be used when that temporary table is to be removed.
arg2 is a variable which contains the data in XML format.
3. use INSERT INTO SELECT query.
4. To remove that temporart 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.
example:
CREATE TABLE EMPX
(ENO INT,EN VARCHAR(12))
DECLARE @xmldoc VARCHAR(500),@p INT
SET @xmldoc='<ROOT>
<emp eno="9001" en="Prasad" />
<emp eno="9002" en="Sunil" />
<emp eno="9010" en="Kiran" />
</ROOT>'
EXEC sp_xml_preparedocument @p OUTPUT,@xmldoc
INSERT INTO empx SELECT * FROM OPENXML(@p,'/ROOT/emp',1)
WITH
(eno INT,en VARCHAR(12))
EXEC sp_xml_removedocument @p
III) Working with XML datatype:
XML data type has been introduced in SQL SERVER 2005.
It supports to insert the data in XML format using INSERT command.
XML Is case sensitive.
xML data type provides default memory of 2GB
example:
CREATE TABLE empt
(eno INT,info XML)
INSERT INTO empt VALUES(101,'<EMP>
<ENAME>XYZ</ENAME>
<SAL>1000</SAL>

</EMP>')
INSERT INTO empt VALUES(101,'<EMP>
<ENAME>ABC</ENAME>
<SAL>2000</SAL>
</EMP>
<EMP>
<ENAME>PQR</ENAME>
<SAL>3000</SAL>
</EMP>')
query() : This function will support to retrieve the required attribute informat
ion 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 w
ith column name created witeL datatype.
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 elemen
t exist else returns with 0.
SELECT info.exist('/EMP/SAL') FROM empt

SUB PROGRAMS:

* NAMED BLOCKS:
PROCEDURE
FUNCTIONS
DB TRIGGERS
PROCEDURES :
1.A procedures is a pre-compiled named block stored in database that performs a
task & may or
maynot return value.
2.procedures are stored in database, so it is called "stored procedure".
3.procedures are created to perform DML operation over database.
syntax:
create/alter procedure <procedurename>(parameters)
as
begin

statements
end
parameters are two types;
1.actual parameter
2.formal parameter
ex:
create procedure addnum(@x int,@y int)
as
begin
declare @z int
set @z=@x + @y
print @z
end
execute addnum 10,20

CREATE PROCEDURE UPDSAL(@E INT,@P INT,@S SMALLMONEY OUTPUT)


AS
BEGIN
UPDATE EMP SET SALARY=SALARY+(SALARY* @P/100) WHERE ENO=@E
SELECT @S=SALARY FROM EMP WHERE ENO=@E
END

CREATE PROCEDURE UPDSAL(@E INT,@P INT,@S SMALLMONEY OUTPUT)


AS
BEGIN
UPDATE EMP SET SALARY=SALARY+(SALARY* @P/100) WHERE ENO=@E
SELECT @S=SALARY FROM EMP WHERE ENO=@E
END
CREATE FUNCTION ADDNUM1(@X INT,@Y INT) RETURNS INT
AS
BEGIN
DECLARE @Z INT
SET @Z=@X + @Y
RETURN @Z
END
SELECT DBO.ADDNUM1(100,10)

EXCEPTION HANDLING:
1.AN EXCEPTION MEANS "RUNTIME ERROR"
2.To handle errors we need to provide a block called "try-catch block".
Syntax:
create procedure <name>(parameters)
as

begin
begin try
statements
end try
begin catch
statements
end catch
end
ex:
create procedure div(@x int,@y int)
as
begin
begin try
declare @z int
set @z=@x /@y
print @z
end try
begin catch
print 'Divide by zero error'
end catch
end
Functions in Exception handling:
1.error_number()
2.error_message()
3.error_line()
4.error_state()
select * from sys.messages (This table maintains the list of errors)
Functions:
Function is also a named TSQL Block takes some input performs
a task and must return a value.
syntax:
create/alter function <name>(parameter) returns <type>
as
begin
statements
return <expression>
end
example:
create function addnum(@x int,@y int)
returns int
as
begin
declare @z int
set @z=@x + @y
return @z
end
drop procedure <name>
drop function <name>

Generating Script:
Script is nothing but collection of batches saved in a
file with .sql extension.
Advantages:
1.Script files are reusable
2.Script files are used to copy database objects from
one system to another system.
Generating T-SQL scripts for existing Database:
object Explorer ----> connect to Database engine--->
Expand Databases ----> select the database----> right
click Tasks------> Generate Scripts
DATA TRANSFORMATION SERVICES(DTS)
OR
SQL SERVER INTEGRATION SERVICES(SSIS)
IN Sqlserver 2000 we have DTS packages, which are based
on COM technology(Component Object Model)
IN Sqlserver 2005 it is introduced with SSIS packages which is
based on .net technology.
To import or Export database objects and data from one
data source to another data source,
we can use SSIS packages.
sqlserver <----------> MSAccess
Sqlserver <----------> Oracle
Sqlserver < --------> MSEXcel
working procedure:
open object Explorer ---> connect to database engine
-> select the server---> select any database--->
right click and select import or export data.
example 1: Exporting data from sqlserver to excel sheet:
Right click on database and then select EXPort
step 1:
click next
step 2: specify source data
step 3 specify destination
step 4 : select copy data from one or more ta
bles or views.
click next
step 5: select tables or views
click next
SQLSERVER AGENT:
IN Sqlserver 2005 Sqlserver Agent is a service.
IT supports to create jobs,Schedules,Alerts and opertors.
It provides automatic execution of jobs and tasks
associated with different steps automatically based
on system date and time.

to start the service:


start-> programs ->microsoft Sqlserver 2005 -> configuation tools
->sqlserver configuration manager -> select sql server
agen (double click on the serivces and click on start)
To work with Sqlserver Agent:
object explorer -> expand SqlserVer Agent->
CREATE TABLE EMP1(ENO INT IDENTITY,DOJ DATETIME)
creating a job,steps and schedules:
step 1:
SQL SERVER REPORTING SERVICES:
Sqlserver Reporting services(SSRS) is a server -based
report generation software system from microsoft.It can be used to
prepare and deliver a varitety of interactive and
printed reports.
it is administed via a web interface.
Reporting services framework contains 3 components:
1.Report Server
2.Report Manager
3.Report Temporary Database.
Report Server : it compiles and executes client requests,
Connecting to the different data sources and loads the required
data into temporary databases.
Report Manager client: It will verify security information,
connections information of client.
Report Temporary database : To store the reporting data
temporary for processing purpose.
generating report:
start-> program->microsoft sqlserver 2005 -> configuration tools->
sqlserver configuration manager->select sqlserver reporting services
(click on start)
start->programs ->microsoft sqlserver 2005 ->
business intelligence development studio
from file->new ->project ->select report server
project wizard
name : userreport
location : c:\mydate
click ok
click next
step 1:
new data source
name : datasource1
type : Microsoft Sqlserver
connection string :
click on edit
server name: peers\sqlexpress
select database name : batch5
click test connection
click ok
click next
step 2: Query String:
select * from emp
click next
step : 3
select report type
select tabular
click next

step 4:
select the columns for groups and details
groups: deptno
details ename,eno,job,sal,comm
click next

Generating Sample Report:


Start the report Services:
start->programs->microsoftsqlserver 2005-> configuration tools->
sqlserver configuration manager ->select sqlserver Reporting Services
(click on start)
start->programs ->microsoftsqlserver 2005 ->
Business Intelligence Development Studio
file ->new -> project->select report server project wizard
name : userReport
location : c:\mydata
click ok
click next
step 1:
newdata Source
name : datasource1
type : microsoft Sqlserver
step 2: query string
select * from emp
click next
step 3:
select report type
select tabular
click next
step 4:
SSAS(Sqlserver Analysis Services )
Sqlserver supports to get data into a sqlserver database and then
later getting the same data out of the database.
we are provided with how to create tables, insert data,
and use sqlstatements,views,and stored procedures to retrived the data.
this pattern of activity ,where individual actions
deal with small pieces of the database, is
often called as online transaction processing or OLTP.
The basic concepts of OLAP include:
cube
dimension table
dimension
level
fact table
measure

schema
CLR Integration: (Common language Runtime)
In SQL Server 2005 database engine is integrated with CLR(
common Language Runtime Environment)
Database objects can be created with T-sql code + .net language code.
A database object created with T-SQL + .net language code
can be called as 'CLR database object'.
1.CLR
2.CLR
3.CLR
4.CLR
5.CLR

stored procedure
user defined functions
Triggers
user defined types
user defined Aggregates

To prepare CLR Database object we have 4 steps:


1.Develop .net assembly
2.Register the assembly in sqlserver 2012 database.
3.Convert the assembly methods into stored procedure,
user defined function,Triggers....etc
4.Invoke the object thru SQLSERVER
example:
CLR function with C#
Start ->run --->devenv
file ->new-->project->>class library->myclr
using System;
using System.Collection.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.Sqlserver.Server;
public class CLRClass
{
[Microsoft.SqlServer.Server.SqlFunction]
public static int MyCLRMethod(int a,int b)
{
return (a+b);
}
}
from build menu---> build Myclr
step 2:
Register the Assembly in Sql Server database.
--> open object Explorer from management studio
--> connect to database engine
--> expane databases
-->select database (batch 5)
-->programmability->assemblies-->right click-->new assembly(myCL
RAssembly)
provide the path of the assembly
c:\myClr\bin\debug\MyClr.dll
click ok

step 3:
CREATE FUNCTION MYCLRTest(@i int,@j int)
return int
as
external name MYCLRAssembly.CLRClass.MYCLRMethod
Enable / Disable CLR Integration
start->programs ->microsoft SQlserver 2005
->configuration tools
->sqlserver surface Area Configuration ->
Surface Area Configuration for features
-> select Clr integration
->Check ENABLE Clr Integration
click apply and click ok
OR
sp_configure 'show_advanced options',1
reconfigure
sp_configure 'clr enabled',1
go
reconfigure
step 4:
to invoke a function;
select dbo.MyCLRTest(27,89)
create 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='passwd'
CHANGING THE PASSWORD:
To change the password of existing login,the
following command is used in that database with has
got administration privileges.
Syntax:
ALTER LOGIN <login_name> WITH PASSWORD='password'
DROPING A LOGIN;
To drop a login user should be in a database which
has got administration privileges.
USE MASTER
DROP LOGIN peers
to Change the password:
USE MASTER
ALTER LOGIN peers WITH PASSWORD='sample123'
create a login with GUI:
object EXplorer---> databases--->security-->right click
on logins---> click on new login
Login Name : guna
select SQL SERVER Authentication

password : test123
confirm password : test123
Deselect Enforce password policy
Default Database : Batch2
From SELECT A PAGE WINDOW, Select User Mapping,
and select the database,where in that user it creates
a user with the same login name.
click ok
CHANGING THE PASSWORD AND PROPERTIES OF LOGIN:
object explorer---->databases -> security-> logins--->select
the login and right click properties
change the necessary options and then click ok.
Global Variables:
These variable are provided by software.
These variables cant be used to intialize the value manually.
These variables will be stored with the data automatically
based on the operations performed by SQL statment.
These variables are preceeded by @@
1.@@SERVERNAME : Returns name of the server
SELECT @@SERVERNAME
2.@@SERVICENAME : Returns name of the service
SELECT @@SERVICENAME
3.@@VERSION
: Returns version of SQLSERVER.
select @@VERSION
4.@@ROWCOUNT
: Returns number of rows affected by last executed sql statement
.
select @@ROWCOUNT
5.@@ERROR
: Returns 0 if there is no errors in the last exeucted sql state
ment
or Returns error number
select @@ERROR
TABLE NAME : EMP
BEGIN TRANSACTION
DROP TABLE EMP;
DROP TABLE DEPT;
DROP TABLE SALGRADE;
CREATE TABLE EMP
(
EMPNO INT,
ENAME VARCHAR(10),
JOB VARCHAR(9),
MGR INT,
HIREDATE DATETIME,
SAL INT,
COMM INT,
DEPTNO INT
);
INSERT INTO EMP VALUES(7369,'SMITH','CLERK',7902,'1980-12-17',800, NULL, 20);
INSERT INTO EMP VALUES(7499,'ALLEN','SALESMAN',7698,'1981-02-20',1600,300,30);
INSERT INTO EMP VALUES(7521,'WARD','SALESMAN',7698,'1981-02-22',1250,500,30);
INSERT INTO EMP VALUES(7566,'JONES','MANAGER',7839,'1981-04-02',2975,NULL,20);
INSERT INTO EMP VALUES(7654,'MARTIN','SALESMAN',7698,'1981-09-28',1250,1400,30);

INSERT INTO EMP VALUES(7698,'BLAKE','MANAGER',7839,'1981-05-01',2850,NULL,30);


INSERT INTO EMP VALUES(7782,'CLARK','MANAGER',7839,'1981-06-09',2450,NULL,10);
INSERT INTO EMP VALUES(7788,'SCOTT','ANALYST',7566,'1982-12-09',3000,NULL,20);
INSERT INTO EMP VALUES(7839,'KING','PRESIDENT',NULL,'1981-11-17',5000,NULL,10);
INSERT INTO EMP VALUES(7844,'TURNER','SALESMAN',7698,'1981-09-08',1500,0,30);
INSERT INTO EMP VALUES(7876,'ADAMS','CLERK',7788,'1983-01-12',1100, NULL,20);
INSERT INTO EMP VALUES(7900,'JAMES','CLERK',7698,'1981-12-03',950,NULL,30);
INSERT INTO EMP VALUES(7902,'FORD','ANALYST',7566,'1981-12-03',3000,NULL,20);
INSERT INTO EMP VALUES(7934,'MILLER','CLERK',7782,'1982-01-23',1300,NULL,10);
CREATE TABLE DEPT
(
DEPTNO INT,
DNAME VARCHAR(14),
LOC VARCHAR(13)
);
INSERT INTO DEPT VALUES (10,'ACCOUNTING','NEW YORK');
INSERT INTO DEPT VALUES (20,'RESEARCH','DALLAS');
INSERT INTO DEPT VALUES (30,'SALES','CHICAGO');
INSERT INTO DEPT VALUES (40,'OPERATIONS','BOSTON');
CREATE TABLE SALGRADE
(
GRADE INT,
LOSAL INT,
HISAL INT
);
INSERT INTO SALGRADE VALUES
INSERT INTO SALGRADE VALUES
INSERT INTO SALGRADE VALUES
INSERT INTO SALGRADE VALUES
INSERT INTO SALGRADE VALUES
COMMIT;

(1,
(2,
(3,
(4,
(5,

700,
1201,
1401,
2001,
3001,

1200);
1400);
2000);
3000);
9999);

SQL Server Reporting Services


SQL Server Reporting Services (SSRS) is a server-based report generation
software system from Microsoft. It can be used to prepare and deliver a variety
of interactive and printed reports. It is administered via a web interface. Rep
orting services features a web services interface to support the development of
custom reporting applications.
SSRS competes with Crystal Reports and other business intelligence tools
, and is included in Express, Workgroup, Standard, and Enterprise editions of Mi
crosoft SQL Server as an install option. Reporting Services was first released i
n 2004 as an add-on to SQL Server 2000. The second version was released as a par
t of SQL Server 2005 in November 2005. The latest version was released as part o
f SQL Server 2008 in August 2008.
Reporting Services framework contains 3 Components;
1. Report Server
2. Report Manager
3. Report Temporary Database
Architecture Of Reporting Services

______________ _______________
|Report Builder| |Report Designer|
--------------- --------------^
^
|
|
V
V
______________
_____________
|Report Manager|<------------>|Report Server|
-------------------------^
^
|
|
V
V
_____________
_________
|Report Server| | Data |
| Database | | Sources |
---------------------Report Server :
It compiles and executes client requests, Connecting to
the different data sources and loads the required data into temporary databases.
Report manager :
tion of client.

It will verify security information, connections informa

Report Temporary Database : To store the reporting data temporary for processing
purpose.
Generating Sample Report
Start the reporting services;
Start--->programs--->Microsoft SQL Server 2005---> Configuration Tools-->SQL Server Configuration Manager---> Select SQL Server Reporting Services (cli
ck on start)
Start--->Programs--->Microsoft SQL Server 2005---> Business Intelligence
Development Studio
From File Menu---->New--->Project--->Select Report Server Project Wizard
Name : UserReport
Location : c:\Mydata
Click Ok
Click Next
STEP 1:
New data Source
Name

DataSource1

Type

Microsoft SQL Server

Connection String

Click on Edit
Server Name : PEERS\SQLEXPRESS
Select database name

Batch5

Click Test Connection


Click Ok
click Next
STEP 2:
Query String:
SELECT * FROM EMP
Click Next
STEP 3:
Select Report Type
Select Tabular
click Next
STEP 4:
Select the columns for Groups and details;
Groups : Deptno
Details : Empno,Ename,Job,Sal,Comm
Click Next
STEP 5:
Select Stepped
Check Include Subtotals
Click Next
STEP 6:
Select Table Style (Bold)
Click Next
STEP 7:
Report Server : http://localhost/ReportServer
Deployment Folder : UserReport
Click Next

STEP 8:
Report Name

Report1

Check Preview Report


Click On Finish
SQL Server Analysis Services (SSAS):
SQL Server supports to get data into a SQL Server database and then later gettin
g the same data out of the database. We are provided with how to create tables,
insert data, and use SQL statements, views, and stored procedures to retrieve th
e data. This pattern of activity, where individual actions deal with small piece
s of the database, is often called as online transaction processing, or OLTP.
The another use of databases, specially large databases. Suppose you run an onli
ne book store and have sales records for 50 million book sales.
Searching for the data and summarizing them is called online analytical processi
ng, or OLAP. Microsoft SQL Server 2005 includes a separate program called Micros
oft SQL Server 2005 Analysis Services to perform OLAP analysis.
The basic idea of OLAP is fairly simple. For Example assume book ordering data t
hru online book store, if you want to know how many people ordered a particular
book during each month of the year. It is quite simple to query to get the infor
mation which we require. It may take a long time for SQL Server to extract the d
ata since it should go thru many rows. If data is scattered in various databases
thruout the organization. SQL Server can handle distributed heterogenous querie
s but they are slower.
This is where OLAP comes in. The basic idea is to trade off increased storage sp
ace for speed of querying later. OLAP does this by precalculating and storing ag
gregates. When you identify the data that you want to store in OLAP database, An
alysis Services analyzes it in advance and figures out those yearly, quarterly,
monthly, weekly, and daily numbers
The basic concepts of OLAP include:
Cube
Dimension table
Dimension
Level
Fact table
Measure
Schema

Creating a Batch and Script Files:

Batch is nothing but set of transact SQL statements

executed under single execution plan. Every batch is followed by


GO (which makes a separate execution plan).
Creation of any object, setting any property
should be presented in different batches.
Script is nothing but collection of batches saved in a file
with .sql extension
Advantages:
1. Script files are reusable
2. Script files are used to copy database objects from one system to another sys
tem.
Generating T-SQL scripts for existing database:
SQL Server provides Script wizard to generate Scripts for existing datab
ase and other objects.
Object Explorer ----> Connect to Database Engine ----> Expand databases ----> Se
lect the database----> right click Tasks---->Generate Scripts
STEP 1:
Click next
STEP 2:
Select the database
Check script all objects in Selected Database
Click next
STEP 3:
Provide Scripting options
Append to File = false / true
If true ----- Select existing file
If false ---- new file is created
Script database create = True / False
If true ---- Create db statement generated
If false --- Create db statement will not be generated
Script for server version ---- SQL Server 2005
STEP 4:
Script to File = d:\TEST.sql
STEP 5:
Click Finish
Example: (Creating User Defined Script File)
CREATE DATABASE TESTING
GO
USE TESTING

CREATE
(EMPNO
GO
CREATE
AS
SELECT
GO

TABLE EMPT
INT PRIMARY KEY,EN VARCHAR(12))
VIEW V1
* FROM EMPT

FROM file menu click on save and specify the file name with .SQL extension.

DATA TRANSFORMATION SERVICES (DTS)


OR
SQL SERVER INTEGRATION SERVICES (SSIS)

In SQL Server 2000 we have DTS packages, which are based on COM technology (Comp
onent Object Model)
In SQL Server 2005 it is introduced with SSIS packages which is based on .net te
chnology.
To Import or Export database objects and data from one data source to another da
ta source, we can use DTS or SSIS packages.
SSIS package will support to import or export the database and data between the
following softwares;
SQL
SQL
SQL
SQL

Server <------------>
Server <------------>
Server <------------>
Server <------------>
..... etc

MS-Access
Oracle
SQL Server
Text File/XML Files/Excel Files

DTS or SSIS communicates with any data source with the help of ODBC or OLEDB or
.net data providers.
_______________ ODBC_____________ Data Src
|
DTS/SSIS------ ______ OLEDB_________ Data Source
|
______ .net data providers______Data Source
Data source can be Oracle,SQL Server,..........etc
SQL NATIVE CLIENT interface can be used to communicate with only SQL Server
ODBC --- Open database Connectivity
OLEDB --- Object Linking Embedding Databases
Working Procedure:
Open Object Explorer
|
Connect to Database Engine
|

Select the Server


|
Select any database (Batch5)
|
Right Click and select Import or Export Data.
Example 1: Exporting data from SQL Server to Excel Sheet
Right click on Database and then select Export;
STEP 1: click Next
STEP 2: Specify Source Data
Data Source : SQL Native Client
Server Name : PEERS\SQLEXPRESS
Database
: Batch5
Click Next
STEP 3: Specify Destination
Destination : Microsoft Excel
Excel File Path : c:\empdetails.xls
Check First row has column names
Click Next
STEP 4: Select Copy data from one or more tables or views
Click Next
STEP 5: Select Tables or Views whose data is to be copied into excel sheet.
SELECT EMP,DEPT,SALGRADE,STUDENT tables,v3(view).
Click Next
STEP 6: Check Execute Immediately
Click Next
STEP 7: Click Finish

Example 2: Copy data from SQL Server to SQL Server


Importing the data from one database to the other database.
Select database into which objects should be imported from other database.
Select database (Test)---->Right click tasks---->click on Import data
STEP 1 : Click Next
STEP 2 : Specify Data source

Data Source

: SQL Native Client

Server Name

: PEERS\SQLEXPRESS

Database

: Batch5

Click Next
STEP 3 : Specify Destination
Destination

: SQL Native Client

Server Name

: PEERS\SQLEXPRESS

Database

: Test

Click Next
STEP 4 : Select copy data from one or more tables or

views

Click Next
STEP 5 : Select tables and views to be copied
After selecting
Click Next
STEP 6 : Check Execute Immediately
Click Next
STEP 7 : Click Finish
NOTE:
SSIS packages will be stored in MSDB database.
Browsing SSIS packages:
Object Explorer
|
Connect to Integration Services
|
Select Stored Packages
|
MSDB (System Database)
|
Select package & Right click Run Package

SQL SERVER AGENT :


In SQL Server 2008 SQL Server Agent is a service.
It supports to create Jobs, Schedules, Alerts And Operators.

It provides automatic execution of jobs and tasks associated with differ


ent steps based on system date and time.

To work with SQL Server Agent it is essential that services should get start.
To start the service the following steps should be used.
start--->programs--->Microsoft SQL Server 2005---> Configuration Tools--->SQL Se
rver Configuration Manager---> Select SQL Server Agent (double click on the serv
ices and click on start)

To work with SQL Server Agent;


creating a table:
CREATE TABLE EMP1
(ENO INT IDENTITY,DOJ SMALLDATETIME)
Object Explorer
|
Expand SQL Server Agent
Creating a job, Steps and Schedules:
STEP 1:
Select the jobs, right click and new job
Name

ins_rec_job

Owner

sa

Category:

[Uncategorized [lOCAL]]

STEP 2:
select "steps" from "select a page window"
Click on New
Step Name

ins_rec

Type

Transact-SQL script (T-SQL)

Database

Batch5

Command

INSERT EMP VALUES(getdate())

Click Ok
STEP 3:
Select "Schedules" from "Select a page window"

Click New
Name

sch_ins_rec

Schedule Type

Recurring

Frequency
Occurs :

Daily

Recurrs Every : 1 Day


Daily Frequency
Occurs Every : 1 Min
Click Ok
Click Ok
NOTE:
To execute the created procedure automatically based on a created schedule.
CREATE PROCEDURE insrow
AS
BEGIN
INSERT EMP1 VALUES(getdate())
END
Under steps window, create a new step and provide the command used to execute th
e procedure;
EXEC insrow
SP_RENAMEDB: Here SP stands for Stored Procedure. This stored procedure is used
to change the name of the existing database.
Syntax: SP_RENAMEDB

OLD DATABASENAME ,

E.g.: SP_RENAMEDB

NRSTT ,

NEW DATABASENAME
NRSTTS

The above statement renames (changes the database name) NRSTT to NRSTTS
SP_RENAME: This stored procedure is used for changing the name of the table and
for changing the name of the column
i. Syntax to change the name of the table
SP_RENAME
E.g.

OLD TABLENAME , NEW TABLENAME

SP_RENAME

EMP , EMPLOY

The above stored procedure changes the name of EMP table to EMPLOY
ii. Syntax to change the name of the column

SP_RENAME
E.g.

TABLE.OLDCOLUMN NAME ,

SP_RENAME

NEW COLUMNNAME

STUDENT.ADR , ADDRESS

The above stored procedure changes the name of ADR column to ADDRESS in STUDENT
table.
SP_HELP: This stored procedure is used to display the description of a specific
table.
Syntax: SP_HELP TABLENAME
E.g.: SP_HELP EMP
The above stored procedure displays the description of EMP table
SP_DATADASES: This Stored procedure displays the list of databases available in
SQL Server.
Syntax: SP_DATABASES

SP_TABLES: This stored procedure displays the list of tables available in the cu
rrent database.
Syntax: SP_TABLES
SP_HELPDB: This stored procedure is used to display the description of master a
nd log data file information of a specific database
Syntax: SP_HELPDB Database-Name
Ex: SP_HELPDB SAMPLE
SP_SPACEUSED: This stored procedure is used to find the memory status of the cur
rent database
Creating a Batch and Script Files:

Batch is nothing but set of transact SQL statements executed under singl
e execution plan. Every batch is followed by GO (which makes a separate executio
n plan).
Creation of any object, setting any property should be presented in diff
erent batches.
Script is nothing but collection of batches saved in a file with .sql ex
tension
Advantages:
1. Script files are reusable
2. Script files are used to copy database objects from one system to another sys
tem.

Generating T-SQL scripts for existing database:


SQL Server provides Script wizard to generate Scripts for existing datab
ase and other objects.
Object Explorer ---->
Connect to Database Engine ----> Expand databases ---->
Select the database----> right click Tasks---->Generate Scripts
STEP 1:
Click next
STEP 2:
Select the database
Check script all objects in Selected Database
Click next
STEP 3:
Provide Scripting options
Append to File = false / true
If true ----- Select existing file
If false ---- new file is created
Script database create = True / False
If true ---- Create db statement generated
If false --- Create db statement will not be generated
Script for server version ---- SQL Server 2005
STEP 4:
Script to File = d:\TEST.sql
STEP 5:
Click Finish
Example: (Creating User Defined Script File)
CREATE DATABASE TESTING
GO
USE TESTING
CREATE TABLE EMPT
(EMPNO INT PRIMARY KEY,EN VARCHAR(12))
GO
CREATE VIEW V1
AS
SELECT * FROM EMPT
GO
FROM file menu click on save and specify the file name with .SQL extension.

DATA TRANSFORMATION SERVICES (DTS)


OR
SQL SERVER INTEGRATION SERVICES (SSIS)

In SQL Server 2000 we have DTS packages, which are based on COM technology (Comp
onent Object Model)
In SQL Server 2005 it is introduced with SSIS packages which is based on .net te
chnology.
To Import or Export database objects and data from one data source to another da
ta source, we can use DTS or SSIS packages.
SSIS package will support to import or export the database and data between the
following softwares;
SQL
SQL
SQL
SQL

Server <------------>
Server <------------>
Server <------------>
Server <------------>
..... etc

MS-Access
Oracle
SQL Server
Text File/XML Files/Excel Files

DTS or SSIS communicates with any data source with the help of ODBC or OLEDB or
.net data providers.
_______________ ODBC_____________ Data Src
|
DTS/SSIS------ ______ OLEDB_________ Data Source
|
______ .net data providers______Data Source
Data source can be Oracle,SQL Server,..........etc
SQL NATIVE CLIENT interface can be used to communicate with only SQL Server
ODBC --- Open database Connectivity
OLEDB --- Object Linking Embedding Databases
Working Procedure:
Open Object Explorer
|
Connect to Database Engine
|
Select the Server
|
Select any database (Batch5)
|
Right Click and select Import or Export Data.
Example 1: Exporting data from SQL Server to Excel Sheet
Right click on Database and then select Export;
STEP 1: click Next
STEP 2: Specify Source Data
Data Source : SQL Native Client
Server Name : PEERS\SQLEXPRESS
Database
: Batch5

Click Next
STEP 3: Specify Destination
Destination : Microsoft Excel
Excel File Path : c:\empdetails.xls
Check First row has column names
Click Next
STEP 4: Select Copy data from one or more tables or views
Click Next
STEP 5: Select Tables or Views whose data is to be copied into excel sheet.
SELECT EMP,DEPT,SALGRADE,STUDENT tables,v3(view).
Click Next
STEP 6: Check Execute Immediately
Click Next
STEP 7: Click Finish

Example 2: Copy data from SQL Server to SQL Server


Importing the data from one database to the other database.
Select database into which objects should be imported from other database.
Select database (Test)---->Right click tasks---->click on Import data
STEP 1 : Click Next
STEP 2 : Specify Data source
Data Source

: SQL Native Client

Server Name

: PEERS\SQLEXPRESS

Database

: Batch5

Click Next
STEP 3 : Specify Destination
Destination

: SQL Native Client

Server Name

: PEERS\SQLEXPRESS

Database

: Test

Click Next

STEP 4 : Select copy data from one or more tables or

views

Click Next
STEP 5 : Select tables and views to be copied
After selecting
Click Next
STEP 6 : Check Execute Immediately
Click Next
STEP 7 : Click Finish
NOTE:
SSIS packages will be stored in MSDB database.
Browsing SSIS packages:
Object Explorer
|
Connect to Integration Services
|
Select Stored Packages
|
MSDB (System Database)
|
Select package & Right click Run Package

SQL SERVER AGENT :


In SQL Server 2005 SQL Server Agent is a service.
It supports to create Jobs, Schedules, Alerts And Operators.
It provides automatic execution of jobs and tasks associated with differ
ent steps based on system date and time.
To work with SQL Server Agent it is essential that services should get s
tart.
To start the service the following steps should be used.
start--->programs--->Microsoft SQL Server 2005---> Configuration Tools--->SQL Se
rver Configuration Manager---> Select SQL Server Agent (double click on the serv
ices and click on start)

To work with SQL Server Agent;


creating a table:

CREATE TABLE EMP1


(ENO INT IDENTITY,DOJ SMALLDATETIME)
Object Explorer
|
Expand SQL Server Agent
Creating a job, Steps and Schedules:
STEP 1:
Select the jobs, right click and new job
Name

ins_rec_job

Owner

sa

Category:

[Uncategorized [lOCAL]]

STEP 2:
select "steps" from "select a page window"
Click on New
Step Name

ins_rec

Type

Transact-SQL script (T-SQL)

Database

Batch5

Command

INSERT EMP VALUES(getdate())

Click Ok
STEP 3:
Select "Schedules" from "Select a page window"
Click New
Name

sch_ins_rec

Schedule Type

Recurring

Frequency
Occurs :

Daily

Recurrs Every : 1 Day


Daily Frequency
Occurs Every : 1 Min
Click Ok

Click Ok
NOTE:
To execute the created procedure automatically based on a created schedule.
CREATE PROCEDURE insrow
AS
BEGIN
INSERT EMP1 VALUES(getdate())
END
Under steps window,
create a new step and provide the command used to execute the procedure;
EXEC insrow

Syntax: SP_SPACEUSED
Data Bases In SQL SERVER:
In SQL Server there are two types of databases available.

1. System Defined Databases


2. User Defined Databases
1. System Defined Databases: Complete system level information SQL Server is sto
red in system databases. SQL Server uses system databases to operate user datab
ases. These are also known as Pre-defined databases or Built-in databases, Inclu
des
a.
b.
c.
d.
e.

Master Database
Model Database
MS Database
Temp Database
Sample Databases

a. Master Database: The Master database is the database of all databases . It keep
s track of logon accounts, linked servers, system configuration settings, and mo
re. It also contains initialization settings for SQL SERVER.
b. Model Database: Model is a very special database.
Anything that you place in model db is automatically
propagated to all the databases that you create thereafter.
This means that u can add a state table to model.

That state table then appears in all the new databases. You can include almost a
ny object in Model db.
c. MS Database: The MSDB (Microsoft Database) database is used as an agent betw
een user and SQL Server meantime it concentrates on Back and Recovery Process.
d. Temp Database: Temp Database is used to hold temporary objects which are gen
erated automatically when user start working with SQL Server.
2.User Defined Database: SQL SERVER enables users to create their own databases.
Those are called User Defined Databases.
Syntax:
CREATE DATABASE Database_Name
Ex:
CREATE DATABASE SAMPLE
CLR Integration :
In SQL SERVER 2005 database engine is integrated with CLR (Common Language Runti
me Environment)
Database objects can be created with T-SQL Code + .net language code.
A database object created with T-SQL + .net language code can be called as 'CLR
database object'.
1.
2.
3.
4.
5.

CLR
CLR
CLR
CLR
CLR

stored procedure
User defined functions
Triggers
User defined types
User defined Aggregates

To prepare CLR database object we have 4 steps;


1. Develop .net Assembly
2. Register the assembly in sql server 2005 database.
3. Convert the assembly methods into stored procedure,user defined function, Tri
ggers ....etc
4. Invoke the object thru SQL server
Example:
CLR Function With C#
Start--->Run--->devenv
File--->New--->Project--->Class Library--->MyClr

using
using
using
using
using

System;
System.Collections.Generic;
System.Text;
System.Data;
System.Data.SqlClient;

using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
public class CLRClass
{
[Microsoft.SqlServer.Server.SqlFunction]
public static int MyCLRMethod(int a,int b)
{
return (a+b);
}
}
From Build Menu---->Build MyClr
STEP 2:
Register the Assembly in Sql Server database.
-->
-->
-->
-->

Open Object Explorer from management studio


Connect to database engine
Expand databases
Select database (Batch2)
-->Programmability
-->Assemblies
--> Right Click -- New Assembly (MyCLRAssembly)
Provide the path of the assembly
c:\MyClr\bin\debug\MyClr.dll
click ok
OR

CREATE ASSEMBLY MyCLRAssembly FROM 'C:\MyClr\bin\debug\MyClr.dll' WITH PERMISSIO


N_SET=safe (DEFAULT ACCESS PERMISSION) / UNSAFE/EXTERNAL
Step 3:
CREATE FUNCTION MyCLRTest(i INT,j INT)
RETURN INT
AS
external name MyCLRAssembly.CLRClass.MyCLRMethod

ENABLE / DISABLE CLR Integration


start-->programs-->Microsoft SQL Server 2005
-->Configuration Tools
|
SqlServer Surface Area Configuration
|
Surface Area Cofiguration For Features
|
Select CLR Integration
|
Check ENABLE CLR Integration

|
Click Apply and Click ok
OR
sp_configure 'show_advanced options',1
reconfigure
sp_configure 'clr enabled',1
go
reconfigure
Step 4:
To invoke a function:
SELECT dbo.MyCLRTest(27,89)

Locking :
Locking resolves problems of concurrent access.
It means accessing same data by the no.of users at same time.
Lock types:
1.shared Lock : is placed when ever user to trying read the database(select)
2.Exclusive Lock : is placed when ever you have to trying update
the database (Update)
3.Deadlocks:
Deadlock occurs when two users have locks on separate objects
and each user wants a lock on the other's object.
For example, User1 has a lock on object "A"
and wants a lock on object "B" and User2 has a lock on object
"B" and wants a lock on object "A". In this case, SQL Server 6.5 ends a deadloc
k by choosing the user, who will be a deadlock victim. After that, SQL Server ro
lls back the breaking user's transaction, sends message number 1205 to notify th
e user's application about breaking, and then allows the nonbreaking user's proc
ess to continue.
You can decide which connection will be the candidate for deadlock victim by usi
ng SET DEADLOCK_PRIORITY. In other case, SQL Server selects the deadlock victim
by choosing the process that completes the circular chain of locks.
So, in a multiuser situation, your application should check for message 1205 to
indicate that the transaction was rolled back and if so, to restart the transact
ion.

Note. To reduce the chance of a deadlock, you should minimize the size of transa
ctions and transaction times.

Viewing locks (sp_lock)


sp_lock
This is the result set of sp_lock stored procedure:
spid
------11
11

locktype
table_id
page
dbname
----------------------------------- ----------- ----------- ------------Sh_intent
Ex_extent

688005482
0

0
336

master
tempdb

example :
begin transaction
declare c2 cursor for select * From employee for update
select * from employee
update employee set eno=1100 where eno=1010
commit transaction
Locking optimizer hints
SQL Server 2005 supports the following Locking optimizer hints:
ROWLOCK
PAGLOCK
NOLOCK
HOLDLOCK
UPDLOCK
TABLOCK
ROWLOCK
Use row-level locks when reading or modifying data.
syntax:
SELECT au_fname FROM pubs..authors (rowlock)
PAGLOCK
Use page-level locks when reading or modifying data.
TABLOCK
Use a table lock when reading or modifying data.
DBLOCK
Use a database lock when reading or modifying data.
UPDLOCK
UPDLOCK reads data without blocking other readers, and update it later with the
assurance that the data has not changed since last read.
XLOCK

Use exclusive locks instead of shared locks while reading a table, and use hold
locks until the end of the statement or transaction.
HOLDLOCK
Use a hold lock to hold a lock until completion of the transaction, instead of r
eleasing the lock as soon as the required table, row, or data page is no longer
required.
NOLOCK
This does not lock any object. This is the default for SELECT operations. It doe
s not apply to INSERT, UPDATE, and DELETE statements.
Examples:
SELECT OrderID
FROM Orders (WITH ROWLOCK)
WHERE OrderID BETWEEN 100
AND 2000
UPDATE Products (WITH NOLOCK)
SET ProductCat = 'Machine'
WHERE ProductSubCat = 'Mac'
example 2:
BEGIN TRAN
SELECT * FROM test1
WITH (HOLDLOCK, ROWLOCK)
WHERE Name = Rahul4'
update test1 set Name =
where Name= Rahul5'

Rahul6'

COMMIT TRAN
Replication is a set of technologies
for copying and distributing data and database objects
from one database to another and then synchronizing
between databases to maintain consistency.
Using replication, you can distribute data to different
locations and to remote or mobile users over local and
wide area networks, dial-up connections, wireless connections,
and the Internet.
Replication Types
Microsoft SQL Server 2005 supports the following types of replication:
Snapshot Replication
Transactional Replication
Merge Replication

Snapshot Replication
Snapshot replication is also known as static replication.
Snapshot replication copies and distributes data and database objects
exactly as they appear at the current moment in time.
Subscribers are updated with complete modified data and not by
individual transactions, and are not continuous in nature.
This type is mostly used when the amount of data to be
replicated is small and data/DB objects are static
or does not change frequently.
Transactional Replication
Transactional replication is also known as dynamic replication.
In transactional replication, modifications to the publication
at the publisher are propagated to the subscriber incrementally.
Publisher and the subscriber are always in synchronization
and should always be connected.
This type is mostly used when subscribers always need the
latest data for processing.
Merge replication
It allows making autonomous(self-governing) changes to replicated data on the
Publisher and on the Subscriber. With merge replication,
SQL Server captures all incremental data changes in the source
and in the target databases, and reconciles conflicts according to
rules you configure or using a custom resolver you create.
Merge replication is best used when you want to support
autonomous changes on the replicated data on the Publisher
and on the Subscriber.

replication tools:
Publisher is a server that makes the data available for

subscription to other servers.


In addition to that, publisher also identifies
what data has changed at the subscriber during the synchronizing process. Publis
her contains publication(s).
Subscriber is a server that receives and maintains the published data.
Modifications to the data at subscriber can be propagated back to the
publisher.

Distributor is the server that manages the flow of data through


the replication system. Two types of distributors are present,
one is remote distributor and the other one local distributor.
Remote distributor is separate from publisher and is configured as
distributor for replication.
Local distributor is a server that is configured as publisher
and distributor.
Agents are the processes that are responsible for
copying and distributing data between publisher and subscriber.
BACKUP & RECOVERY OF DATABASE:
Backup of Database:
As system is an electronic device, at any point of time it may come acro
ss with a problem in hardware at at os or at db, due to which data available in
db may be lost.
In order to have security for data and database objects, it is essential
that at the end of a day to go for a backup. It creates a backup of database in
to flatfiles. Backup data later can be transfered into other external devices fo
r security reasons.
Backup can be created in different ways;
1. Full backup
2. Differential backup
Syntax:
BACKUP DATABASE <db_name>
TO DISK='DRIVE:\PATH'
File name should be provided with an extension as .bak

Creating a backup with GUI.


Connect to Database Engine,
Object Explorer
Databases
Batch2
Right click, Tasks ,
EXAMPLES:
FULL BACKUP:
BACKUP DATABASE BATCH2
TO DISK='C:\MYDATA\B2.BAK'
DIFFERENTIAL BACKUP:
BACKUP DATABASE [Batch2] TO
DISK = N'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Backup\Batc
h2.bak'
WITH DIFFERENTIAL , NOFORMAT, NOINIT,
NAME = N'Batch2-Differential Database Backup',
SKIP, NOREWIND, NOUNLOAD,
STATS = 10
GO
Restore of Database:
Database can be restored in a same system or it can be on different syst
em.
Syntax:
RESTORE DATABASE db_name
FROM DISK='DRIVE:\PATH'
DEPLOYMENT OF DATABASE:
The process of copying database objects structure with data from one ser
ver to another server is called Deployment of database.
Method 1:
Copy backup file (.bak) to destination system.
Restore it on destination system
Method 2:
Copy data files and log files to destination system
1. Detach the database on Source System

sp_detach_db database_name
2. Copy the database files to any location on destination System
3. Attach these files to a database on destination system.
Syntax:
CREATE DATABASE database_name
ON
(FILENAME='path of a file')
FOR ATTACH

XML Integration

In SQL SERVER 2005 XML integration is introduced, which supports to stor


e and access the data in XML format.
I) 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 <mode>,ROOT(name)
Mode can be classified like RAW, AUTO, PATH
EXAMPLES:
SELECT empno,ename,deptno FROM emp
FOR XML RAW
OUTPUT:
<row empno="1001" ename="RAJ" deptno="20" />
<row empno="1010" ename="JAMES" deptno="10" />
SELECT empno,ename,deptno FROM emp
FOR XML AUTO,ROOT('EMPINFO')
OUTPUT:
<EMPINFO>
<emp empno="1001" ename="RAJ" deptno="20" />
<emp empno="1010" ename="JAMES" deptno="10" />
</EMPINFO>

SELECT empno,ename,deptno FROM emp


FOR XML PATH,ROOT('EMPINFO')
OUTPUT:
<EMPINFO>
<row>
<empno>1001</empno>
<ename>RAJ</ename>
<deptno>20</deptno>
</row>
<row>
<empno>1010</empno>
<ename>JAMES</ename>
<deptno>10</deptno>
</row>
</EMPINFO>
II) Storing XML data into table:
1. Data which is represented in XML format, can be stored into a table in the fo
rm of rows and columns using OPENXML()
2. XML data is converted in table format by creating a temporary memory and it i
s 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 tha
t table. It can be used when that temporary table is to be removed.
arg2 is a variable which contains the data in XML format.
3. use INSERT INTO SELECT query.
4. 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.
example:
CREATE TABLE EMPX
(ENO INT,EN VARCHAR(12))
DECLARE @xmldoc VARCHAR(500),@p INT
SET @xmldoc='<ROOT>
<emp eno="9001" en="Prasad" />
<emp eno="9002" en="Sunil" />
<emp eno="9010" en="Kiran" />
</ROOT>'
EXEC sp_xml_preparedocument @p OUTPUT,@xmldoc
INSERT INTO empx SELECT * FROM OPENXML(@p,'/ROOT/emp',1)
WITH

(eno INT,en VARCHAR(12))


EXEC sp_xml_removedocument @p
III) Working with XML datatype:
XML data type has been introduced in SQL SERVER 2005.
It supports to insert the data in XML format using INSERT command.XML Is case se
nsitive.
xML data type provides default memory of 2GB
example:
CREATE TABLE empt
(eno INT,info XML)
INSERT INTO empt VALUES(101,'<EMP>
<ENAME>XYZ</ENAME>
<SAL>1000</SAL>
</EMP>')
INSERT INTO empt VALUES(101,'<EMP>
<ENAME>ABC</ENAME>
<SAL>2000</SAL>
</EMP>
<EMP>
<ENAME>PQR</ENAME>
<SAL>3000</SAL>
</EMP>')
query() : This function will support to retrieve the required attribute informat
ion 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 w
ith column name created witeL datatype.
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 elemen
t exist else returns with 0.
SELECT info.exist('/EMP/SAL') FROM empt

SQL Server 2005 Workbench Platform


The SQL Server 2005 Workbench suite consists of five basic tools:

1.SQL Server Relational Database used to create relational database


2.Analysis Services used to create multidimensional model
(measures, dimensions and schema)
3.Data Transformation Services (DTS)
used to extract, transform and load data from source(s) to the data ware house o
r schema
4.Reporting Services used to build and manage enterprise reporting using the relat
ional or multidimensional sources
5. Data Mining used to extract information based on predetermined algorithms.
Data Mining.
Data mining is a term that refers to searching a large data set
in an attempt to detect hidden or low-level patterns.
Analysis Services provides tools for
data mining with which you can identify rules and
patterns in your data, so that you can determine why
things happen and predict what will happen in the future giving
you powerful insight that will help your company make
better business decisions.
Data mining is a term that refers to searching a large data set
in an attempt to detect hidden or low-level patterns.
What is OLTP?
OLTP is abbreviation of On-Line Transaction Processing.
This system is an application that modifies data the instance
it receives and has a large number of concurrent users.
What is OLAP?
OLAP is abbreviation of Online Analytical Processing.
This system is an application that collects, manages,
processes and presents multidimensional data for
analysis and management purposes.
What is the difference between OLTP and OLAP?
Data Source
OLTP: Operational data is from original data source of the data
OLAP: Consolidation data is from various source.
Process Goal
OLTP: Snapshot of business processes which does fundamental business tasks
OLAP: Multi-dimensional views of business activities of planning and decision ma
king
Queries and Process Scripts
OLTP: Simple quick running queries ran by users.

OLAP: Complex long running queries by system to update the aggregated data.
Database Design
OLTP: Normalized small database. Speed will be not an issue due to smaller datab
ase and normalization will not degrade performance. This adopts entity relations
hip(ER) model and an application-oriented database design.
OLAP: De-normalized large database. Speed is issue due to larger database and de
-normalizing will improve performance as there will be lesser tables to scan whi
le performing tasks. This adopts star, snowflake or fact constellation mode of s
ubject-oriented database design

1.

XML Format

It is new feature in SQL Server 2005 version which will display the table data i
n
XML format which in between open tag < and closed tag /> .
This format basically useful to the .Net developers
Syntax : SELECT {*/ Columns list} FROM TABLENAME FOR XML AUTO
Ex: SELECT * FROM EMP FOR XML AUTO
The above select statement will generate a file preceded by xml, if you click on
that file then automatically emp table data will be converted into XML format

Microsoft Sqlserver 2008R2 Features


--merge command
merge into employee1 as t
using employee s
on(s.empno=t.empno)
when matched then
update set t.ename=s.ename
when not matched by target then
insert values(s.empno,s.ename)
when not matched by source then
delete;
-- pivot
select 'total_salary' as dept_num,[10],[20],[30]
from (select deptno ,sal from emp) as s
pivot
(
sum(sal) for deptno in([10],[20],[30])) as t
--GROUPING SETS

select job,deptno,SUM(sal)
from emp
group by job,DEPTNO with rollup
select job,deptno,SUM(sal)
from emp
group by job,DEPTNO with CUBE
-- sparse columns
create table sparse_table
(
empno int sparse null,
ename varchar(10)
)
create table test_table
(
a date,
b time
)
select * from test_table
insert into test_table values('2011-01-01','01:50:50:250')
sp_help test_table

Potrebbero piacerti anche