You are on page 1of 74

1) Introduction Database: A database is a collection of multiple tables. Tables are the part of the database.

Tables: Tables are database objects that contain all the data present in a database. A table is a collection of rows and columns. Columns---2power 10 1024 Rows-------2powere 20 1048576 Structure Query Language:(consist of) DDL Data Definition Language (Create, Alter, Drop, Truncate) DML Data Manipulating Language (Insert, Update, Delete, Select) DCL Data Control Language (Revoke, Commit, Rollback, Grant) Flat File: A flat file is a file containing records that have no structure. DBMS: (Database Management System) A database management system can be defined as a collection of related records and a set of programs that

access and manipulate these records. Database Management System enables one to enter, store and manage this data. //The main disadvantage with these DBMS packages was that the data was stored in the Flat file format. How is the Database System Beneficial The amount of redundancy in the stored data can be reduced (In an organization, several departments often store the same data. Maintaining a centralized database helps the same data to be accessed by many departments. Thus duplication of data or data redundancy can be reduced.) No more inconsistencies in data (Since there is a central database, it is possible for one person to take up the task of updating the data on a regular basis.) The Stored data can be shared. (A central database can be located on a server, which can be shared by several users. In this way everybody can access the common and updated information all the time). Standards can be set and followed (A central control ensures that a certain standard in the representation of data can be set and followed) ex. Format of user name

Data Integrity can be maintained (Maintaining Data Integrity refers to ensuring of data in the database) Security of data can be implemented (In a central database system, the privilege of modifying the database is not given to everyone)

RDBMS: (Relational Database Management System) A relational database is a database based on the relational model. A relational database management system or RDBMS is a suite of software programs for creating, maintaining, modifying and manipulating a relational database. It can also be used to create an application that a user will require for interacting with the data stored within the database.

2) Tables Creating Tables: Syntax: Create Table <Table Name> (<Column_Name> <Data_Type>) Example: create table

login (userid int, username varchar(20), password varchar(20), type char(5)) Modifying Table: Syntax: Alter Table <Table_Name> [Alter Column <Column_name> <New_data_type>] [Add [Column_name <Data_Type>] | (Drop Column <Column_Name> Example: alter table login alter column type varchar(50) alter table login add test varchar(10) alter table login drop column test alter table nnn drop column empdept Adding Row: Syntax: Insert [into] <Table_Name> Values <values> Example: insert into login values (1,'kaleem','test', 'admin')

Updating Row: Syntax: Update <Table_Name> Set <Column_name = Value> [Where <Search Condition>] Example: update login set username='kal', password='testing',type='user' where userid=1 Deleting Row: Delete from <table_name> [Where <search _condition>] Example: Delete from login where userid=1 View Table: To view the data in the table Syntax: Select <select_list> From <table_name>

Example: Select * from login Removing Table: Syntax: Drop table <table_name> Example: Drop Table login Remove Database: Syntax: Drop database <database_name> Example: Drop database test 3) Overview of Sql Server Using Select Statement The select statement retrieves rows and columns from a table and presents the result set. It can also be used to join two tables together or to retrieve a subset of columns from one or more tables. The select statement defines the columns to be used for query. It is a series of expressions separated by commas. Each expression defines a column in the result set. The Columns in the result set are in the same sequence as the order of the expression in the select statement.

Choosing All the columns Select * from login Here asterisk(*) is used to retrieve all the columns from the table. Choosing selected columns To select few columns from a table, list them out by name. Syntax: Select <column1>, <column2> from <table_name> Example: Select username, userid, type from login Constants in Query Result Set Character String constant is included for proper formatting or readability when character columns are concatenated. Constants are not usually specified as a separate column in a result set. It is usually more efficient for an application to build the constant value into the results when they are displayed. For example to include character : and -> in the result set retrieved from the table.

Select statement will be like this: select username +':' + password +'->' + type from login Assigning Result Set Column Name The As clause can be used either to change the name of a result set column or assign a name to derived column. If you want to make heading more understandable, you can customize those headings using As Clause. Example: select username +':' + password +'->' + type as testing from login or Select username as 'User Name' from login Computed values in the selected list The table used in the form clause of a query is called a base table. Calculating from the values stored in the base tables. Example: select prod_id, prod_name, price, price * .01 as Discount from product

Eliminating Duplicates with Distinct The Distinct keyword eliminates duplicate rows from the resultset of a Select statement. If Distinct is not specified, all rows are returned, including duplicates. Example: Select distinct username from login Limiting Result sets using TOP and PERCENT The Top Clause limits the number of rows returned in the result set. Syntax: Select TOP n <Column_name> from <table_name> Example: select top 3 * from product select top 3 prod_id, prod_name from product Similarly, you can also retrieve a percentage of records from the table. Example:

Select Top 40 percent * from product It will display 40 percent of the total rows from the beginning. Filtering Rows from a table using where clause There are two type of filtering: Vertical Filtering: Vertical filtering means selecting few columns from the table Horizontal Filtering: Horizontal filtering means selecting few rows from the table Where Clause: The option Where Clause in a query acts as a filter to limit the number of rows returned based on the specified condition. Only those rows that match the condition are displayed in the result set. Syntax: Select <Column name> from <table_name> where <Condition> Example: Select * from login where username='hari' Using Relational Operators and Wild Card Characters

You can use different types of search conditions and comparison operators where constructing Where clause. Different Type of Comparison Operators is given below. Operator = > < >= <= <> ! Using Like The following SQL statement will return persons with first names that start with an 'P': select * from product where prod_name like 'p% The following Sql statement will return person name ends with a letter L: select * from product where prod_name like '%l' Meaning Equal to Greater than Less than Greater than or equal to Less than or equal to Not equal to Not

The following SQL statement will return persons with first names that contain the pattern 'EN': select * from product where prod_name like '%en%' Logical Operators: The Logical operators are AND, OR, and NOT And joins two conditions and returns true only when both conditions are true. Or are connects two conditions, but it returns true when either of the condition is true. Not rejects the search condition Example: select * from login where not type='user' Sorting the rows with Order by The Order by clause sorts query result by one or more columns, Sort can be ascending (Asc) or desending (Desc). By default, the records are sorted in Asc order. Example: Select * from login order by username

Select * from login order by username desc 4) Advanced Query Techniques Querying Multiple Tables We learnt how to retrieve data from a single table. Now in the following section, we will learn to combine data from multiple tables. It is not possible to store the entire data in a single table. When data is stored in different tables, we need to combine and retrieve the data from those tables. There are three ways to combine data from multiple tables: Unions: Combine rows from multiple data tables. Subqueries: Subquery is encapsulation of one query inside another query Joins: Joins combine columns from multiple data tables. a Unions: The Union operator combines the result of two or more Select statements into a single result set. Each select statement must have the same structure, compatible column type and same number of columns. Column name can be different in each select statement.

