Triggers

Triggers are one of the database object,which performs their own operation when user performs any DML operation on a specific table.

or

Trigger is a type of stored procedure that implicitly executed when user performs DML operation on the table. It will not accept any parameters.

Types of Triggers:

1. After Trigger: These are the triggers,which performs their own operation after performing insert,delete,and update operations on a specific table.

Syntax:

CREATE TRIGGER TRIGGERNAME ON TABLENAME FOR/AFTER {INSERT/UPDATE/DELETE}
AS
BEGIN
SQL STATEMENT
END

A)INSERT TRIGGER: This trigger fires when user performs insert operation on the table.When user insert a record into the table the temporary table called inserted is created the newly inserted record is also stored table temporarily.
B)DELETE TRIGGER: This trigger fires when user performs delete operation on the table.When user delete a record from the table the temporary table called deleted is created the deleted record is also stored in deleted table temporarily.
C)UPDATE TRIGGER: This trigger fires when user performs update operation on the table.When user update a record into the table the temporary tables called inserted and deleted are created the new values placed into inserted table and old values will be placed in deleted table temporarily.

Example:
CREATE TRIGGER T1 ON DEPT FOR INSERT
AS
BEGIN
INSERT INTO DEPT1 SELECT * FROM INSERTED
END

The above triggers fires after performing INSERT operation on DEPT table. It will inserts the newly inserted records into DEPT1.

2)Instead of Triggers:These are the triggers,which performs their operations instead of performing user specified operations.

Syntax: CREATE TRIGGER TRIGGERNAME ON TABLE NAME INSTEAD OF {INSERT/UPDATE/DELETE}
AS
BEGIN
SQL STATEMENT
END

Example:CREATE TRIGGER T4 ON DEPT INSTEAD OF INSERT,UPDATE,DELETE
AS
BEGIN
PRINT 'THESE OPERATIONS ARE NOT ALLOWED'
END

The above trigger fires automatically and shows a message THESE OPERATIONS ARE NOT ALLOWED, when user try to perform INSERT,UPDATE,DELETE operations on DEPT table.
Share/Bookmark

FORWARD_ONLY CURSOR

This is the most unused logical area because it supports only NEXT operation.

Example: DECLARE FC CURSOR FORWARD_ONLY FOR SELECT * FROM DEPT

OPEN FC

FETCH FIRST FROM FC

Error Message

FETCH NEXT FROM FC

15 SALES LONDON

CLOSE SC

DEALLOCATE FC
Share/Bookmark

KEYSET CURSOR

This is the logical area, which is useful only when there is a primary key in the table. This logical area holds only Primary Key column values. Based on the key column values in the logical area (Cursor) the rest column values are coming from physical area (Table).

Example: DECLARE KC CURSOR KEYSET FOR SELECT * FROM DEPT

OPEN KC

FETCH FIRST FROM KC

10 SALES LONDON

UPDATE DEPT SET LOC=’LOSSANGLES’ WHERE LOC=’LONDON’

FETCH FIRST FROM KC

10 SALES LONDON

UPDATE DEPT SET DEPTNO=15 WHERE DEPTNO=10

FETCH FIRST FROM KC

0 NULL NULL

CLOSE KC

OPEN KC

FETCH FIRST FROM KC

15 SALES LONDON

CLOSE KC

DEALLOCATE KC

Note: Dynamic updations are not possible on key column of the keyset cursor, we have to close the cursor and we need to reopen it for the modified values.
Share/Bookmark

DYNAMIC CURSOR

This is the logical area in which dynamic updations possible. We need to close and reopen the cursor for the modified values.

Example: DECLARE DC CURSOR DYNAMIC FOR SELECT * FROM DEPT

OPEN SC

FETCH FIRST FROM DC

15 SALES LONDON

UPDATE DEPT SET DEPTNO=10 WHERE DEPTNO=15

FETCH FIRST FROM DC

10 SALES LONDON

Note: ABSOLUTE N will not be supported by the dynamic cursor because dynamic updations are possible.
Share/Bookmark

STATIC CURSOR

