Sequellll
Sequellll
If any company wants to provide permanent storage and to provide security to the
customer data compulsory they will go for databases
In olden days running the business is important, Now a days running the business
and analyisng the business is also important.
SQL server can be used for day to day transactions and also for analysis...If sql
server is used analysis then hadaoop came into picture??
We will do data operations on the database like create, read, update and
delete...But we cant directly coummnicate with data we use SQL server as an
mediator
Sql server is a software used to manage the database.Sql Server is a back end
tool..
NoSQL
---------
MongoDB
Cassandra
These database softwares will not use SQL..they will use JSON..
These databases are good for storing and processing unstructured data
He will take one system(High configuration) and he will install SQL Server in that
system.
Once you installing Sql server software on that machine it will become server.
In Server DBA will install Sql Server, In Sql Server he will create database of
project like bankdatabase, salesdatabse etc.
Assume there are 3 developers and there are assigned to work with this
bankdatabase.
Every day what this these developers has to do? Everyday they has to connect to the
server & database and work with database
Developers cannot directly work with servers because servers are located some where
For example nee laptop is acting as both server and client. because SSMS and SQL
Server installed on the same laptop.
1)DB
2)INSTANCE
Client
------------
A Client is a system from where users can
1) Connects to server
2) Submit requests to server
3) recevies response from server.
Client Tool---SSMS
SQL SERVER
---------
Sql Server is a RDBMS product from microsoft used to create and to manage
databases.
The main difference between these DBMS are how the data is organized
Example:
DBMS VECHILE
HDBMS
NDBMS-------------------------2 WHeeler
RDBMS--------------------------4 Wheeler
SQL SERVER------------------------Honda City
ORACLE----------------------------Swift
Roles/Responsibilities of developer
-----------------------
Creating tables
Creating views
Creating synonyms
Creating sequences
Creating indexes
Creating procedures
Creating functions
Creating triggers
Writing Queries
Roles/Responsibilities of DBA
----------------
Installation of SQL Server
Creating database
Creating Logins
DB Backup and restore
DB Export and import
DB Upgradation and migration
Performance Tuning
Creating Database
-----------------
Open object explorer----select databases---roght click and create new
Once database is created, Database is created with two files
1)Data file(.MDF)--Master Data file
Data/MDF File stores data
2)Log file(.LDF)--Log Data file
Log files stores operations. What ever operations performed on database all that
operations are recorded in log file
DBA persons will take back up right..taking the back up means nothing but taking
the back up of these two files only.
Sql is originally introduced by IBM and initial name of this language was "SEQUEL"
and later it is renamed to SQL
User---SSMS---SQL---SQL Server---Database
tool---language---software---storage
User---Sqlplus---sql---oracle---database
In DDL---rename,flashback,purge
In DML insert all
DataTypes
-----
Character Data Type
-----------
ASCII UNICODE
---- ---------
char nchar
varchar nvarchar
varchar(max) nvarchar(max)
DATE BINARY
-------- -----------
Date Binary
Time Varbinary
DateTime varbinary(max)
CHAR(size)
---------
Allows character data upto 8000 chars
Recommended for fixed length char fields
Ex: NAME CHAR(10)
NARESH--- Remaining wasted
Note: In CHAR datatype extra bytes are wasted so CHAR is not recommended for
varibale length fields and it is recommended for fixed length fields
STATE_CODE CHAR(2)
--------
AP
TS
MH
COUNTRY_CODE CHAR(3)
------------
IND
AUS
USA
VARCHAR(SIZE)
--------
Allows character data upto 8000 characters
Recommended for variable length fields
SACHIN--------Released
Note: In Varchar extra bytes are not wasted and they are released
VARCHAR(MAX)
---------
Allows character data upto 2 gb
2) Relational Operators == Used for comparision == >, >=, <, <=, =, <> or !=
10>2 => TRUE
10<2 => FALSE
10=2 => FALSE
10<>2 => TRUE
4) Special Operators ==> BETWEEN, IN, LIKE, IS, ANY, ALL, EXISTS, PIVOT
Displaying Data
--------------
"SELECT" command is used to display/retrieve the data from table
--> By using select command We can display all columns and specific columns
--> By using select We can display all rows and specific rows.
Syntax: SELECT columns / * from <tablename>// Here the whole thing is called
query...Individual parts are called clauses.
SQL = ENGLISH
QUERIES = SENTENCES(will coummnicate)
CLAUSES = WORDS
WHERE Clause
----------
Used to get specific row/rows from table based on a condition.
Note: Greater than and less than operators can be used with dates also
Compound Condition
-----------
Multiple conditions combined with AND / OR operators is called compound condition
IN Operator
--------------
Use "IN" operator for list comparision.
List means empid=100,103 ..........
Use "IN" operator for "=" comparision with multiple values
WHERE COLNAME=V1,V2,V3====>INVALID
WHERE COLNAME IN (V!,V2,V3,----) ===> VALID
BETWEEN Operator
------------
Use BETWEEN Operator for range comaparision
Ex: 5000 to 10000
2020 to 2022
Like Operator
-----------
Use Like operator for pattern comparision.
IS Operator
----------
use IS operator for NULL comparision
ORDER BY Clause
-----------
Order by clause is used to sort data based on one or more columns either in
ascending or in desending order
Examples
---------
Arrange employee list name wise ascending order?
--------------
SELECT * from emp ORDER BY ename ASC
Note 2: ORDER BY Number is not based on table and it is based on select list.
Arrange employee list dept wise asc and with in dept sal wise desc??
-----------------------------------
SELECT empno,ename,sal,deptno FROM emp ORDER BY 4 ASC, 3 DESC
Display employee list working as clerk,manager and arrange list salary wise desc?
----------------------------
SELECT * from emp WHERE job IN ('CLERK','MANAGER') ORDER BY sal DESC
DISTINCT Clause
-------------
Distinct clause eliminates duplicates from select statement output not from actual
table
We can apply distinct on single column, mulitple columns or all columns
TOP Clause
----------
Used to display top N rows
used to limit no of rows return by query
Syntax: SELECT TOP <n> columns FROM tabname [WHERE] [ORDER BY <col>]
SET IMPLICIT_TRANSACTIONS ON
UPDATE Command
----------
Command used to modify the data in a table
we can update all rows or specific rows
we can update single column or multiple coulmns
If where condition is not there update is applied for all the rows
Examples
----
Update all the employees comm with 500?
UPDATE emp SET comm=500
Null Assignment =
NUll Comaprision IS
Alter
-----------
Command used to modify the table structure
Using Alter command we can add columns, drop column, modify a
columns(Increase/Decrease Field size, CHanging Data type)
Adding Column
-----------
ALTER TABLE <tabname> ADD colname DATATYPE(size)
After adding the column by default the new column is filled with nulls, to insert
data into the new column use update command
Dropping COlumn
------------
ALTER TABLE <tabname> DROP COLUMN colname
Modifying a column
----------
Alter Table <tabname> ALTER COLUMN colname DATATYPE(Size)
Drop Command
---------
Command used to drop table from database.
Drops table structure along with data.
Truncate Command
-----------
Deletes all the data from table
Will empty the table
Releases memory allocated for table
When truncate command is executed sql server goes to memory and releases all the
pages allocated for table, when pages are released then data stored in the pages
also deleted.
DELETE
------
DML COmmand
Deletes only data but not structure
TRUNCATE
--------
DDL COmmand
Deletes only data but not structure
DELETE VS TRUNCATE
-----------
DELETE
-----
DML
Can delete specific row/rows
where condition can be used with delete
Deletes row by row
slower
will not release memory
will not reset identity
TRUNCATE
---------
DDL
Can delete only allrows but cannot delete specific rows
where condition cannot be used with truncate
delete all rows at a time
faster
releases memory
will reset identity
SP_RENAME
-----------
Used to change tablename and column name
SP_RENAME 'oldname','newname'
Identity
----------
USed to generate sequence numbers
Used to auto increment column values
We can declare identity for integer columns
Synatx: IDENTITY(SEED,INCR).....Default(1,1)
Example
-----------
CREATE TABLE Cust(cid INT IDENTITY(100,1),cname VARCHAR(10))
INSERT INTO cust(cname) VALUES ('A')
INSERT INTO cust(cname) VALUES ('B')
INSERT INTO cust(cname) VALUES ('C')
Output
--------
CID cname
100
101
102
CID NAME
103
TRUNCATE TABLE cust
INSERT INTO CUST(CNAME) VALUES('k')
CID NAME
100 K
Note: By default sql server will not allow explicit value to identity column
To provide explicit value into identity column execute the following command
Types of functions
-------------
1) Date
2) String
3) Mathematical
4) Conversion
5) Special
6) Analytical
7) Aggregate
Date functions
-----------
1) GETDATE()---Returns Current date and time
DATEPART(INTERVAL,DATE)
SELECT DATEPART(YY,GETDATE())==>2022
MM====10
DD====01
DW====7 (Day of the week)
1--Sunday
7--Saturday
SELECT DATEPART(DAYOFYEAR,GETDATE())
DAYOFTHEYEAR=>274
HH=>8
MI=>21
SS=>10
QQ=>4(QUARTER) 1 JAN-MAR, 2 APR-JUN, 3 JUL-SEP, 4 OCT-DEC
FORMAT
--------
FUnction used to get date in different formats
FORMAT(date,format)
SELECT FORMAT(GETDATE(),'yyyy-MM-dd')
SELECT FORMAT(GETDATE(),'dd-MM-yyyy')
SELECT FORMAT(GETDATE().'MM/dd/yyyy')
DATENAME()
------------
USed to extract part of the date
MM DW
DATEPART 10 2
DATENAME OCTOBER MONDAY
DATEDIFF()
---------
Used to find difference between two dates
DATEDIFF(interval,date1,date2)
SELECT DATEDIFF(yy,'2021-10-10',GETDATE())=>1
SELECT DATEDIFF(mm,'2021-10-10',GETDATE())=>12
SELECT DATEDIFF(dd,'2021-10-10',GETDATE())=>365
SELECT ENAME,
DATEDIFF(MM,HIREDATE,GETDATE())/12 AS YEARS,
DATEDIFF(MM,HIREDATE,GETDATE())%12 AS MONTHS From EMP
DATEADD()
------
Used to add/subtract days,years,months to/from a date
DATEADD(interval, int,date)
SELECT DATEADD(DD,10,GETDATE())===>2022-10-20
SELECT DATEADD(DD,-10,GETDATE())===>2022-09-30
SELECT DATEADD(MM,2,GETDATE())===>2022-12-10
Scenario
---------
GOLD_RATES
DATEID RATE
2015-01-01 ??
2015-01-02 ??
2022-10-09 ??
EOMONTH()
--------
Returns end of the month i.e last day of the month
EOMONTH(DATE,INT)
String Functions
-----------
UPPER()---Converts string to uppercase
UPPER(arg)
Select UPPER('hello')===>HELLO
LOWER(arg)
SELECT LOWER('HELLO')===>hello
LEN(arg)
Select ename, len(ename) from emp//This query shows names along with length
SUBSTRING()
------------
Used to extract part of the string
THis functions takes 3 arguments
SUBSTRING(string,start,length)
REPLICATE()
------------
Repeats character for given number of times
REPLICATE(char,len)
SELECT REPLICATE('*',5)===>*****
SCENARIO
------
your a/c no XXXX1234 debited
REPLICATE('X',4) + RIGHT(ACCNO,4)
REPLACE()
------------
Used to replace one string with another string
REPLACE(str1,str2,str3)
SELECT REPLACE('hello','ell','abc')=>habco
SELECT REPLACE('hello','1','abc')=>heabcabco
SELECT REPLACE('hello','ell','')=>ho
SELECT REPLACE('@@he@@ll@@o@@','@','')=>hello
SELECT REPLACE('hello','elo','abc')=>hello
TRANSLATE()
------------
Used to translate one character to another character
TRANSLATE(str1,str2,str3)
SELECT TRANSLATE('hello','elo','abc')//habbc
e==>a
1==>b
o==>c
SELECT TRANSLATE('hello','elo','ab')//Error
TRANSLATE function used to encrypt data i.e converting plain text to cipher text
CHARINDEX()
------------
Returns position of a character in a string
CHARINDEX(char,string,[start])
Mathematical functions
------------
1) POWER:- Calculate power
POWER(3,2)=>9
3)SQUARE:-Returns square
SQUARE(5)=>25
SIGN(10)=>1
SIGN(-10)=>-1
SIGN(10-10)=>0
6) Rounding Numbers:-
ROUND => rounds numbers based on avg
CEILING => rounds number always to highest
FLOOR=> rounds number always to lowest
38.4747383 =>38
38.47
38.4747
ROUND
------------
ROUND(number,decimal places)
ROUND(38.5678,0)===>39
38---------------38.5---------------------39
300------------------350----------------400
380-----------------385-------------------390
ROUND(386,-3) => 0
0-------------------500-----------------------1000
SELECT ROUND(4567,-1),ROUND(4567,-2),ROUND(4567,-3)
4570 4600 5000
CEILING()
--------------------
Rounds number always to highest
CEILING(number)
FLOOR()
-------------
Rounds number always to lowest
FLOOR(number)
Conversion Functions
-------------------
Used to convert one datatype to another datatype
1.CAST
2.CONVERT
CAST
----------
CAST(source-expr as target-type)
CONVERT()
----------------
CONVERT(TARGET-TYPE,SOURCE-EXPR)
2) Using convert we cna display numbers in different formats which is not possible
using cast function
mm---minutes
MM---Months
FORMAT
-------
FORMAT(DATE,FORMAT)
Special Functions
--------------
ISNULL()-----Used to convert null values
TOTSAL= SAL+COMM
Syntax:
RANK() OVER (ORDER BY COLNAME ASC/DESC,---------)
DENSE_RANK() OVER (ORDER BY COLNAME ASC/DESC,---------)
Display ranks of the employees based on sal and highest paid employee should get
1st rank?
-------------------------
SELECT EMPNO,ENAME,SAL,RANK() OVER(ORDER BY SAL DESC) AS RNK FROM EMP
5000 1 1
4000 2 2
3000 3 3
3000 3 3
3000 3 3
2000 6 4
2000 6 4
1000 8 5
DIsplay ranks of the employees based on sal desc, if salaries are same then ranking
should be based on hiredate asc?
------------------------
SELECT ename,hiredate,sal, DENSE_RANK() OVER (ORDER BY sal DESC, hiredate ASC) as
rnk FROM emp
Partition By Clause
--------------------
Used to find ranks with in group for example to find ranks with in dept first we
need to divide the table dept wise and apply rank functions on each dept instead of
applying it on whole table.
ROW_NUMBER()
-------------------
Returns record numbers
row_number is also based on some column
data must be sorted
SELECT EMPNO,ENAME,SAL ROW_NUMBER() OVER (ORDER BY SAL DESC) AS RNO FROM EMP
Aggregate Functions
------------------
From a group of value if we get a single value that is called aggregate
These functions process group of rows and returns one value
SUM()
-----
Returns total
SUM(args)
Note: sum,avg functions cannot be applied on date and char columns can be applied
only on numeric columns
COUNT(*)
-----------
Returns no of rows in a table.
SELECT COUNT(*) FROM EMP
Select count(comm) from emp// If nulls are there in the column they are not
countable
Note: Window functions can only appear in the SELECT or ORDER BY caluses
CASE Statement
--------------
Used to implement IF-THEN-ELSE
Useful to return expressions based on conditions
Case statements are 2 types
1) Simple case 2) Searched case
Simple case
------------
Use simple case when conditions based on "=" operator
CASE COLNAME
WHEN VALUE1 THEN RETURN EXPR1
WHEN VALUE2 THEN RETURN EXPR2
---------------------
ELSE RETURN EXPR
END
SELECT ENAME,
CASEDEPTNO
WHEN10 THEN 'ACCOUNTS'
WHEN20 THEN 'RESEARCH'
WHEN30 THEN 'SALES'
ELSE 'UNKNOWN'
END AS DNAME
FROM EMP
Update emp
set sal=CASE job
WHEN 'clerk' THEN sal+(sal*0.1)
WHEN 'salesman' THEN sal+(sal*0.15)
WHEN 'manager' THEN sal+(sal*0.2)
ELSE sal+(sal*0.05)
END
Searched Case
--------------
Use searched case when conditions not based on "=" operator.
CASE
WHEN COND1 THEN RETURN EXPR1
WHEN COND2 THEN RETURN EXPR2
----------------------
ELSE RETURN EXPR
END
SELECT ENAME,SAL,
CASE
WHEN SAL>3000 THEN 'Hisal'
WHEN SAL<3000 THEN 'Lowsal'
ELSE 'Avgsal'
END as SALRANGE
FROM EMP
SELECT SNO,SNAME
S1+S2+S3 As Total
(S1+S2+S3)/3 As Avg
CASE
WHEN S1>=35 AND S2>=35 AND S3>=35 THEN 'PASS'
ELSE 'FAIL'
END AS RESULT
FROM EMP
GROUP BY Clause
-----------------
Used to group rows based on one or more columns to calculate min,max,sum,avg,count
for each group.
GROUP BY clause converts detailed data into summarized data which is useful for
data analysis.
Syntax:
-------
Select columns from tablename [where condition]
group by <colname>,---------------
[having condition]
[order by <colname> asc/desc-------]
Here in this syntax group by clause is mandatory and other clauses are optional.
SQL SERVER cannot calculate dept wise count before group by and it can calculate
only after group by , so apply the condition COUNT(*)> after group by using HAVING
clause.
Scenario
----
PERSONS
AADHARNO NAME GENDER AGE ADDR CITY STATE
ROLLUP
-----------
rollup displays subtotals for each group and also displays grand total
CUBE
---------
displays subtotals for each group by column (deptno,job) and also displays grand
total
Display state wise and with in state gender wise population and display state wise
and gender wise subtotals
----------------------------------
SELECT state,gender,count(*) FROM persons
GROUP BY CUBE(state,gender)
ORDER BY state ASC,gender ASC
GROUPING_ID
-------------------
This function accepts group by columns and returns sub total belong to which group
by column
GROUPING_ID(deptno,job)
For clear understanding for user write the above query like this
Integrity Constraints
-------------------------
Integrity constraints are the rules to maintain Data Integrity i.e Data Quality
Used to prevent users from entering invalid data
Used to enforce rules like min bal must be 1000
1) NOT NULL
2) UNIQUE
3) PRIMARY KEY
4) CHECK
5) FOREIGN KEY
6) DEFAULT
1) column level
2) table level
column level
-----------------
If constraints are decalred immediately after declaring column then it is called
column level
NOT NULL
-------
NOT NULL constraint doesnt accept null values
A column decalred with NOT NULL is called mandatory column
Example:
---------
CREATE TABLE emp22(
empno INT,
ename VARCHAR(10) NOT NULL)
INSERT INTO emp22 VALUES(100,NULL)==>Error
INSERT INTO emp22 VALUES(101,'A')
Unique
-----------
Unique constriant doesnt acccept duplicates
Example
----------
CREATE TABLE cust(
cid int,
cname varchar(10),
emailid varchar(20) UNIQUE)
PRIMARY KEY
----------------
Primary key doesnt accept duplicates and nulls
Primary key is the combination of unique and not null
In DB tables one column must be there to uniquley identify the records and that
column must be declared with primary key.
Example
-----------
CREATE TABLE emp33(
empid INT PRIMARY KEY,
ename VARCHAR(10) NOT NULL,
sal MONEY)
Beacuse empid doesnt allow duplicates and nulls so using empid we can uniquely
identify the records.
Primary Key
---------
1) Doesnt allow nulls
2) Only one column can be declared with primary key
Candidate key
-------------
A field eligible for primary key is called candidate key
VECHILE
VECHNO VNAME MODEL PRICE CHASSISNO
While creating table secondary keys are declared with UNIQUE & NOT NULL
CHECK
---------
Use check constraint when rule based on condition
CHECK(condition)
EMAILID VARCHAR(30)
CHECK(EMAILID LIKE '%@%'
AND(
EMAILID LIKE '%.COM' OR EMAILID LIKE '%.CO' OR EMAILID LIKE '%.IN'
))
Foreign Key
------------
1) foreign key is used to establish relationship between two tables.
2) To establish relationship take primary key of one table nad add it to another
table as foreign key and declare with references constraint.
3) Foreign key allows duplicates and nulls
4) After declaring foreign key a relationship is established between two tables
calles parent/child relation ship.
5) PK table is parent and FK table is child
Assignment
-----------
ACCOUNTS
ACCNO ACTYPE BAL
Rules
------------
1) Accno should not be duplicate and null
2) Actype must be 's' or 'c'
3) Bal must be min 1000
TRANSACTIONS
TRID TTYPE TAMT TDATE ACCNO
Rules
--------
1) trid must be auto incremented
2) ttype must be 'w' or 'd'
3) tamt must be multiple of 100
4) tdate must be system date
5) accno should match with accounts table accno
Types of relationships
----------------------
one to one (1:1)
one to many(1:m)
many to one(m:1)
many to many(m:m)
In sql server by default one to many relationship is created between two tables
To establish one to one (1:1) realtion ship between two tables decalre forign key
with unique constraint.
Example :- (1:1)
DEPT
DNO DNAME
10 HR
20 IT
MGR
MGRNO MNAME DNO REFRENCES DEPT(DNO) UNIQUE
1 A 10
2 B 20
3 C 10====>INVALID
In the above example one dept is managed by one manager and one manager manages one
dept so relationship between two tables is 1:1
Many to Many:---(M:N)
--------------------------
By default sql server doesnt support many to many relationship
Example
----------
PRODUCTS CUSTOMERS
prodid pname price cid name addr
100 A 1000 10 x HYD
101 B 2000 11 k HYD
Relationship between products and customer is many to many because one product can
be purchased by many customers and one customer can purchase many products.
To establish many to many create 3rd table and add primary keys of both tables as
foreign keys
SALES
DATEID PRODID CUSTID QTY AMOUNT
15// 100 10
15// 100 11
15// 101 10
DEFAULT
-----------
==> While inserting if we skip hiredate then sql server inserts default value
CREATE TABLE emp66
(
empno INT,
hiredate DATE DEFAULT GETDATE()
)
empno hiredate
100 2022-10-22
101 2022-01-01
102 NULL
TABLE LEVEL
-------------
If constraints are decalred after declaring all columns then it is called table
level
Example:
STUDENT COURSE
SID NAME CID NAME
1 A 10 SQL
2 B 11 .NET
REGISTRATIONS
SID CID DOR FEE
1 10 ? ?
1 11 ? ?
2 10 ? ?
REGISTRATIONS
SID CID DOR FEE
1 10 ? ?
1 11 ? ?
2 10 ? ?
CERTIFICATES
CERTNO DOI SID CID
1000 ? 1 10
1001 ? 1 11
1002 ? 2 11====>Invalid
In the above example SID,CID combination should match with registrations table
primary key i.e SID,CID combination so declare this combination as foreign key at
table level.
Because some of the employee salaries are less than 3000 while adding constraint
sql server also validates existing data
WITH NOCHECK
------------------
If check constraint added with "NO CHECK" then sql server will not validate
existing data and it validates new data.
Dropping Constraints
-------------------
ALTER TABLE <tabname>
DROP CONSTRAINT <name>
NOTE:
-------
primary key cannot be dropped if referenced by some fk
primary key table cannot be dropped if referenced by some fk
primary key table cannot be truncated if referenced by some fk
DELETE Rules
-----------------
ON DELETE NO ACTION
ON DELETE CASCADE
ON DELETE SET NULL
ON DELETE SET DEFAULT
ON DELETE NO ACTION
----------------------------
Parent row cannot be deleted if associated with child rows
Scenario
----------------
ACCOUNTS
ACCNO ACTYPE BAL
100 S 10000
LOANS
ID TYPE AMT ACCNO
1 H 30 100
2 C 10 100
ON DELETE CASCADE
--------------------------
If parent row is deleted then it is deleted along with child rows.
Scenario
------------
ACCOUNTS
ACCNO ACTYPE BAL
100 S 10000
TRANSACTIONS
TRID TTYPE TDATE TAMT ACCNO REFRENCES ACCOUNTS (ACCNO)
1 W ? 2000 100 ON DELETE CASCADE
2 D ? 5000 100
RULE: When account is closed then along with account delete transactions.
ON DELETE SET NULL
----------------------
If parent row is deleted then it is deleted without deleting child rows but foreign
key will be set to null.
EMPNO DNO
1 NULL
2 NULL
Scenario
----------------
PROJECTS
projid pname duration
100
101
EMP
empid name projid
1 100
2 100
Update Rules
------------------
ON UPDATE NO ACTION
ON UPDATE CASCADE
ON UPDATE SET NULL
ON UPDATE SET DEFAULT
Update rules specifies how foreign key value is affected if we update primary key
value
JOINS
---------
Types of joins
----------------------
1) Inner join/ Equi Join
2) Outer Join
Left
Right
Full
3) Non Equi Join
4) Self Join
5) Cross Join/ Cartesian Join
To perform Inner join between the two tables there must be a common field and name
of the common field need not to be same and pk-fk relation shipis not compulsory
join condition
-----------------
based on the given join condition sql server joins the records of two tables.
table1.commonfield = table2.commonfield
Example:
-----------
EMP DEPT
EMPNO ENAME SAL DEPTNO DEPTNO DNAME LOC
1 A 3000 10 10 ACCTS
2 B 4000 20' 20 RESEARCH
3 C 5000 30 30 SALES
4 D 3000 20 40 OPERATIONS
5 E 2000 NULL
SELECT ename,sal,dname,loc
FROM emp INNER JOIN dept
ON emp.deptno = dept.deptno
Note:
--------
In join queries declare table alias and prefix column names with table alias for
two reasons
1) to avoid ambiguity
2) for faster execution
Outer Join
---------------
Inner join returns only matching records but wont return unmatched records but to
display unmatched records perform outer join.
LEFT JOIN
-------------
returns all rows(matched+unmatched) from left side table and matching rows from
right side table.
Above query returns all rows from emp and matching rows from dept
A ACCT
B RESEARCH
C SALES
D ACCT
E NULL ==> unmatched from emp
Right Join
----------------
Returns all rows from right side table and matching rows from left side table.
A ACCT
B RESEARCH
C SALES
D ACCT
NULL OPERATIONS ==> unmatched from dept
Full Join
--------------
Returns all rows from both tables.
SELECT e.ename,d.dname
FROM emp e RIGHT JOIN dept d
ON e.deptno=d.deptno
A ACCT
B RESEARCH
C SALES
D ACCT
E NULL====>unmatched from emp
NULL OPERATIONS====>unamtched from dept
E NULL
NULL OPERATIONS
Both Tables
---------------------
SELECT e.ename,d.dname
FROM emp e FULL JOIN dept d
ON e.deptno=d.deptno
WHERE e.ename IS NULL
OR
dname IS NULL
E NULL
NULL OPERATIONS
SELF JOIN
--------------
Joining a table to itself is called self join
In Self join a record in one table joined with another record of same table
To perfrom self join the same table must be declared two times with different alias
Question
--------------
TEAMS
ID COUNTRY
1 IND
2 AUS
3 NZ
TEAMS A TEAMS A
ID COUNTRY ID COUNTRY
1 IND 1 IND
2 AUS 2 AUS
3 NZ 3 NZ
A=1,2
B=3,4
If cross join performed between teo tables then all the records of 1st table joined
with all the records of 2nd table
To perform cross join submit the join query without join condition.
SELECT e.ename,d.dname
FROM emp e CROSS JOIN dept d
EMP DEPT
EMPNO ENAME SAL DEPTNO DEPTNO DNAME LOC
1 A 3000 10 10 ACCTS
2 B 4000 20' 20 RESEARCH
3 C 5000 30 30 SALES
4 D 3000 20 40 OPERATIONS
5 E 2000 10
ON e.deptno = d.deptno
-------------------
1 A 3000 10 ACCTS
2 B 4000 20' RESEARCH
3 C 5000 30 SALES
4 D 3000 20 RESEARCH
5 E 2000 10 ACCTS
GROUP BY d.dname
-------------------
ACCTS
1 A 3000
5 E 2000
RESEARCH
2 B 4000
4 D 3000
SALES
3 C 5000
Questions
-----------------
SALES
DATEID PRODID CUSTID QTY AMOUNT
2022-10-31 100 10 1 1000
PRODUCTS
PRODID PNAME PRICE CATEGORY
100 AAA 1000 ELECTRONICS
CUSTOMERS
CUSTID NAME ADDR COUNTRY
10 KK HYD IND
SET OPERATORS
--------------
UNION
UNION ALL
INTERSECT
EXCEPT
A = 1,2,3,4
B = 1,2,5,6
A UNION B = 1,2,3,4,5,6
A UINON ALL B = 1,2,3,4,1,2,5,6
A INTERSECT B =1,2
A EXCEPT B = 3,4
B EXCEPT A = 5,6
In sql server set operations are performed between set of rows return by two
queries.
SELECT STATEMENT 1
UNION/UNION ALL/INTERSECT/EXCEPT
SELECT STATEMENT 2
Rules
--------
1) Both queries must return same no of columns
2) Corresponding columns data type must be same
UNION
-------------
==> combines rows return by two queries
==> eliminates duplicates
==> sorts result
CLERK
MANAGER
ANALYST
CLERK
ANALYST
SALESMAN
SALESMAN
SALESMAN
MANAGER
SALESMAN
ANALYST
CLERK
MANAGER
SALESMAN
UNION VS JOIN
---------------
UNION JOIN
Scenario
---------------
EMP_US
EMPNO ENAME DNO
100 A 10
101 B 20 DEPT
DNO DNAME
EMP_IND 10 HR
EMPNO ENAME DNO 20 IT
200 A 10
201 B 20
UNION ALL
------------------
==> combines rows return by two queries
==> duplicates are not eliminated
==> result is not sorted
INTERSECT
--------------------
returns common values from the output of two select statements
EXCEPT
--------
returns values from 1st query output and not present in 2nd query output
SUBQUERIES/NESTED QUERIES
-------------------------------------
A query in another query is called sub query or nested query
One query is called inner/child/sub query
other query is called outer/parent/main query
First sql server executes inner query then it executes outer query and result of
inner query is input to outer query
Use subquery when where condition based on unknown value
Types of subqueries
---------------------
1) Single row subqueries
2) multi row subqueries
3) co-related subqueries
4) derived tables
5) scalar subqueries
SELECT ename FROM emo WHERE sal = (SELECT MAX(sal) FROM emp) => Correct
Note:
----------
Outer query can be SELECT/INSERT/UPDATE/DELETE but inner query must be always
SELECT
Multirow subqueries
--------------------------
If subquery returns more than one value then it is called multirow subquery
SELECT columns
FROM tabname
WHERE colname OP (SELECT STATEMENT)
==> OP must be IN, NOT IN, ANY, ALL
ANY operator
-----------------
==> used for > < comaprision with multiple values
ALL
--------
used for > < comaprision with multiple values
WHERE
DERIVED TABLES
------------------
Subqueries in FROM clause are called derived tables
SELECT columns
FROM (SELECT statement) <alias>
WHERE cond
==> Sub query output acts like a table for outer query
FROM
WHERE
GROUP BY
HAVING
SELECT
ORDER BY
Above query returns annual salaries of all employees but to display employees whose
annual salary > 20000 then
column alias cannot be used in where clause because where clause is executed before
select, to overcome this ise derived table
SELECT *
FROM ( SELECT ename,sal*12 as annsal FROM emp) AS E
WHERE annsal>20000
Example 2
-------------
Display ranks of the employees based on sal and highest paid employee should get
1st rank?
-----------------------
SELECT ENAME,SAL,DENSE_RANK() OVER (ORDER BY SAL DESC) AS RNK From EMP
Above query returns ranks of all the employees but to display top 5 employees
SELECT ENAME,SAL,
DENSE_RANK() OVER (ORDER BY SAL DESC) AS RNK FROM EMP
WHERE rnk<=5======> Error
WHERE rno=5
WHERE rno%2=0
DELETE
FROM(SELECT empno,ename,sal,ROW_NUMBER() over (order by empno asc)
FROM emp) AS E
WHERE rno<=3 ===> Error
Note: In dervived tables outer query cannot be DML and it must be always SELECT. To
overcome this use CTEs.
CTE
----------
CTE stands for common table expression, It is a named query that can be referenced
in another query like SELECT/INSERT/UPDATE/DELETE.
In Dervied tables outer query cannot be DML but in CTE'S outer query can be
SELECT/INSERT/UPDATE/DELETE
Synatx:
--------
WITH <name>
AS
(SELECT STATEMENT)
SELECT /INSERT/UPDATE/DELETE
Example
----------
Delete first 5 rows from emp??
----------------
WITH E AS
(SELECT empno,ename,ROW_NUMBER() OVER (ORDER BY empno ASC) as rno
FROM emp)
DELETE FROM E WHERE rno<=5
Pivot Operator
---------------------
==> used to convert rows into columns
==> used for cross tabulation
==> used to display data in matrix form
Example
-------
10 20 30
ANALYSR ?? ?? ??
CLERK ?? ?? ??
MANAGER ?? ?? ??
SALESMAN ?? ?? ??
Syntax
-------------
SELECT columns FROM (SELECT required data) AS <ALIAS>
PIVOT
(
AGGR-EXPR FOR COLNAME IN (V1,V2,V3,-----)
)
ORDER BY COLNAME ASC/DESC
Example
------------
SELECT * FROM (SELECT deptno,job,sal FROM emp) AS E
PIVOT
(
SUM(sal) FOR deptno IN ([10],[20],[30])
) AS PIVOT_EXPR
ORDER BY job ASC
Example 2
-----------
1 2 3 4
1980 ? ? ? ?
1891 ? ? ? ?
1982 ? ? ? ?
1983 ? ? ? ?
Example 3
--------------
STUDENTS
SNO SNAME SUBJECT MARKS
1 A MAT 80
1 A PHY 50
1 A CHE 60
2 B MAT 70
2 B PHY 40
2 B CHE 50
Output
------------
SNO SNAME MAT PHY CHE
1 A 80 50 60
2 B 70 40 50
UNPIVOT Operator
----------------
1) reverse of PIVOT is called UNPIVOT operator
2) converts columns into rows
STUDENT
SNO SNAME MAT PHY CHE
1 A 80 90 70
2 B 60 50 40
OUTPUT
-----------
SNO SNAME SUBJECT MARKS
1 A MAT 80
2 A PHY 90
3 A CHE 70
2 B MAT 60
2 B PHY 50
2 B CHE 70
==> the new table is created with rows and columns return by query .
MERGE command
------------------
=> Command used to merge data into a table
=> It is the combination of insert, update and delete
=> Widely used in ETL applications
=> Used to manage replicas
E==> Extract
T==> Transform
L==> Load
Syntax:
------------
MERGE INTO <TARGET-TABLE> <ALIAS>
USING <SOURCE-TABLE> <ALIAS>
ON(CONDITION)
WHEN MATCHED THEN
UPDATE
WHEN NOT MATCHED THEN
INSERT
WHEN NOT MATCHED BY SOURCE THEN
DELETE
Example:-
-------
Step 1:- Create source table
CUSTS
CID NAME ADDR
1 A HYD
2 B MUM
CUSTT
CID NAME ADDR
1 A HYD
2 B MUM
DB SECURITY
------------
1 LOGINS => Provides security at server level
2 USERS => provides security at db level
3 PIVILEGES => provides security at table level
4 VIEWS => provides security at row and col level
VIEWS
------------
==> A view is a subset of a table
==> A view is a virtual table because it doesnt store data and doesnt occupy menory
and it always derives data from base table
==> A view is representation of a query
==> Views are created
1) For security
2) To reduce complexity
Views provides another level of security by granting specific rows and columns to
users
1) Simple Views
2) Complex Views
Simple Views
------------
If view created on single table then it is called simple view
example:
-----------
Create view v1
as
Select empno, ename, job, deptno from emp
==> When above command is executed sql server creates view v1 and stores query but
not query output.
Select * from v1
==> When above query submitted to sql server it executes the query as follows
NARESH
-------------
1) SELECT * FROM V1
2) UPDATE V1 SET JOB='SALESMAN' WHERE EMPNO=7698
3) UPDATE V1 SET SAL=4000 WHERE EMPNO=7698=====> Error
==> user "NARESH" can access only the employees belongs to 20th department
Complex views
----------------
A view said to be complex view
With the help of view complex queries are converted into simple queries
After creating view whenever we want data from emp & dept tables instead of writing
join query write the simple query as follows
Example 2
-----------------
CREATE VIEW CV2
AS
SELECT D.DNAME, MIN(E.SAL) AS MINSAL,
MAX(E.SAL) AS MAXSAL,
SUM(E.SAL) AS TOTSAL,
AVG(E.SAL) AS AVGSAL,
COUNT(*) AS CNT
FROM EMP E INNER JOIN DEPT D
ON E.DEPTNO=D.DEPTNO
GROUP BY D.DNAME
Droping View
-----------------
Drop VIEW V1
WITH SCHEMABINDING
------------------------
If view created with "SCHEMABINDING" then sql server will not allow users to drop
base table if any view exists on the base table
Rules
----------
1) '*' is not allowed in schema binding
2) tablename should be prefixed with schemaname
CREATE VIEW V5
WITH SCHEMABINDING
AS
SELECT DEPTNO,DNAME,LOC FROM DBO.DEPT
SYNONYMS
---------------
1) A synonym is another name or alternative name for a table or view
2) If tablename/viewname is lengthy then we can give a simple and shortname to the
table/view called synonym and instead of using tablename we can use synonym name.
After creating synonym instead of using tablename we can use synonym name in
SELECT/INSERT/UPDATE/DELETE queries.
1) SELECT * FROM E
2) UPDATE E SET COMM=500 WHERE EMPNO=7369
Question
-----------------
CREATE SYNONYM E FOR EMP
SELECT * FROM EMP E'
SP_RENAME 'EMP','E'
Droping Synonym
--------------
DROP SYNONYM E
SEQUENCES
--------
==> Sequence is also a db object created to generate sequence numbers
==> Sequence can use to auto increment column values.
Syntax
--------
CREATE SEQUENCE <NAME>
[START WITH <VALUE>]
[INCREMENT BY <VALUE>]
[MAXVALUE <VALUE>]
[MINVALUE <VALUE>]
[CYCLE/NOCYCLE]
[CACHE <SIZE>]
Example 1:
-------------
CREATE SEQUENCE S1
START WITH 1
INCREMENT BY 1
MAXVALUE 5
Example 3:
--------------
INVOICE
INVNO INVDT
NIT/1122/1 2022-11-10
/2
CREATE SEQUENCE S3
START WITH 1
INCREMENT BY 1
MAXVALUE 9999
CYCLE/NOCYCLE
------------------
==> BY default sequence is created with NOCYCLE.
==> If sequence created with NOCYCLE then it starts from start with and generated
upto max and after reaching max then it stops.
==> If sequence create with CYCYLE then it starts from start with and generates
upto to max and after reaching max then it reset to min
CREATE SEQUENCE S5
START WITH 1
INCREMENT BY 1
MAXVALUE 5
MINVALUE 1
CYCLE
CACHE 4
Sql server preallocates 100 values in cache memory, so when we call 'next value for
seq' then sql server goes to cache memory and gets the value and return the value
from cache memory.
so no of requests going to db are reduced and performance is improved.
Droping Sequence
----------------
DROP SEQUENCE S1
INDEXES
--------------
--> Index is also a db object created to improve the performance data accessing
--> Index improves performance of search operation
--> Index in db is similar to index in textbook. In textbook using index a
particular topic can be located fastly and in db using index a particular record
can be located fastly.
---> Indexes are created on columns and that column is called index key.
Types of Indexes
----------------
1) Non Clustered
simple
composite
unique
2) Clustered
When we submit query to sql server it uses following 2 methods to locate the record
1) TABLE SCAN
2) INDEX SCAN
In table scan sql server scans complete table i.e each and every record but in
index scan on avg sql server scans only half of the table
Composite Index
-----------------
If index created on multiple columns then it is called composite index
EMP
DEPTNO JOB
20 CLERK
30 SALESMAN
10 MANAGER
20 ANALYST
30 SALESMAN
10 CLERK
20 CLERK
30 CLERK
20
10 30
10 CLERK * 20 ANALYST * 30 CLERK *
10 MANAGER * 20 CLERK * 30 SALESMAN *,*
Note: Sql server uses above index when where condition based on leading column of
the index i.e deptno
UNIQUE INDEX
------------------
unique index doesnt allow duplicate values into the column on which index is
created
Clustered Index
-----------------
A non cluster index stores pointers to actual records where as clustered index
stores actual records.
In non clustered index order of the records in table and order of the records in
index will not be same where as in clustered index order will be same
Example
----------
CREATE TABLE CUST
(
CID INT,
CNAME VARCHAR(10)
)
50
30 70
10 A 40 C 60 D 80 B
SELECT * FROM CUST ===> Sql server goes to clustered index and access records from
left to right
10 A
40 C
60 D
80 B
Note:
----------
--> only one clustered index allowed per table
--> by default sql server creates clustered index on primary key column
Droping Index
----------------
DROP INDEX EMP.I1
SERVER
DATABASE
TABLES
ROWS & COLUMNS
CONSTRAINTS
INDEXES
TRIGGERS
VIEWS
SYNONYMS
SEQUENCES
PROCEDURES
FUNCTIONS
1) improves performance
-----------------------------
In TSQL, sql commands can be grouped into one block and we submit that block to sql
server, so in TSQL no of requests and response between user and sql server are
reduced and performance is improved.
3) supports loops
--------------
tsql supports looping statements like while, using loops we can executes statements
repeatedly multiple times
5) supports reusability
---------
TSQL programs can be stored in db and applications which are connected to db can
reuse those programs
6) supports security
--------------
because these programs are stored in db so only authorized users can execute these
programs
1) anonymous blocks
2) named blocks
strored procedures
stored functions
triggers
Anonymous blocks
-----------------
A TSQL block without name is called anonymous block
1) DECLARE
2) SET
3) PRINT
DECLARE Statement
--------------------
Used to declare variables
SET Statement
--------------
Used to assign value to variable
SET @varname=value
PRINT Statement
-------------
Used to print variable values or messages
PRINT 'hello'
PRINT @x
example 1:
-----------
DECALRE @a tinyint, @b tinyint, @c tinyint
SET @a=10
SET @b=20
SET @c=@a+@b
PRINT @c
example 2:
-------------
write a program to input and print day of the week?
----------------------
DECLARE @d DATE
SET @d='2023-01-01'
PRINT DATENAME(dw,@d)
output: sunday
SELECT @var1=col1,
@var2=col2
FROM tabname
WHERE condition
example
-------------
1) SELECT @s=ename FROM emp WHERE empno=7844
2) SELECT @n=ename, @s=sal FROM emp WHERE empno=7844
IF-ELSE
------------
IF COND
BEGIN
STATEMENTS
END
ELSE
BEGIN
STATEMENTS
END
MULTI - IF
------------
IF COND1
BEGIN
STATEMENTS
END
ELSE IF COND2
BEGIN
STATEMENTS
END
ELSE IF COND3
BEGIN
STATEMENTS
END
ELSE
BEGIN
STATEMENTS
END
NESTED IF
--------
Write a program to input empno and increment sal by specific amount and after
increment if sal exceeds 5000 then cancel that increment?
--------------------------------
DECLARE @eno INT, @amt MONEY, @sal MONEY
SET @eno=107
SET @amt=2500
UPDATE EMP SET SAL=SAL+@amt WHERE EMPNO=@eno
SELECT @sal=SAL FROM EMP WHERE EMPNO=@eno
IF @sal>5000
ROLLBACK
ELSE
COMMIT
Using ROWCOUNT
-----------------------
DECLARE @sacno int, @tacno int, @amt money, @bal money
SET @sacno=100
SET @tacno=101
SET @amt=1000
SELECT @bal=bal FROM accounts WHERE accno=@sacno
IF @amt>@bal
PRINT 'insufficient balance'
ELSE
BEGIN
UPDATE accounts SET bal=bal-@amt WHERE accno=@sacno
SET @CNT1=@@ROWCOUNT
UPDATE accounts SET bal=bal+@amt WHERE accno=@tacno
SET @CNT2=@@ROWCOUNT
IF @CNT1=1 AND @CNT2=1
COMMIT
ELSE
ROLLBACK
END
Note:
--------
Every transaction must gurantee a peroperty called atomocity i.e all or none if
transaction contains multiple operations if all re successful then it must be
saved, if any of the operation fails then entire transaction must be cancelled
@@ROWCOUNT
----------------
It is a system variable that returns no of rows affected by dml
If DML is successful then it returns no of rows affected
If DML fails then returns 0
While Loop
--------------
Loops are used to execute statements repeatedly multiple times.
WHILE(COND)
BEGIN
Statements
END
Cursors
-------------
ftech statement fetches one row at a time but to process multiple rows fetch
statement should be executed multiple times, so fetch statement should be inside a
loop
Closing Cursor
---------------
CLOSE <cursor-name>
Ex: CLOSE C1
Deallocating cursor
--------------------
DEALLOCATE <cursor-name>
Ex: DEALLOCATE C1
@@FETCH_STATUS
--------
It is a system variable that returns
0 ====> if fetch successful
-1====> if fetch unsuccessful
STUDENT
sno sname S1 S2 S3
1 A 80 90 70
2 B 70 60 30
RESULT
sno total avg result
Write a program to calculate all the students total, avg, result and insert into
result table
---------------------------
DECLARE C1 CURSOR FOR SELECT sno, s1,s2,s3 FROM student
DECLARE @sno int, @s1 int, @s2 int, @s3 int, @total int, @avg numeric(5,2)
DECLARE @res char(4)
OPEN C1
FETCH NEXT FROM C1 INTO @sno,@s1,@s2,@s3
WHILE(@@FETCH_STATUS=0)
BEGIN
SET @total=@s1+@s2+@s3
SET @avg=@total/3
IF @s1>=35 AND @s2>=35 AND @s3=35
SET @res='pass'
ELSE
SET @res='fail'
INSERT INTO RESULT VALUES(@sno,@total,@avg,@res)
FETCH NEXT FROM C1 INTO @sno,@s1,@s2,@s3
END
CLOSE C1
DEALLOCATE C1
SCROLLABLE CURSOR
-----------
==> By default cursor is forward only cursor and it supports forward navigation
but doesnt support backward navigation
==> If cursor declared with SCROLL then it is called scrollable cursor and it
supports both forward and backward navigation.
Example
--------------
DECLARE C1 CURSOR SCROLL FOR SELECT ename FROM emp
DECLARE @ename VARCHAR(10)
OPEN C1
FETCH FIRST 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
Write a program to print names from last to first?
--------------------------------
DECLARE C1 CURSOR SCROLL FOR SELECT ename FROM emp
DECLARE @ename VARCHAR(10)
OPEN C1
FETCH LAST FROM C1 INTO @ename
WHILE(@@FETCH_STATUS=0)
BEGIN
PRINT @ename
FETCH PRIOR FROM C1 INTO @ename
END
CLOSE C1
DEALLOCATE C1
==> Erros that are raised during program execution are called runtime errors
Ex: DECLARE @x TINYINT
SET @x=1000 ==> runtime Error
==> If any statement causes runtime error then sql server displays error message
and contimues program execution
===> To replace system generated message with our own simple and user freindly
message then we need to handle that runtime error
BEGIN TRY
Statements ====> causes runtime error
END TRY
BEGIN CATCH
Statements ====> handles runtime error
END CATCH
Example
-------------------
DECLARE @a TINYINT, @b TINYINT, @c TINYINT
BEGIN TRY
SET @a=100
SET @b=2000
SET @c=@a/@b
PRINT @c
END TRY
BEGIN CATCH
PRINT 'runtime error'
END CATCH
=====>
CREATE TABLE emp88
(
empno int primary key,
ename varchar(10) not null,
sal money check(sal>-3000)
)
state ==> between 00 through 255. If you raise the same user defined error at
multiple locations, you can use a unique state number for each location to make it
easier to find which section of the code is causing the errors.
Write a program to increment specific employee sal by specific amount but sunday
updates are not allowed
------------------
DECLARE @eno int,@amt money
SET @eno=7369
SET @amt=1000
IF datename(dw,GETDATE())='sunday'
RAISEERROR('sunday not allowed',15,1)
ELSE
UPDATE emp SET sal=sal+@amt WHERE empno=@eno
Advantages
------------------
1) Modular Programming
-----------------
with the help of procedures and function a big tsql program can be divided into
small modules
2) reusability
------------
beacuse these programs are stored in db and applications which are connected to db
can reuse these programs
3) security
------------------
because these programs are stored in db so only authorized users can execute these
programs
STORED PROCEDURES
--------------------------
A procedure is a named TSQL bloack that aceepts some input perfroms some action on
db and may or may not returns a value
Syntax
--------------
CREATE OR ALTER PROCEDURE <name>
parameters if any
AS
STATEMENTS
Parameters
----------
We can declare parameters and we can pass valyes to parameters
parameters are 2 types
1) INPUT
2) OUTPUT
execution
-----------
execute raise_salary
execution
---------------
1) EXECUTE raise_salary 100,1000 (positional association)
2) EXECUTE raise_salary @eno=100, @amt=1000 (named association)
3) EXECUTE raise_salary @amt=1000, @eno=100
example 3:
------------------
Procedure with output parameter
Execution
----------------
declare @sal money
execute raise_salary @eno=100, @amt=1000, @newsal=@sal ouput
print @sal
Example 4
-------------------
ACCOUNTS
ACCNO ACTYPE BAL
100 S 10000
101 S 20000
Execution
---------------
declare @b money
execute debit @acno=100, @amt=1000, @newbal=@b output
print @b
create procedure for money deposit
create procedure for money transfer
A function is also a named tsql block that accepts some input performs some
calculation and must return a value.
1) Scalar Valued
2) Table Valued
Syntax
---------------------
CREATE OR ALTER
FUNCTION <NAME>(paramters if any) RETURNS <type>
AS
BEGIN
statements
RETURN <expression>
END
Example 1
-----------
CREATE OR ALTER
FUNCTION CALC(@a INT,@b INT,@op CHAR(1)) RETURNS INT
AS
BEGIN
DECLARE @c INT
IF @op='+'
SET @c=@a+@b
ELSEIF @op='-'
SET @c=@a-@b
ELSEIF @op='*'
SET @c=@a*@b
ELSEIF @op='/'
SET @c=@a/@b
RETURN @c
Execution
---------------
1) Sql commands
2) another program
3) front end applications
Example 2
----------------
create a function that accepts deptno and returns employee names working for that
dept sepearated by ','
input deptno:- 20
output:- smith, jones, scott, adams, ford
CREATE OR ALTER
FUNCTION getNames(@d INT) RETURNS VARCHAR(1000)
AS
BEGIN
DECLARE C1 CURSOR FOR SELECT ename FROM emp WHERE deptno=@d
DECLARE @name VARCHAR(10),@s VARCHAR(500)
OPEN C1
FETCH NEXT FROM C1 INTO @name
WHILE(@@FETCH_STATUS=0)
BEGIN
SET @s=@s+@name+','
FETCH NEXT FROM C1 INTO @name
END
CLOSE C1
DEALLOCATE C1
RETURN @s
STRING_AGG
-------------
It is a predefine function used to concatenate column values
STRING_AGG(colname,separator)
CREATE OR ALTER
FUNCTION <NAME>(parameters) RETURNS TABLE
AS
RETURN (SELECT STATEMENT)
Example
-------------
Create a function that aceepts deptno and returns list of employees working for
that dept?
-------------------------------
CREATE OR ALTER
FUNCTION getEmpList(@d INT) RETURNS TABLE
AS
RETURN (SELECT * FROM EMP WHERE DEPTNO=@d)
Execution
----------------
Table valued functions are invoked in from clause
SELECT * FROM DBO.getEmpList(20)
Example 2
-----------
Create a function that returns top N employee list based on sal?
------------------
CREATE OR ALTER
FUNCTION getTopNEmpList(@n INT) RETURNS TABLE
AS
RETURN (SELECT * FROM
(SELECT empno,ename,sal,dense_rank() over (order by sal
desc) as rnk
FROM emp) AS E
WHERE rnk<=@n)
Execution
----------------
Select * from dbo.getTopNEmpList(3)
Functions
--------------
Must return a value
Always returns one value
Returns value using return statement
functions cannot contain dml statements
can be called from sql commands
created for calculation or fetch data from the table
sp_helptext
----------------
stored procedure used to see the procedure or function code
sp_helptext <proc-name>
TRIGGERS
-------------
trigger is also a named TSQL block like procedure but executed implicitly by sql
server whenever user submits DML commands
1) to control dmls
2) to enforce complex rules and validations
3) to audit day to day operations on tables
4) to manage replicas(duplicate copy)
5) to generate values for primary key columns
Syntax
------------
CREATE OR ALTER TRIGGER <NAME>
ON <TABNAME>
AFTER/INSTEAD OF INSERT, UODATE, DELETE
AS
STATEMENTS
AFTER trigger
-----------------
If trigger is after then sql server executes the trigger after executing dml
INSTEAD OF triggers
----------------
If trigger is instead of then sql server executes the trigger instead of executing
dml
Example 1
--------------
Create a trigger to not allow dmls on sunday on emp table
------------------------
CREATE OR ALTER TRIGGER T1
ON EMP
AFTER INSERT, UPDATE, DELETE
AS
IF DATENAME(DW,GETDATE())='SUNDAY'
BEGIN
ROLLBACK
RAISERROR('sunday not allowed',15,1)
END
Testing
-----------
UPDATE EMP SET SAL=SAL+1000 WHERE EMPNO=110