Syntax: Select statement Union [All] Select statement If you include the All clause, all rows are included in the resultset and duplicates are not removed. Example: Select name1, age from sam2 Union Select name, age from sam1 Using Sub Query: You can use one Select statement to return records that will be used by another Select statement. The encapsulating query is called Parent Query and the inner query is called subquery. In other words, in a subquery one Select statement is nested inside another Select Statement. Example: select username from login where username in (select prod_name from product)

With Where Condition select username from login where username in (select prod_name from product where prod_name='kaleem') Using Exits and Not Exits Keyword When a subquery has a word Exists, it functions as an existence test. The keyword Exists is used to check the existence of rows returned by the subquery. The subquery does not actually return any data. It returns a value of True or False. Syntax: Where [Not] Exists [Subquery] Example:(Exists) select username from login where exists (select prod_name from product) select username from login where exists (select prod_name from product where prod_name='kaleem') Result will be same, it means in subquery where is not going use. Example:(Not Exists)

select username from login where not exists (select prod_name from product) Nested SubQueries: It is possible to extend the subquery technique learnt earlier, and have a subquery that calls another subquery. When this is accomplished, it is called Nested SubQueries. Example: select order_id, prod_id, amount from Order1 where prod_id in (select prod_id from product where sup_id in (select sup_id from supplier where sup_id='S001')) or select order_id, prod_id, amount from Order1 where prod_id in (select prod_id from product where sup_id in (select sup_id from supplier)) Using Aggregate functions in Queries: Aggregate function generate summary values. They can be applied to the rows in a table, or to the rows specified by a Where clause. Aggregate functions generate a single value from each set of rows.

Aggregate functions such as SUM, AVG, COUNT, MAX, MIN generates summary value in a query result set. SUM: Sum returns the sum of the values in an expression. Sum can be used only for numeric columns. Syntax: Sum(Expression) Example: select sum (price) as Total from product or select prod_id, prod_name, sum(price) as Total from product group by prod_id, prod_name COUNT: Count returns the number of non-null values in the expression provided. Count supports the use of both numeric and character columns. Primary Key and Foreign Key column can be safely used with the Count option, because these columns do not have Null values. Syntax: Count (Expressions)

Example: select count(price) as Total from product Syntax: Count(*) Example: select count(*) as Total from product AVG: Average function returns the average of all the values in an expression. Avg function can be used with numeric columns only and it automatically ignores null values. Syntax: Avg ([All|Distinct] Expression) select avg (price) as Total from product MAX: Max returns the maximum value in an expression. Max can be used with Numeric, Character and Date/Time data types. Max returns the highest value in collated order. Max ignores the Null value. Syntax: Max(Expression) Example:

select max (price) from product MIN: Min returns the minimum value in an expression. Min can be used with Numeric, Character and Date/Time data types. Min returns the minimum value in collated order. Min function is also ignores the Null value. Syntax: Min(Expression) Example Select min(price) from product Group by Clause: The Group by clause partitions the table into one or more subsets where each subset has values and expressions in common. If an aggregate function is used in a select statement, Group by clause produces a single value per aggregate. Syntax: Group by <Column Name> Example:

select prod_name, sum(price) as Total from product group by prod_name The Group by Keyword followed by a list of columns, known as grouping columns. select prod_name,sum(price) as Total from product group by prod_name Group by and where Clause: Where Clause can be used with Group by clause to restrict the rows for grouping. The rows that satisfy the search condition are considered for grouping. The rows that do not meet the conditions in the where clause, are eliminated before any grouping is done. Example: select prod_name,sum(price) as Total from product where prod_name='kaleem' group by prod_name Group by and Null values: If the grouping column contains a null value, that row becomes a separate group in the result set. If the grouping column contains more than one null value, the null values are put into single group. Selecting Row using Having Clause:

The Having clause is used to filter rows after grouping them or for restricting rows by applying aggregate functions in the Select Statement. Example: select salary from employee group by salary having sum(salary) > 3000 select coll from qwas group by coll having count(*) >1 select * from qwas group by coll,rank,year,location,distance,salary having coll like 'l %'

5) Joins Joins are used to retrieve data from two or more tables based on a logical relationship between tables. Sometimes we have to select data from two or more tables to make our result complete. We have to perform a join. Tables in a database can be related to each other with keys. A primary key is a column with a unique value for each row. Each primary key value must be unique within the table. The purpose is to bind data together,

across tables, without repeating all of the data in every table. Table Alias Name: Select emp_name, emp_desig from employee as e Syntax: Select Employees.Name, Orders.Product From Employees, Orders Where Employees.Employee_ID=Orders.Employee_ID There are Three type of JOINS: Inner Join Outer Join Self Join

Inner Joins: In inner join, records from two tables are combined and added to a queries result only if the rows from both the tables are matched based on a column. Syntax: Select <Shortname.ColumnNameList of Columns> From Table_A as Table_Alias A Inner join

Table_B as Table_Alias_B On Table_Alias A.Column_Field = Table_Alias_B.Column_Field> Example: select a.emp_id, a.emp_name, b.prod_name, b.price from employee a inner join product b on a.emp_id=b.prod_id Outer Joins: Inner join returns rows only when there is at least one row from both tables that matches the join condition. Inner join eliminate the rows that do not match with a row from the other table. Outer joins, however, return all rows from atleast one of the tables mentioned in the from clause, as long as those rows meat any where or having search conditions of the select statement. There are three types of outer joins: Left Outer Join Right Outer Join Full Join

Left Outer Join

Left Outer join returns all the records from the left table and only matching records from the right table. Example: select * from employee a left outer join product b on a.emp_id=b.prod_id Right Outer Join In the right outer join pulls all the records from the second table in the join regard less of whether there is matching data in the first table. Example: select * from employee a right outer join product b on a.emp_id=b.prod_id where a.salary>40000 Full Outer Join Besides these two outer join, Sql server has yet another kind of join called Full join or Full Outer Join. A full join lists all the record from both the tables, regardless of whether there are matching records in the tables or not. Example: select * from employee a full outer join product b on a.emp_id=b.prod_id

Self Join: Self join is a type of inner join. This is used to find records in a table that are related to other records in the same table. A table is joined itself in a self join. Example: select a.emp_id as 'Employee 1', a.emp_name, b.emp_id as 'Employee 2' from employee a join employee b on a.emp_name=b.emp_name and a.emp_name='kaleem' Indexes: An index in a database is similar to the index in a book. When you want to gather information on a given topic in a book, you do not search from the first page to the last page. In a book, an index allow you to find information quickly without reading the entire book. In a database, an index allow program to find data in a table without scanning the entire table. A index can be created for a single field or a combination of fields. Primary key constraint creates clustered indexes automatically. Guidelines for creating indexes:

In general, columns for indexing should be selected carefully, A column can be selected for indexing based on the following criteria: The column is used for search very frequently. The column is used for sorting the data. Do not index the columns in the following cases: The column contains only a few unique values. Indexing small tables may not be optimal because it can take Sql server longer to traverse the index searching for data than to perform a row-by-row search.

Types of Indexes: After you have determined that creation of an index is justified for a column, you can select the type of index that best fits your situation. Clustered Index Non Clustered Index Unique Index Composite Index

Clustered Index: A clustered index determines the storage order of data in a table. It is similar to a telephone directory, which arranges the data by last name. A table can have only one Clustered

index, because clustered index dictates the physical storage order of the data. Syntax: Create clustered index index_name on table_name (Column_name) Example: Create clustered index empClusIndex on emp(empno) Drop Index: drop index emp.empClusIndex

Non Clustered Index: A non-clustered index specifies a logical ordering only. The items in the index are stored in the order of the index key values, but the information in the table remains unchanged. Syntax: Create nonclustered index index_name on table_name (Column_name) Example:

Create nonclustered index nonclus on emp(emp no) If you create an index and do not specify whether it is clustered index or non-clustered index, it will be by default a non-clustered index. Composite Index: A composite index consists of two or more columns indexed together. The maximum number of columns that can be combined is 16. You may also create a Clustered composite index or a non-clustered composite index. Example: Create Clustered index test on testing (idd, name) Unique Index: A unique index ensures that the indexed column contains no duplicate values. In the case of multi-column unique indexes, the index ensures that each combination of values in the indexed column is unique. Create unique clustered index tt on testing (idd) To view the indexes on a table: sp_helpindex testing