This is the logical area in which dynamic updations not possible. If we want those updations in logical area we close the cursor and we need to reopen it.

Example: DECLARE SC CURSOR STATIC FOR SELECT * FROM DEPT

OPEN SC

FETCH FIRST FORM SC

10 SALES LONDON

UPDATE DEPT SET DEPTNO=15 WHERE DEPTNO=10

FETCH FIRST FROM SC

10 SALES LONDON

FETCH ABSOLUTE -2 FROM SC

30 IR BAN

FETCH FIRST FROM SC

15 SALES LONDON

FETCH RELATIVE 2 FROM SC

30 IR BAN

FETCH RELATIVE -2 FROM SC

15 SALES LONDON

CLOSE SC

DEALLOCATE SC
Share/Bookmark

Cursors

Cursor is a logical area, which is used to retrieve a particular nth record. Selecting a particular nth record is not possible through physical area (Table). In such situations one logical area (Cursor) we can create and then we can select a particular nth record. Cursors are used to store transaction information temporarily.

Types of Cursors:

1. Static Cursor
2. Dynamic Cursor
3. Keyset Cursor
4. Forward_Only Cursor

Syntax to declare the Cursor:

DECLARE CURSORNAME CURSOR CURSORTYPE FOR SELECT * FROM TABLENAME

Syntax to open the Cursor:

Open cursorname

Syntax to fetch the records from cursor:

Fetch {first/next/prior/last/absolute/relative n} from cursorname

Syntax to close the cursor:

Close cursorname

Syntax to deallocate the cursor:

Deallocate cursorname

FIRST: Fetches first record from the cursor

NEXT: Fetches next record from the current position of the cursor

PRIOR: Fetches previous record from the current position of the cursor

LAST: Fetches last record from the cursor

ABSOLUTE N: Fetches nth record from the top of the cursor if n positive fetches the nth record from bottom of the cursor if n is negative. Where n is an integer.

RELATIVE N: Fetches nth next record from current position of the cursor if n is positive fetches nth previous record from the current position of the cursor if n is negative where n is an integer.
Share/Bookmark

Table Valued function

These functions will return entire table to the calling environment.

Syntax:
CREATE FUNCTION (PARA 1 DATA TYPE………………)
RETURNS TABLE
AS
BEGIN

RETURN (SELECT STATEMENT)
END

Example : Write a function to return entire dept table
CREATE FUNCTION F3()
RETURNS TABLE
AS
BEGIN
RETURN (SELECT * FROM DEPT)
END
Share/Bookmark

USER DEFINED FUNCTIONS

Functions created by user are called user defined functions:
Types of user defined functions:
A. Scalar valued functions
B. Table values functions

Scalar valued functions: These functions will return a scalar value to the calling environment

Syntax: CREATE FUNCTION < FUNCTION_NAME > (@PARA 1 DATA TYPE, @PARA 2 DATATYPE,….) RETURNS
AS
BEGIN
DECLARE @VARIABLE DATATYPE
…….
………….
RETURN @VARIABLE
END
Syntax to execute the user defined function:
SELECT/PRINT DBO.FUNCTIONNAME(VALUE1,VALUE2,…………)

Note: The number of values supplied through PRINT/SELECT statement must be equal to the number parameters.

Example: Write a function to find the product of two numbers
CREATE FUNCTION F1 (@A INT,@B INT)
RETURNS INT
AS
BEGIN
DECLARE @C INT
SET @C = @A * @B
RETURN @C
END
SELECT/PRINT DBO.F1 (3,5)
Share/Bookmark

Programming constructs

Programming constructs:
Programming constructs are used to execute the set of sql statements as a unit. These are also known as Control Structures.
1. If-else
2. Begin-end
3. While

If-else: It is used to execute the statement based on condition.
Syntax: if (condition)
Begin

End
Else
Begin

End
If condition is true then statement1 is executed otherwise statement2 will be executed.

While: If the condition is true then statements under while will be excluded repeatedly until the given condition false
Syntax:
While (condition)
Begin

statement1
statement1
statement1
……………….
End.

