SQL basics INDEX S.No Topics Page number 1 Creating and altering table records(DDL and DML) 2 2 Constraints 7 3 Joins 13 4 Views 16 5 Control flow constructs in SQL 18 6 Using Local Variables 20 7 Cursors 21 8 Creating User Defined Data types 28 9 Stored Procedures 28 10 Functions 33 11 Exception Handling in Procedures 40 12 Triggers 44 13 Indexing in SQL 52 14 Transaction and Locking 55 15 XML support in SQL Server 60 Trainer: Mr. C.Santhosh Kumar, 329649.
68
Embed
SQL basics - microsofttechy.weebly.commicrosofttechy.weebly.com/uploads/2/6/7/1/2671903/sql_santhosh.pdf · 5 Control flow constructs in SQL 18 6 Using Local Variables 20 7 Cursors
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
SQL basics INDEX
S.No Topics Page number
1 Creating and altering table records(DDL and DML) 2
2 Constraints 7 3 Joins 13 4 Views 16
5 Control flow constructs in SQL 18 6 Using Local Variables 20 7 Cursors 21 8 Creating User Defined Data types 28
--displaying selected entries based on the conditions given
select * from cts.employee where name='lakshman' and address='salem'
--creating another table
create table cts.employees
(
empid varchar(10) primary key,
empname varchar(200),
deptid varchar(10),
joining_date date,
dob date,
yrs_of_expr int,
employee_category varchar(10)
)
--displaying all the entries in the table
select * from cts.employees
--inserting values to table
insert into cts.employees values(346238,'lena','dn','2012-08-28','1990-05-09',0,'programmer analyst
trainee')
insert into cts.employees values(346200,'kishore','dn','2012-08-28','1990-12-08',0,'programmer analyst
trainee')
insert into cts.employees values(346201,'prasanna','dn','2012-08-28','1990-07-10',0,'programmer
analyst trainee')
insert into cts.employees values(346197,'lakshman','dn','2012-08-28','1990-08-16',0,'programmer
analyst trainee')
--adding new column to the table (Altering the table data structure)
alter table cts.employees alter column employee_category varchar(50)
--displaying details based upon a condition
select empid,dob,joining_date from cts.employees where (year(joining_date))>2010 and
(month(dob))>5
4 | P a g e
:
--counting no. of records in the employee table based upon a specified condition
select COUNT(*) "no,ofemployees" from cts.employees where (year(joining_date))>2010 and
(datename(mm,dob))='december'
--Displaying all entries with the difference between 2 dates is greater than 21
select empid,dob,joining_date from cts.employees where DATEDIFF(yy,dob,joining_date) >21
--Deleting a specific entry from table
DELETE FROM cts.Employees where dob='1990-07-10'
--T- SQL Operations
Select , Order by, from, where clauses:
o SELECT keyword is used to display all the entries specified next to it.
o ORDER BY clause allows us to sort the records in your result set. The ORDER BY clause can
only be used in SELECT statements
o FROM clause produces the tabular structure, the starting set of data on which all other
operations in a SELECT statement are performed. Note that, FROM clause is the first clause
that will be looked by the database system while parsing the SQL statement. o WHERE clause is always followed by the condition. It is used to filter the data set.
o Syntax :
SELECT columns
FROM tables
WHERE predicates
ORDER BY column ASC/DESC;
Top clause:
o TOP clause is used to specify the number of records to return.
o Syntax:
SELECT TOP number|percent column_name(s)
FROM table_name
Patterns and wildcards:
o SQL patterns and wildcards can substitute for one or more characters when searching for
data in a database.
o For example:
o ‘%s’ - displays all the strings that ends with ‘s’
o ‘s%’ – displays all the string that starts with ‘s’
o ‘%san%’ – displays all the strings that has ‘san’ either in the front or at the back
o ‘[san]%’ – displays all the strings that starts with s,a, and n.
o IN CLAUSE in SQL is typically used in a WHERE clause. It is normally used when we want to
create a subset of records from another set.
o BETWEEN clause is used to select a range of values specified between the keyword
‘between’ & ‘and’.
o '_00%' - Finds any values that have 00 in the second and third positions.
5 | P a g e
:
o The below is the table which gives more explanation about the wildcards.
Wild card Description
% A substitute for zero or more characters
_ A substitute for exactly one character
[charlist] Any single character in charlist
[^charlist] (Or) [!charlist]
Any single character in charlist
Note: LIKE clause is used to compare a value to similar values using wildcard operators. There are two wildcards used in conjunction with the LIKE operator:
The percent sign (%) The underscore (_)
String Functions:
There are some inbuilt functions in SQL that will be used to manipulate the strings. They are as
follows:
a) substring(string,startIndex,length) - Returns part of a string. For example, SELECT
SUBSTRING('SQLServer', 4, 3) returns ‘Ser’.
b)len(string) – returns the length of the string. For example SELECT LEN(‘Hello’) returns 5.
c)upper(string) – Converts the given string to uppercase.
d)lower(string) – Converts the given string to lowercase.
e)replace(string1,String2,String3) -Replaces all occurrences of the string2 in the string1 with string3. For
example, SELECT REPLACE('All Function' , 'All', 'SQL') will return ‘SQL Function’
f)ltrim(string) and rtrim(string) – ltrim(String) returns a string after removing leading blanks on Left side.
For example, SELECT LTRIM(' sqlserver') returns 'sqlserver' (Remove left side space or blanks).similarly,
rtrim(String) Returns a string after removing leading blanks on right side. For example,
SELECT RTRIM('sqlserver ') returns 'sqlserver' (Remove right side space or blanks).
g)left(String,Integer) - Returns left part of a string with the specified number of characters. For example,
SELECT LEFT('TravelYourself', 6) gives ‘Travel’
h)right(String,Integer)- Returns right part of a string with the specified number of characters. For
example, SELECT RIGHT('TravelYourself', 6) gives ‘urself’
6 | P a g e
:
Date Functions:
There are several functions that deals with date manipulation.They are:
a)Getdate() and sysdatetime() –returns current date and time from the sql server
b)Dateadd(format,number,date) - adds or subtracts a specified time interval from a date.
c)Datediff(format,date1,date2) - returns the time between two dates.
d)Datepart(format,date) -returns a single part of a date/time, such as year, month, day, hour, minute,
etc.
e)Datename(format,date) - returns the name or value of the specified datepart of the a date.
format – yy/yyyy/mm/dd/d/m/ hh/mi/ss
7 | P a g e
:
2.CONSTRAINTS Points to remember:
Constraints are used to limit the type of data that can go into a table.
Constraints can be specified when a table is created (with the CREATE TABLE statement) or after the table is created (with the ALTER TABLE statement).
There are several constraints available in SQL. They are namely,
a)Primary key d) Default
b)Foreign key e) Unique
f)Not null
Defining Primary key constraint:
o Creating a column as a primary key:
Syntax:
Create table tablename
(
Columnname type primary key,
……
)
Note: If we add primary key constraint as said above, then we will not be
able to drop them individually. Instead, we need to drop the entire table
later if there is a change in the primary key column of the table.
o Creating a primary key constraint at column level:
Syntax:
Create table tablename
(
Columnname type constraint constraint_name primary key,
……
)
Note: If we add primary key constraint as said above, then we can drop the
primary key constraint whenever needed without needed to drop the table.
o Creating a primary key constraint at table level:
insert into cts.orderid values (1000,'E-Learning',1002,3,5000.00) -- it will be inserted.
select * from cts.orderid
13 | P a g e
:
3.JOINS
Concept:
Querying result from multiple tables is the main concept of Joins.
It provides new visualized table records.
There are 3 types of join. Namely:
1.Inner join – default join is Inner join.
2.Outer join
a)Right Outer join or Right join
b)Left Outer join or Left join
c)Full Outer join
3. Cross join
--inner join
select c.c_id,c.c_name,c.language_known,o.orderno,o.product_name from cts.Customer c inner join
cts.orderid o on c.c_id=o.c_id
--left outer join
select c.c_id,c.c_name,c.c_address,o.product_name from cts.Customer c left outer join cts.orderid o on
c.c_id=o.c_id
--inner join using and clause
select c.c_id,c.c_name,o.product_name from cts.Customer c join cts.orderid o on c.c_id=o.c_id and
c.c_address='Andhrapradesh'
--alternate way for inner join using where clause
select c.c_id,c.c_name,o.product_name from cts.Customer c join cts.orderid o on c.c_id=o.c_id where
c.c_address='Andhrapradesh'
--to find who didnt bought product
select o.c_id,o.product_name from cts.Customer c right join cts.orderid o on c.c_id=o.c_id where c.c_id
is null
Aggregate Functions:
Aggregate functions perform a calculation on a set of values and return a single value. Except for COUNT, aggregate functions ignore null values. Aggregate functions are frequently used with the GROUP BY clause of the SELECT statement.
14 | P a g e
:
Some of the Aggregate Functions are:
a)count() b)avg()
c)sum() d)max()
e)min()
Examples:
AVG() - Average value of columns
SELECT AVG(Salary) FROM CUSTOMERS
Value = 4675
COUNT() - number of rows
Select COUNT(*) FROM CUSTOMERS
Value = 4
SELECT COUNT (DISTINCT Salary) FROM CUSTOMERS
Value = 3
MAX() - Maximun or Highest number in a column
SELECT MAX(Salary) FROM CUSTOMERS
Value = 5000
MIN() - Minimum or Lowest number in a column
SELECT MIN(Salary) FROM CUSTOMERS
Value = 4000
SUM() - Total number in a column
SELECT SUM(Salary) FROM CUSTOMERS
Value = 18500
--to find distinct no. of customers
select distinct COUNT(c.c_id) "No. of customers" from cts.Customer c join cts.orderid o on c.c_id=o.c_id
--Alternatively, the above statement can be written as
select distinct COUNT(c_id) "No. of distinct customers" from cts.orderid
-- sum function
select SUM(Order_price) from cts.orderid where Order_Price>76
select c_id,SUM(Order_Price),product_name "total amount" from cts.orderid group by
c_id,product_name
15 | P a g e
:
select c_id,SUM(Order_Price) from cts.orderid group by c_id having c_id > 1002
select c_id,SUM(Order_Price) "Total price" from cts.orderid where c_id > 3 and Order_Price >100 group
by c_id having SUM(Order_Price) > 10
16 | P a g e
:
4.VIEWS
Points to remember:
In SQL, a view is a virtual table based on the result-set of an SQL statement.
A view contains rows and columns, just like a real table. The fields in a view are fields from one
or more real tables in the database.
You can add SQL functions, WHERE, and JOIN statements to a view and present the data as if the
data were coming from one single table.
Creating a view:
Syntax:
CREATE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition
Updating a view:
Syntax:
ALTER VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition
Dropping a view:
Syntax:
DROP VIEW view_name
--Example 1: Create a view that displays all the entries of employee table.Also display the view
create view employee as select * from cts.employee select * from employee
--Example2: create a view employee with attributes id, name where salary=55000 from employee
table. Also display the view.
create view employeeIDandName (id,name)as select id,name from cts.employee where salary=55000;
select * from employeeIDandName
17 | P a g e
:
--Example 3: create a view emp with name and with the condition that all salary reduced by half from
employee table.
create view employeeHalfSalary (name,salary) As select name,salary/2 from cts.employee; select * from employeeHalfSalary;
--Example 4: Create a view that has all the details about the customer whose address is “chennai”
create view Viewcustomers as select * from customers where addres='Chennai' select * from Viewcustomers
--Example 5: Alter the above view and make the salary to be twice the actual salary in employee table.
alter view doubleEmpSalary(name,salary)as(select name,2*salary from cts.employee); select * from doubleEmpSalary;
--Example 6: drop the view created.
drop view employee;
18 | P a g e
:
5.CONTROL FLOW CONSTRUCTS IN SQL
--***** using if statement
if ((select id from cts.employee where name = 'lena prasanna') = 346238)
begin
print 'Andhrapradesh'
end
else
begin
print 'Tamilnadu'
end
--**** using while loop
--Prints 5 tables till 100
declare @count int
declare @num int
--Note: every variables declared, should be initialized to any number
set @num = 0
set @count = 1
while @num < 100
begin
set @num = 5 * @count
print @num
set @count = @count + 1
end
--*****using if exists statement
if exists (select name from cts.employee where name='lena prasanna')
print 'Andhrapradesh'
else
print 'Tamilnadu'
19 | P a g e
:
--*****using switch case
--tax calculation
--NOTE: using syntax 1, we can’t evaluate an expression. Below is the example of using syntax 1.
1.simple case expression function
select name,States=case name
when 'harsha' then 'Andhrapradesh'
when 'sivasaiprasad' then 'Andhrapradesh'
when 'lena prasanna' then 'Andhrapradesh'
when 'kishore' then 'Tamilnadu'
when 'chanakya' then 'Andhrapradesh'
else 'karnataka'
end from cts.employee
--METTL syntax if we use syntax 1
select name,case name
when 'harsha' then 'Andhrapradesh'
when 'sivasaiprasad' then 'Andhrapradesh'
when 'lena prasanna' then 'Andhrapradesh'
when 'kishore' then 'Tamilnadu'
when 'chanakya' then 'Andhrapradesh'
else 'karnataka'
end "States" from cts.employee
--using syntax 2 , we can evaluate expression (search case expression function which evaluate result
based on Boolean expression)
select name, Tax_amount =case
when SALARY >40000 then '20000'
when SALARY <=40000 and SALARY <=30000 then '10000'
else '7500'
end
from cts.employee
--METTL syntax if we use syntax 2
select name, case
when SALARY >40000 then '20000'
when SALARY <=40000 and SALARY <=30000 then '10000'
else '7500'
end
“Tax_amount” from cts.employee
20 | P a g e
:
6.USING LOCAL VARIABLES use dn016_346238
--find odd or even
declare @num int;
set @num=6;
if (@num % 2 = 0)
print 'Number is even';
else
print 'Number is odd';
--calculate tax using basic pay
declare @basicPay money;
declare @tax money;
set @basicPay=600000;
if (@basicPay > 500000)
set @tax= @basicPay * 20 /100;
else if (@basicPay >300000)
set @tax= @basicPay * 10 / 100;
else if (@basicPay >200000)
set @tax = @basicPay * 5/100;
else
set @tax = 0;
print ' The tax amount for the given '+cast(@basicPay as nvarchar(50))+ ' is ' +
convert(nvarchar(50),@tax);
--selecting employee details whose ID is greater than 500 using local variables
use dn016_346238
declare @id int;
set @id=500;
select * from cts.Employee where EmpID > @id;
21 | P a g e
:
7.CURSORS
Note:
attributes with "Identity property" cannot be changed normally. This applies to cursors also.
Syntax for declaring cursors:
declare cursor_name cursor
for
<--TSQL Statements-->
[For update (of column_name)]
note: the contents within [] and () are optional.
Steps involved in cursors:
We need to follow 5 steps on dealing with cursors:
1.Declare Cursor
2.Open Cursor
3.Fetch from cursor
4.Close Cursor
5.Deallocate Cursor
we have 6 priority levels
1.FIRST
2.LAST
3.NEXT
4.PRIOR
5.ABSOLUTE
6.RELATIVE
Declaring cursors as a local variable
DECLARE @varcursor CURSOR
SET @varcursor = CURSOR FOR
select * from cts.employee
OPEN @varcursor
FETCH @varcursor
22 | P a g e
:
WHILE( @@FETCH_STATUS = 0)
BEGIN
FETCH @varcursor
END
CLOSE @varcursor
DEALLOCATE @varcursor
--TYPE 1: FORWARD ONLY CURSOR
--NOTE:Updation made using cursor, affects the cursor as well as in the main table.
-- we cannot use the priority levels like FIRST,LAST,PRIOR,ABSOLUTE,RELATIVE. We can use only NEXT
prioriy level in this type.
--Step 1: Declaring cursor
declare myCursor cursor --myCursor is the cursor name.It is not a variable. By default, any cursor is a
Forward-only cursor
for
select * from cts.employee
--Step 2: Opening cursor
--Cursor will be created only when step 2 is executed
Open myCursor
--Step 3: Fetch records using my cursor
FETCH next FROM myCursor
--NOTE: we can use "NEXT" only. We cannot use other
--Intermediate step: update records
update cts.employee set name= 'Lenaprasanna',address ='Andhrapradesh' where current of myCursor
--Normal update query
update cts.employee set name= 'Sriharsha',address ='Hyderabad' where id=346538
--Step 4: Closing cursor
close myCursor
23 | P a g e
:
--Step 5: Cursor De allocation
deallocate myCursor
Forward Only Scroll :
-- we can use all the keywords like FIRST,LAST,NEXT,PRIOR,ABSOLUTE,RELATIVE.
Declaration of Forward only Scroll:
declare myCursor cursor scroll
for
select * from cts.employee
open myCursor
--NOTE: All the priority levels like FIRST,LAST,NEXT,PRIOR,ABSOLUTE,RELATIVE are available in the
forward only scroll type cursor
FETCH first FROM myCursor --retrieves first record
FETCH last FROM myCursor--retrieves last record
FETCH next FROM myCursor --retrieves next available record
FETCH prior FROM myCursor -- moves one step back
--ABSOLUTE - Moves to absolute position we specify
FETCH absolute -2 FROM myCursor --it moves 2 entries before.
FETCH absolute 3 FROM myCursor --it will move 2 steps ahead.
FETCH relative 3 FROM myCursor --moves to the specified 3rd position from the current position
--Updating records using cursor
update cts.employee set name= 'Sivaprasad',address ='hyderabad' where current of myCursor
--Displaying the updated table
select * from cts.employee
--USING FORWARD ONLY CURSOR: To add a constraint that a particular column alone to be updated,
we can redefine the declaration by including “for update” keyword followed by the column names
which we need to modify.
--Step 1:
declare myCursor cursor
for
select * from cts.employee --IT IS MANDATORY.. Since cursor is like pointer, it should be
allowed to point to a particular table. Here it points to cts.employee table
24 | P a g e
:
for update of name,address --This field is optional. Now,Updating any fields other than name and
address is not valid with this cursor.
--Step 2:
open myCursor
--Step 3:
update cts.employee set name= 'SriHarshaChilla',address ='Andhrapradesh' where current of myCursor
--Step 4 and Step 5:
close myCursor
deallocate myCursor
--TYPE2: DYNAMIC CURSOR
--NOTE:Changes made using dynamic cursor, affects the main table as well as the table created by the
cursor in tempdb.
--Hence, Dynamic cursors are called as "SENSITIVE CURSORS"
--Step1: Cursor Declaration:
declare myCursor cursor dynamic
for
select * from cts.employee
--Step2: Opening cursor
open myCursor
--Step 3: fetching using cursor
--Note:Except ABSOLUTE, the others like NEXT,PRIOR,FIRST,LAST,DYNAMIC can be used
FETCH next from myCursor
FETCH first FROM myCursor
FETCH last FROM myCursor
FETCH next FROM myCursor
FETCH prior FROM myCursor
FETCH relative 3 FROM myCursor
25 | P a g e
:
--updating entries using Dynamic Cursor
update cts.employee set name='Lenaprasanna' where current of myCursor
update cts.employee set id=346200 where name = 'S.Kishore'
--Step 4: Closing and freeing the resource
close myCursor
deallocate myCursor
--TYPE 3: STATIC CURSOR
--NOTE: Changes made in the main table doesnot affect the cursor. Because this cursor retrieves the data
from tempdb which initializes datas from the table when the cursor is created and it never checks the
current updated main table again even if the changes are made. Note that, this cursor is READ ONLY.
--Hence, Static cursors are called as "INSENSITIVE CURSORS AND NOT UPDATABLE".
--FOR UPDATE is not valid for static cursors. SO dont give for update keyword in the cursor declaration.
--All the priority levels can be used.
--Step1: Cursor Declaration
declare myCursor cursor static
for
select * from cts.employee
--Step2: Opening cursor
open myCursor
--Step 3: fetching using cursor
-- All priority levels like ABSOLUTE,NEXT,PRIOR,FIRST,LAST,DYNAMIC can be used.
FETCH next from myCursor
FETCH first FROM myCursor
FETCH last FROM myCursor
FETCH next FROM myCursor
FETCH prior FROM myCursor
FETCH absolute -2 FROM myCursor
FETCH absolute 3 FROM myCursor
FETCH relative 3 FROM myCursor
26 | P a g e
:
--updating entries using static Cursor
update cts.employee set name='Lenaprasanna' where current of myCursor --this statement is INVALID
as the cursor is READONLY. No update can be done with this cursor.
--Step4: Closing and deallocating the cursor
close myCursor
deallocate myCursor
--TYPE4: KEYSET DRIVEN CURSORS
--Note: This cursors are used to update any key columns
--Here, When we update any entry using cursor, unlike Dynamic cursor, this cursor will make the current
pointing entry to be null and make the updated entry in the end of the base table.
--If we update using normal update query, the corresponding values pointed by the cursor becomes null
and no actual entry will be added in the end of the table.
--Step1: Cursor Declaration
declare myCursor cursor keyset
for
select * from cts.employee
--Step2: Opening cursor
open myCursor
--Step 3: fetching using cursor
-- All priority levels like ABSOLUTE,NEXT,PRIOR,FIRST,LAST,DYNAMIC can be used.
FETCH next from myCursor
FETCH first FROM myCursor
FETCH last FROM myCursor
FETCH next FROM myCursor
FETCH prior FROM myCursor
FETCH absolute -2 FROM myCursor
FETCH absolute 3 FROM myCursor
FETCH relative 3 FROM myCursor
27 | P a g e
:
--updating entries using keyset Cursor
update cts.employee set id=346534 where current of myCursor
--Step 4: Closing and freeing the resource
close myCursor
deallocate myCursor
28 | P a g e
:
8.CREATING USER DEFINED DATATYPES
create type udtDescription from nvarchar(max);
create table cts.UserDescription
(
UserName udtDescription,
Passwd nvarchar(50)
);
insert into cts.UserDescription values ('Lenaprasanna','12345678');
insert into cts.UserDescription values ('kishore','32445568');
select * from cts.UserDescription;
9. STORED PROCEDURES Note:
There are three types of stored procedures. Namely,
o System Stored procedures
o User defined Stored procedures
o Extended Stored procedures
System Stored Procedures
Many administrative activities in SQL Server are performed through a special kind of
procedure known as a system stored procedure. For example, sys.sp_changedbowner is
a system stored procedure. System stored procedures are physically stored in the
Resource database and have the sp_ prefix. System stored procedures logically appear in
the sys schema of every system- and user-defined database. In SQL Server 2008, GRANT,
DENY, and REVOKE permissions can be applied to system stored procedures.
Some of the system Stored Procedures are sp_rename, sp_execute, etc.
Example:
o Changing the name of the column in the table using sp_rename stored
procedure:
EXEC sp_rename
‘dbo.Orders.Details’, -- Fully Qualified column name