6) Implementing Views Definition for View Queries are used to retrieve data from the table. Queries operate on the actual data stored in the table directly. Instead of querying and directly manipulating the data in the tables. Sql supports the simulated tables that present the existing data in a new way. The simulated table supports the same functionality as physical tables. The data can be read, added and updated in the simulated tables. These simulated tables are called Views. A view acts as a filter on the table addressed in the query. The query that defines the view can be based on one or more tables or from other views, from the current database or other database. Syntax: Create view <view_name> as <select_statement> Examples: View1: create view view1 as select * from employee

To execute your view through View select * from view1 View2: create view view2 as select * from product View3:(Join view) create view view3 as select a.emp_id,a.emp_name,a.emp_desig,a.salary,b.prod_nam e,b.price from view1 a inner join view2 b on a.emp_id=b.prod_id Advantages of View: The use of views offers numerous potential advantages for users and developers. They are Advantages of views for the End User: Easier to understand results While creating the views, the column name can be changed meaningfully so that it is easier for the user to understand what the column represents.

Changing the column name in the view does not affect the underlying table column name. Easier to obtain data

As lot of people know very little of Sql, it becomes difficult for them to create complex queries from multiple tables. Therefore, you can create a view accessing data from multiple tables for the ease of user. Advantages of views for the developer Easier to restrict data retrieval

As a developer you may want to conceal information in certain columns or rows. By using views the user can be given flexible access to the data they need, while maintaining the security for other data in the same table or different tables. To do this, view can be set up to exclude the columns that you do not want to show the user. Application are easier to maintain

It is easier to debug the view rather than debug the queries. Tracking mistakes in each step of a process in a view is easier since all the steps are a part of the view. Guidelines for creating views:

Views can be created only in the current database. A view name should be similar to the table name because it is easy to remember and associate. It should follow the naming conventions for identifiers. A view can be built on other views. Sql server allows views to be nested upto 32 levels. It can contain upto 1024 columns from one or more tables or views. Defaults, Triggers cannot be associated with views. Views cannot be indexed. View definition holds good even if the tables are dropped. The query defining the view cannot include Order by, Compute or Compute by Clause or the into keyword.

Modifying data through views A view can be used to modify the data in the table provided: The view contains at least one table in the From Clause of the view definition, that means the view cannot be based on an expression. No aggregate function (Avg, Sum, Count, Max, Min, Grouping) or Group by, Union, Distinct, or Top clauses are used in the select list. However, aggregate functions can be used within a subquery

that is defined in the Form Clause provided that the derived values generated by the aggregate functions are not modified. The view has no derived columns in the select list. Derived columns are result set columns formed by anything other than a simple column expression, such as using functions or addition or subtraction operators.

Dropping view: drop view view1 Index in View: If you want to use index for a view, for that you have to create a view like this create view view2 with schemabinding as select id,name from dbo.empl View cant create Clustered index. To Create Non clustered index also, we have to create unique clustered index then only we can create Non Clustered index. create unique clustered index clviewUnq on view2(id) --Before creating nonclustered index we have to create unique clustered index

create nonclustered index clview3 on view2(name) drop index view2.clviewunq

7) Temporary Tables Permanent Temporary Table Temporary table is only to view the table in the particular time only. After closing the table the 8) Implementing Stored Procedure Introduction to Variables: Variables are defined memory locations, which are given a name and which contain some value. Since variables are created in memory, whatever they contain is not permanent. Variables are mainly used for calculations or to store some value for Store Procedures. These are two types of Variables in Sql Server: Local Variables System Global Variables

A variable is an object that can hold a data value. You can pass data to Sql statement using local variables. The name of the local variable must be prefixed with @ sign.

Syntax: Declare { @local_variable name data type } For example, let us declare a variable to hold upto 4 characters Declare @Flight char(4) The Set Statement or the Select Statement is used to assign some value to the local variable. Syntax: Set @local_variable name = value Or Select @local_variable name = value For example, let us assign a value to the variable declared earlier.

Set @Flight = IC01 Select * from flight_details Where aircraft_code = @Flight Sql server maintains several system global variables that hold information useful to the database user. These variables are prefixed with @@ sign. You can retrieve the value of these variables by calling them in the Select statement. Syntax: Select <Variable Name> Example: Select @@version The Version variable returns the version of Sql server. Some System variables are listed below: System Global Variable @@Trancount @@Servername @@Rowcount @@Nestlevel This Variable returns Transactions currently open on the connection Local Server name Number of rows affected by the latest Sql Statement Nesting level of the current stored

@@Language @@Servicename @@Procid @@Connections @@Fetch_Status

procedure Language name Sql Server service name on the current computer ID of the current Store Procedure Number of connections established with the server since it is started Status of the Fetch operation. Returns 0 if it is successful, -1/-2 if it is unsuccessful.

The following table summarizes the various control-offlow statements available in Sql Statement. Begin <sql statement> End Return GOTO <label> <label>: If <Condition> <sql statements> Else <Sql statements> While <condition> Begin <Sql Statements>

<on Some Condition> Break <on Some Condition> Continue End Case <expression> When <expression1> Then <expression1> [When <expression2> Then <expression2>] Else <Expression> End