Named Batches: Set of T-Sql statements can written and executed as a single unit with a proper name called Named Batch. These includes
a. Stored procedures
b. User defined functions
c. Triggers
Stored procedures: Stored procedures are one of the database objects. There are two types of stored procedures available in Sql Server.
a. System Defined Stored Procedures
b. User Defined Stored Procedures
System Defined Stored Procedures: These are also known as predefined or built- in stored procedures.
Example:
SP_HELP
SP_RENAMEDB
SP_RENAME
SP_HELPCONSTRAINT
SP_HELPTEXT
……
…..
……

User Defined Stored Procedures: Procedures created by the user are called used defined stored procedures.
Syntax: create proc [edure] procedurename [@para 1 datatype (size)[=default_value][output]@ para 2 datatype (size)[=default_value][value],…..]
As
begin
select statement
end

Syntax to execute the user defined stored procedure:
Exec [ute] procedurename [value1,value2,……]

Note: The number of values supplied through EXEC statement must be equal to the number parameters.

Example1: write a Procedure to select the data from EMP table.
CREATE PROCEDURE P1
AS
BEGIN
SELECT * FROM EMP
END
EXEC P1

Example2: Write a procedure to add two numbers
CREATE PROCEDURE P3 @A INT=10,@B INT=20
AS
BEGIN
DECLARE @C INT
SET @C=@A+@B
PRINT @C
END
EXEC P3
Output: 30
EXEC P3 25,45
Output: 70

Note: Server will give highest priority to the user supplied values rather than default values.
Share/Bookmark

BATCH STATEMENTS

A Batch is a collection T-Sql statements can be written and executed as a single unit

A batch may be
1. Anonymous Batch / Name less Batch
2. Named Batch

Anonymous Batch / Name less Batch:
Set of T-Sql statements can written and executed as a single unit without any proper name Anonymous batch or Nameless batch.
Variable:Variable is nothing but a memory element, which can be varied through out the program execution.
Types of variables:
In Sql Server there existed two types of variables.

A. Global variables: These are the variables which can be accessible by any user, any database, any function, any procedure. These variables are preceded by a special symbol ‘@@’. These are also known as “Public variables”.
Examples:
select @@Servername
select @@Version
select @@Language
………………………….
…………………………………

B. Local variables: These are the variables which can be accessible by particular user, particular database, particular function, and particular procedure. These variables are preceded by a special symbol ‘@’. There are also known as “Private variables”.
Syntax: to declare the local variables:
Declare @varaiblename datatype,………….
Example: declare @x int, @y varchar(20)
Syntax to assign the values:
Set @variablename = value/expression
Example:
Set @x=125
Set @y=’NRSTT’
Set @z=@A+@B

Print statement:
This statement is used for printing the output in result window.
Syntax: Print @ variablename/constant
Example:
print @x
print @y
print ‘sqlserver’

comments:

In sql server comment is nothing but a non-executable statement we can make a single line / multiple lines as comments
--for single line comment
/*------------
----------*/ for multiple line comments
Share/Bookmark

INDEXES

Indexes in sql server is similar to index in text book…Indexes are used to improve the performance of queries.

Indexes are generally created for following columns:

Primary key column
Foreign key column: frequently used in join conditions.
Column which are frequently used in where clause
Columns, which are used to retrieve the data in sorting order.

Indexed cannot be created for following columns:

The columns which are not used frequently used in where clause
Columns containing the duplicate and null values
Columns containing images, binary information, and text information.

Types of Indexes:

1. Clustered index
2. Non-clustered index
3. Unique index
Composite index

Clustered index:

only one clustered index is allowed per table. The order of values in a table order of values in index is also same. When cluster index is created on table data is arranged in ascending order cluster index will occupy 5% of the table.

Syntax: create clustered index indexname on tablename (column)

Example: create clustered index c1 on emp (empno)

NonClustered index:

It is the default index created by the server the physical order of the data in the table is different from the order of the values in index.

Max no. Of non-clustered indexed allowed for table is 249

Syntax: create nonclustered index indexname on tablename (columns)