Store Procedures: Store Procedures are a vital tool for any database system. Store Procedures are written by database developer or database administrators to run commonly performed administrative tasks or to apply complex business rules. The stored procedure contains data manipulation or data retrieval statements. System Stored Procedures A Store Procedure is a precompiled collection of Sql statement stored with a name and processed as a unit.

Sql server provides some precompiled stored procedures for managing Sql server and displaying information about the databases and users. These Stored Procedures are called as System Stored Procedures. Stored procedures in Sql server are similar to procedures in other languages as they can: Accept input parameters and return values to the calling procedure or statement. Contain programming statements that perform operations in the database of call another Stored Procedure. Return a status value to a calling procedure to indicate the success or failure (and also reason for failure).

Benefits of Stored Procedures: Speed One of the greatest advantages using the Store Procedure is the Speed. Stored Procedures are optimized the first time they are compiled, this allow them to run with much less overhead than a normal Sql Statement. Faster Access to data Stored Procedures are optimized for the best execution path to the required data. They enhance the performance greatly because Sql

server does not have to select the best route to execute Sql statements and access the data once they are complied. Less compilation time When the stored procedures are executed, the query plan is read into the procedure plan and run. In case of normal Sql statement, Sql server first checks for Syntax, resolves and compiles a query every time it is executed. Modular Programming Another benefit associated with Stored Procedure is being able to share application logic. A large Stored Procedure can be broken down into many smaller Stored Procedures. These smaller stored procedures can be shared between many large stored procedures. This greatly decreases the time in designing and implementing the stored procedures. These individual parts can be easily managed and debugged. Consistency Utilizing Store Procedures enforces consistency because the user do not have to use their own Sql Statement. Enhance security mechanism One of the major benefits of using Stored Procedures is to enforce the security. If the user is not supposed to access the data directly, complete access the data directly, complete access to the table can be revoked and you can

create your own stored procedure. You can give Execute rights to this stored procedure and it will perform the right task for the user. This creates a more secure environment because fewer people will have direct access to the underlying data. Types of Stored Procedures: System stored procedures (Can be executed only) Extended stored procedures (Can be created and executed) User-defined stored procedures (Can be created and executed)

System Stored Procedures: System Stored Procedures are supplied by Sql server, they are precompiled collection of Sql statements. Sql server provides system stored procedures to report and manage the information in system tables. Users should use these system procedures instead of accessing the system tables directly. The users should not update any of the system tables directly. The name of all system stored procedures begins with sp_. Extended Stored Procedures: Similar to user-defined and system stored procedures except that they are not residents of Sql server. They

work outside Sql Server and are stored as DLLs (Dynamic Link Library). Sql server dynamically locates them and executes them. Extended stored procedures are usually denoted by the xp_ prefix. Dynamic Link Library is an executable routine containing a specific set of functions stored in .dll file and loaded on demand when needed by the program. User defined Stored Procedures: Apart from using the built-in stored procedures. (System and extended) you can create your own stored procedures. To create stored procedure, Create procedure or create proc statement are used. All stored procedures are created in the current database. In order to create procedure you must the permission to execute the create procedure statement. A stored procedure can have upto 1024 parameters. Procedures can be nested upto 32 levels.

The syntax: Create Proc[edure] procedure_name Example:

Create proc proc1 As Select * from login go Executing Store Procedures Stored procedures can be executed using Sql statement Exec or Execute. Syntax: Execute procedure_name For example to execute the stored procedure, Execute proc1 Using Parameters in Stored Procedures A stored procedure communicates with the calling program through its parameters. When a statement executes a store procedure, it can pass values to the stored procedure. Parameters are used to exchange data between stored procedures and the routine that called the stored procedure. The syntax for the parameter portion of create procedure statement is: Create procedure procedure_name @parameter_name data type

Example: Create proc proc2 @uname varchar(20), @pas varchar(20), @add varchar(50), @phone int, @eid varchar(20) as insert into ragu values(@uname, @pas, @add, @phone, @eid) GO Executing store procedure with parameter Execute proc2 kaleem,test,aynavaram,25897898 ,E1424878 Or If your giving null value you can give like this Execute proc2 kaleem,test,aynavaram,null ,null Example: Create procedure NewSum @num1 int, @num2 int As Declare @mysum int

Select 'Number are:', @num1, @num2 Set @mysum = @num1 + @num2 Select 'Sum is:', @mysum

Example: ALTER procedure sent @empid int as declare @but VARCHAR(20) set @but = (select EMPID from emp where empid =@empid) if @but = @EMPID begin select * from emp where empid =@empid end Example: create procedure search @name varchar(20), @group varchar(20), @song varchar(20) as begin if @name is not null begin

select * from details where name=@name end else if @group is not null begin select *from details where r_group=@group end else if @song is not null begin select *from details where songname=@song end else select * from details end Exec search 'hariharan',null,null Exec search null, sony bmg,null Exec search null,null,'thaniyae' Example: create procedure search2 @name varchar(20), @group varchar(20), @song varchar(20) as begin if @name is not null and @group is not null and @song is not null begin

select * from details where name=@name or r_group=@group or songname=@song end else select * from details end exec search2 'hariharan','sony bmg','thaniyae' Modifying Stored Procedure alter procedure NewSum @num1 int, @num2 int As Declare @mysum int Set @mysum = @num1 + @num2 Select 'Sum is:', @mysum Dropping Stored Procedure drop proc newsum To view Stored Procedure details: To view the details of Stored Procedure: sp_helptext sp_test

Stored Procedure using case: create procedure sp_case @a int as begin select case @a when 1 then 'i m in 1' when 2 then 'i m in 2' else 'llll' end end Stored procedure using while: create procedure sp_sam1 @a int as declare @b int begin set @b=1 while @a<10 begin print 'hai' print @b if (@a=5) break set @a = @a+1

set @b= @b+1 end end

CONSTRAINTS: Setting Foreign Key: -------------------------CREATE TABLE ORDERS (Order_ID integer primary key, Order_Date datetime, Customer_SID integer references CUSTOMER(SID), Amount double); Check Constraint: ----------------------CREATE TABLE Customer (SID integer CHECK (SID > 0), Last_Name varchar (30), First_Name varchar(30)) Unique Constraint: -----------------------CREATE TABLE Customer (SID integer Unique, Last_Name varchar (30), First_Name varchar(30))

Not Null Constraint: -------------------------CREATE TABLE Customer (SID integer NOT NULL, Last_Name varchar (30) NOT NULL, First_Name varchar(30)) Primary Key Constraint: -------------------------------CREATE TABLE Customer (SID integer PRIMARY KEY, Last_Name varchar(30), First_Name varchar(30)) Alter and Adding Primary Key --------------------------------------ALTER TABLE Customer ADD PRIMARY KEY (SID);

Triggers: Triggers are special stored procedures created by the user and provoked any database (Sql, Oracle, Pl/Sql) when data modification statements are issued. Triggers are special object created on the table and are part of the database. A trigger is invoked automatically whenever the data in the table is modified. They are invoked in response to Insert, Update or Delete Statements. A Trigger may query other tables and can include complex statements. You can create a separate trigger on a table for insert update and delete operations. You may have one trigger performing any two operations, or all three operations. You can have multiple triggers for each table. Some of the common uses of triggers are: Triggers can cascade(primary-foreign) changes through related tables in a database. This means if a row is deleted in a table, the related row in other tables will also be deleted. Triggers can disallow or reject changes that violate referential integrity, thereby cancelling the attempted data modification. Such a trigger will be affected when the foreign key of one table, is given a value which does not match, with the Primary key of another table. Triggers are used to apply validation rules that are complex and cannot be implemented using

constraints like foreign keys, defaults and check constraints. Triggers can enforce complex restrictions than those defined with check constraints. Unlike Check constraints, triggers can refer a column in another table. Triggers can find the difference between the state of a table before and after data modification. Multiple triggers of the same type (Insert, Update or Delete) on a table allow multiple different actions to take place in response to the same modification statement. Triggers can be used to implement error handling in transactions. Triggers can be used to call an alert when an error occurs. Stored Procedures like sp_OAGetErrorInfo can be called in a trigger to check what caused the problem. In case of multiple triggers, it is essential to identify the order in which they are executed. A new stored procedure, sp_settriggerorder permits you to set the order of the triggers.

Creating Triggers: The code contained in the trigger has access to two virtual tables, which are local to the trigger and are referred as Inserted and Deleted. Deleted and Inserted tables contain images of data prior to and after the updation. Since the inserted and deleted tables are created dynamically in RAM

and do no use any permanent storage, these tables are called as logical tables. Below given table shows the role played by the inserted and deleted tables while executing Insert, Delete and Update Triggers. TRIGGER Update INSERTED TABLE Copy of records after the command is completed Not Used Contains the data to be added DELETED TABLE Copy of records before the command is completed Contains the data to be removed Not used

Delete Insert

There are three type of Triggers: Insert Trigger, Delete Trigger and Update trigger. Any type of trigger can be created using Create Trigger Statement. Syntax: Create Trigger Trigger_Name On Table For ([Delete] [,] [Insert] [,] [Update] ) [With Encryption] As Sql_Statement

Arguments Trigger_name Table With Encryption

For [Delete] [,] [Insert] [,] [Update] AS Sql_Statement

Description Name of the Trigger Name of the Table on which the trigger has to be executed This option is used to prevent other user from viewing the text after it is loaded into Sql server. Specifies the DML Command that is going to be included in the trigger body Keywords that specify which statement will invoke the trigger Action of trigger The Transact Sql Statement to be executed when the trigger is invoked.

Update Triggers: When an update trigger is executed, the original data is moved to the logical Deleted table. The new rows are then

moved to the Inserted table. Once the data has been successfully moved, the trigger will check to see if the data can be verified. Update trigger can be classified into two types: * Update Table level Trigger * Update Column level Trigger Table Level The update table level trigger is fired when any field in the row is updated. The following is an example of the update trigger occurring at the table level. Create trigger trg on mark1 for update as if(select m1 from inserted) > 100 begin print 'Marks should not be greater than 100' select * from inserted select * from deleted select * from mark1 rollback transaction select * from mark1 end Column Level The update column level trigger occurs when data in a particular column is updated, it uses if update