Example: create nonclustered index NCI on emp (ename, sal)

Unique Index:

An index with unique constraint. It will not allow duplicate values.

Syntax: create unique index indexname on tablename (column)

Example: create unique index UI on dept (dname)

Composite Index:

If a unique index is created on more than one column is called composite index.

Create unique index coi on dept (deptno, dname)

Sp_HelpIndex:

This stored procedure is used to display the list of indexes, which have been placed on different columns of a specific table.

Example: sp_helpindex emp

Syntax:

Drop index tablename . indexname

Example: drop index dept. ui
Share/Bookmark

SET OPERATORS

Set operators in sql server are used to combine the output of multiple queries.
When ever we want to combine the output of multiple queries we have to identify three factors.

1.Whether the multiple queries contains equal number of columns or not?
2.If they are equal again we have to identify whether their data types are equal or not?
3.We have to identify whether the output column name coming from first query or not?

In Sql Server there existed four types of Set Operators

1. Union all
2. Union
3. Intersect
4. Except

Union all: It combines the output of multiple queries including duplicate values.

Syntax: select column1, column2………from table1 union all select column1, column2….from table2

Example: select empno from emp union all select detpno from dept

Union: It combines the output of multiple queries without considering duplications values, mean time it arranges output data in ascending order.

Syntax: select column1, column2………from table1 union select column1, column2….from table2

Example: select empno from emp union select detpno from dept

Intersect: It selects the common values from given set of queries.

Syntax: select column1, column2………from table1 intersect select column1, column2….from
table2

Example: select empno from emp intersect select detpno from dept
Expect: It selects particular values from the first query which are not available in second query.

Syntax: select column1, column2………from table1 expect select column1, column2….from
table2

select empno from emp expect select detpno from dept
Share/Bookmark

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 base table. There are two types views available in Sql Server.

Note: If we perform any modifications in base table, then those modifications automatically effected in view and vice-versa.

1. Simple Views:

Creating View by taking only one single base table.

Syntax
: create view viewname [with encryption] as select * from tablename [where condition][with check option]

Example: 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 into view v1.

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 because this encryption option hides the definition.

Example:

create view v4 with encryption as select * from emp where deptno=20

Sp_Helptext v4

Output: Object Comments have been 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

Example:

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 only one multiple base tables.

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

Create view viewname [with encryption] as select * from viewname [where condition][with check option]

Example: create view v5 as select * from v1 where deptno=10

Syntax: to drop the views:

Drop view viewname […N]

Example: drop view v1,v2,v3,v4,v5
Share/Bookmark

Functions

A function is nothing but a sub program or a module which can written for achieving a particular task.

OR

A function is a readymade formula, which takes values as input and returns values as output.

OR

A function is a pre defined program segment that carries specific and well-defined task.

Classifications of Functions:

1. Scalar or Single-Valued Functions
2. Group or Aggregate Functions

Scalar Valued Functions:

These functions take single value as input and returns single value as output.

Classification of Scalar Valued Functions:

1. Mathematical functions
2. String Functions
3. Date & Time Functions

Mathematical Functions:

ABSOLUTE: It returns the ABSOLUTE value of N

->Select ABS (-10.65)
->Select ABS (18.67)

Power (M, N): It returns the Power N Value

->Select Power (3, 2) = 9
->Select Power (6, 2) =36

String Functions:

ASCII (CH): It returns the ASCII value of given character.
-> Select ASCII (‘A’) =65
-> Select ASCII (‘a’) =97
-> Select ASCII (‘o’) =48
-> Select ASCII (‘ ’) =32

Date Functions:

Get DATE(): It returns the current date and time

-> Select GetDate ()

Aggregate or Group Functions:
These functions takes multiple values as input and returns single value as output, these includes
Max ()
Min ()
Sum ()
Avg ()
Count ()
Count_big ()

Based on the above table we will do some examples for Aggregate functions
Example: Select max (sal) as Hisal from emp
Hisal = 20000

Group by Clause:

This clause is used to divide the table into number of subgroups based on a specific column.

Syntax: select statement Group by column name
Share/Bookmark