(Column_name) clause. The following is an example of update trigger occurring at column level. create trigger trg1 on mark1 for update as if update(ssum) begin print 'Sum Field should not be Update' select * from inserted select * from deleted rollback transaction end To Modify trigger we can use alter keyword Delete Triggers: Delete trigger are executed when the delete statement is issued against rows in a table. When rows from a table are deleted, the delete rows are moved from the base table to the logical Deleted table. Example: create trigger trg3 on ttt for delete as if (select count(*) from deleted) >5 begin Print 'You should not delete more than 5 records'

rollback transaction end delete from ttt

Limitations for Triggers: * Triggers can only be created on the tables. Although a trigger can refer to temporary tables, triggers cannot be created on views or temporary tables. * Triggers cannot contain objects creation statements such as: Create Database, Create Table, Create Index, Create Procedure, Create Default, Create Rule, Create Trigger and Create View. * Triggers cant contain any drop statements such as drop database. * Triggers cant use database object modification statement such as Alter table, Alter Database. Cascading Triggers: Cascading updates can automatically update data in a reference table that is logically related to the base table on which an update is being carried out. You can even update related data in the same table. Create trigger trg on stores for delete as

Begin Delete sales From deleted inner join sales On sales.stor_id=deleted.stor_id End Run: delete from stores where stor_id=7066

Instead of Triggers: In case of Instead of Triggers, the code contained inside them is executed in place of the original data manipulation statement. There are three type of instead of triggers they are * * * Instead of insert Instead of delete Instead of update

For example, let us create a sample table and a instead of trigger on it. Create table sample (sometext varchar(20))

Now, let us insert records in the sample table. Insert into sample values(You cannot) Insert into sample values(delete records) Let us create instead of triggers: Create trigger sample_trg on sample instead of delete As Begin Select sometext as Inserted Columns from inserted Select sometext as Deleted Columns from deleted Select sometext as Table sample from sample End Now delete Delete sample

Output: Inserted Columns empty Deleted columns-> deleted values Table sample-> orginal values The ouput shows that the data in the sample table is intact even after the delete operation. This is because the instead of trigger on the sample table with respect to the delete

operation prevents the operation. Hence, here the data is not deleted. In output, the original table values will not be deleted. If we use without using the instead of delete, Orginal row will be affect. The prime advantage of instead of trigger is that, by using them you can update views that would not be possible otherwise. For a view containing multiple base tables in it definition, you must use an instead of trigger in order to carry out insert, update and delete operations that reference data in the tables. Another advantage of instead of triggers is that it permits you to code the logic that can reject parts of a batch while permitting other parts of a batch to succeed. Note: You cannot define Instead of delete and instead of update triggers on a table that has a foreign key defined with a delete or update action. Now let us consider another example. In this example, we will use a instead of trigger to update two base tables from a view. Now we are going to use the Instead of trigger to insert records into multiple tables via a single view. When a user tries to insert records with duplicate social_sn, they are documented in the Duplicate table. Duplicate rows in Emp table are changed to update statements.

First Table: Person create table person (social_sn char(5) primary key, name varchar(50), address varchar(50)) Second Table: Emp create table emp (emp_id int primary key, social_sn char(5) unique, dept varchar(10), salary money, constraint fk_emp_person foreign key (social_sn) references person (social_sn) ) Create view: Person_emp create view person_emp as select b.social_sn, name, address, emp_id, dept, salary from person a, emp b where a.social_sn = b.social_sn Create Table: Duplicate create table duplicates (social_sn char(5), name varchar(50), address varchar(50), insertsname varchar(50), insertedtime datetime) Create Trigger create trigger trg1 on person_emp instead of insert as

begin if(not exists(select p.social_sn from person p, inserted i where p.social_sn=i.social_sn)) insert into person select social_sn, name, address from inserted else insert into duplicates select social_sn, name, address, suser_sname(), getdate() from inserted if (not exists(select e.social_sn from emp e, inserted i where e.social_sn=i.social_sn)) insert into emp select emp_id, social_sn, dept, salary from inserted else update emp set emp_id=i.emp_id, dept=i.dept, salary=i.salary from emp e, inserted i where e.social_sn = i.social_sn select * from inserted select * from person_emp select * from person select * from emp select * from duplicates end Now run insert into person_emp values('AB01', 'Pearl', '12, Avenue Rd, New York', 101, 'sales', 12000) Output:

Inserted (All values will be inserted) Person_emp(All values will be display) Person (It will also insert) Emp (It will also insert) Duplicates(Empty) Again your are going insert the same social_sn with little different values insert into person_emp values('AB01', 'Sam', '12, Avenue Rd, New York', 101, 'HRD', 12000) Output: Inserted (All values will be inserted) Person_emp(Only HRD will be update) Person (No changes old value only display) Emp (It will update HRD) Duplicates(New value will be inserted) Cursors Cursors are database objects used to manipulate data in a set on a row-by-row basis. You can fetch cursor rows and perform operations on them in a loop just like using any looping mechanism found in any other programming language. Cursor declaration

DECLARE cursor_name CURSOR [ LOCAL | GLOBAL ] [ FORWARD_ONLY | SCROLL ] [ STATIC | KEYSET | DYNAMIC | FAST_FORWARD ] [ READ_ONLY ] FOR select_statement [ FOR UPDATE [ OF column_name [ ,...n ] ] ] Local Scope of the cursor is local to that batch or stored procedure Global Scope of the cursor is global to the connection FORWARD_ONLY Specifies that FETCH NEXT only can be specified STATIC Cursor makes a temporary copy of the database data in temporary tables in tempdb KEYSET Changes made by the other users are not visible DYNAMIC

Changes are visible as the user scrolls through the cursor. Absolute will not work in this cursor. FAST_FORWARD Declares a FORWARD_ONLY and READ_ONLY cursor READ_ONLY Creates a read only cursor Steps to be followed: * Declare cursor * After a cursor is created you need to open the cursor before you fetch the records from it. Open <cursor_name> * Once cursor is opened, records are fetched from the cursor to display them on the screen. Fetch <cursor_name> * A cursor should be closed, once the cursor is closed, the rows can be fetched only after it is reopened. Close <cursor_name> * When the cursor is not required any more, its reference is removed. The Deallocate statement is used to remove the reference of a cursor. Deallocate <cursor_name> Types of Fetching in cursor:

When a cursor is opened, the current row position in the cursor is logically before the first row. Cursor can fetch one row at a time. The operation of retrieving the rows from the cursor is called Fetching. These are the various fetch operations.

* * * * * *

Fetch First Fetch Next Fetch Prior Fetch Last Fetch Absolute n Fetch Relative n

Example: ----------Declare cursorname cursor scroll For Select * from testing order by name Open cursorname Fetch First from cursorname While @@fetch_status =0 Begin Fetch Next from cursorname end Example:

-------------Declare cursorname cursor scroll For Select pnr_no, ticket_no, name from passenger where pnr_no=1 Open Cursornamecommand successfully message will come Fetch cursorname---First row will display Fetch First cursornameFirst row will display Fetch Next cursorname Fetch Last cursorname Fetch Absolute 2 from cursorname Fetch Relative 1 from cursorname Fetch prior cursorname

Creating Forward Only Cursor: Declare cur1 cursor Forward_only For Select * from testing where desg='ts'

For update Open cursorname Fetch cursorname Update testing set name ='Hari1' where Current of cursorname Select * from testing where desg='ts' Creating Keyset cursor: declare key1 cursor keyset for select * from marks where class='msc' or class='mca' open key1 fetch first from key1 while @@fetch_status=0 begin fetch next from key1 end Note: In a keyset cursor the order of rows is fixed when the cursor is opened. Creating Static cursor: declare key1 cursor static for select * from empl where name='aaa' or name='test'

open key1 fetch first from key1 fetch next from key1 fetch last from key1 After open cursor, if we insert value into the table that will not affect in the cursor. Again if we close cursor and reopen cursor the last inserted value will be included. Try using insert command. For (static and keyset) insert into empl values('test') Creating dynamic cursor: declare key1 cursor scroll dynamic for select * from empl where name='aaa' or name='test' open key1 fetch first from key1 fetch next from key1 fetch last from key1 Creating Local cursor: declare key1 cursor local

scroll dynamic for select * from empl where name='aaa' or name='test' open key1 fetch first from key1 fetch next from key1 fetch last from key1 Note: Local cursor will run at that time only, you cant open cursor with that name, you will get error message like this A cursor name with the name key1 does not exist. Creating Global cursor: declare key1 cursor Global scroll dynamic for select * from empl where name='aaa' or name='test' open key1 fetch first from key1 fetch next from key1 fetch last from key1

Creating Readonly cursor:

deallocate key1 declare key1 cursor read_only for select * from empl where id=26 and name='test' open key1 fetch key1 fetch first from key1 fetch next from key1 fetch last from key1 delete from empl where current of key1 close key1 Note: The cursor is readonly, deletion/update cant be done. Only we can view the next record it is like forward only.

Function: -----------Creating Function: create function GetSal11() returns int begin return (Select salary from employee where emp_id=3) end

To view the result: select dbo.getsal11() or select kaleem.dbo.GetSal() Now we are calling in the Sql Query Statement: select * from employee where salary > dbo.GetSal11() or select * from employee where salary> kaleem.dbo.GetSal11() Altering Function: -----------------alter function GetSal11() returns int begin return (Select emp_id from employee where emp_id=3) end Droping Function: ----------------drop function getsal11

Index: -----Clustered Index: ---------------Clustered Index will physicaly short, only one clustered index should be in one table. If you set primary key for a any columun, clustered index will automatically created.

Primary Key Constraint: ----------------------Creating : create table testinggg (dd int constraint test1245 primary key ) Deleting Primary Key Constraint: ALTER TABLE testinggg drop CONSTRAINT test1245 After creating table Giving Primary Key: ---------------------------------------alter table testinggg

add constraint conname3 PRIMARY KEY (id) View With Join: --------------Create view viewjoin as select,, b.username, b.salary from empl a, employee b where insert into viewjoin values(20,'test12','test12',4) JOin view can't UPdate or delete, only insert can be done