MSC Is
MSC Is
SQL SERVER
(TSQL,PL/SQL)
NAME : ----------------------------------------------------------
-----------------------------------------------------------
-----------------------------------------------------------
Mr. V.G.Reddy
International Corporate Trainer and
Project Manager
Mobile No: 9885464910
Email id: [email protected]
1
2
LEGEND OF VGREDDY
Mr. V.G.Reddy
International Corporate Trainer and
Project Manager
Mobile No: 9885464910
Email id: [email protected]
Vgreddy was native of small hamlet village within 50 kms radius of hyderabad.This village is
under the border of ranga reddy dist(east) and nalgonda district(West). Vgreddy was unable to
bear financial problems young age life doing in cultivation in village and studying in government
schools. Vgreddy didn't live with parents from childhood and he was faced lot of problems
economically,educationally.Vgreddy himself prepares food and studies in Government Schools.
Vgreddy living as tenant from schooling to nearly 26 years. From thereafter Vgreddy was fully
settled in hyderabad.Vgreddy was working since 1994-95 as faculty he used to teach home
tutions from school level to engineering subjects in young age life.vgreddy having good
experience in IT industry on client/server,internet,ERP Technologies and Engineering
Subjects.Vgreddy is a teacher,trainer,consultant in field of Information Technology and Bio
Technology.Vgreddy like honest and understanding people and a man of vision, truth and
hardworking. Vgreddy full name is Venkat G. Reddy. Vgreddy having good international
exposure with various countries Clients and Universities like USA, MIDDLE
EAST,AUSTRALIA,UK,IRELAND,CANADA,EUROPE,SOUTH AMERICA AND SOUTH AFRICA.Lakhs
of students are studied with Vgreddy. If you have any doubts you can mail to
[email protected]
Moulding the child right way into the right direction - Vgreddy
2
3
SQL SERVER
CREATING THE DATABASE TABLES
STORING INFORMATION INTO THE DATABASE TABLES
MANIPULATION MEANS CHANGES CAN BE DONE IN THE DATABASE TABLES (OR ) CHANGING
THE EXISTING COLUMN VALUES
EXTRACTING/RETRIEVAL OF THE INFORMATION FROM THE DATABASE TABLES
CLIENT/SERVER APPLICATIONS
SQL Server 2012, like its predecessors, is more than a database engine. It is a collection of
components you can implement either separately or as a group to form a scalable, cloud-ready
information platform. In broad terms, this cloud-ready information platform consists of
twocategories:those that help you manage data and those that help you deliver business
intelligence (BI).Accordingly, we divided this book into two parts to focus on the new
capabilities for each of these areas.
3
4
database
APPLICATIONS OF DATABASE
5) DATA SECURITY MEANS THERE ARE ONE THOUSAND ROWS AND TWO
HUNDRED COLUMNS ARE THERE IF DELETED PARTICULAR COLUMN VALUE OTHER
COLUMNS CAN'T TO BE DISTURBED. IF DELETED PARTICULAR COLUMN ROW
OTHER ROWS CAN'T TO BE DISTURBED. AND OTHER SECURITY IS FEATURE FOR
OUR CLIENTS WE HAVE TO CREATE OUR OWN USER NAME AND PASSWORD THAT
MEANS AUTHENTICATION FEATURE IS AVAILABLE FOR OUR SQL SERVER
DATABASE
4
5
1:MANY RELATIONSHIP
MANY:MANY
A PARENT UNIT MAY HAVE MANY CHILD UNITS , CHILD UNIT CAN ALSO HAVE
DIFFERENT PRODUCTS FROM THE DIFFERENT PARENT UNITS.
EXAMPLE:- REYNOLDS
5
6
High Level Database Programming Language. The Relational Model Principles Were
Laid Down By Dr. E.F.Codd In June 1970, He Was Published A Paper Called "A
Relational Model Of Data For Large Shared Database" . He Was Proposed 12 Rules.
Dr. Ef Codd Says If You Satisfy Atleast 6/12 Then You Can Say Your Product Name
Is Called Rdbms Product.
ORACLE,
SQL SERVER
INFORMIX
INGRES
MY SQL
DB2
MS ACCESS
1:1
1:1
RDBMS
6
7
FEATURES OF RDBMS
1) THE ABILITY TO CREATE MULTIPLE RELATIONS AND STORE DATA INTO THEM.
2) IT IS AN INTERACTIVE QUERY LANGUAGE
3) RETRIEVAL OF INFORMATION STORED IN MORE THAN ONE TABLE
REFINEMENT OF ER DIAGRAM
7
8
NORMALIZATION
1) REFINEMENT OF ER DIAGRAM
2) NORMALIZATION
i) FIRST NORMAL FORM (1NF)
ii) SECOND NORMAL FORM (2NF)
iii) THIRD NORMAL FORM (3NF)
i) FIRST NORMAL FORM (1NF):- YOU HAVE TO REMOVE THE REPEATING FIELDS OF
A TABLE WHICH IS UNNECESSARY DATA.
ii) SECOND NORMAL FORM (2NF):- YOU HAVE TO IDENTIFY THE TABLENAMES AND
FIELDS. FIELD SHOULD BE ACCORDING TO THE TABLE THEN YOU HAVE TO
SPECIFY NAME OF THE TABLE.
iii) THIRD NORMAL FORM (3NF):- YOU HAVE TO IDENTIFY THE KEYS, FIELDS OF A
TABLE WHICH IS MASTER TABLE AND CHILD TABLE. PRIMARY KEY COLUMN TABLE
IS CALLED MASTER TABLE. FOREIGN KEY COLUMN TABLE IS CALLED CHILD TABLE.
CHILD TABLE COLUMN VALUE IS DEPENDENT ON THE MASTER TABLE.
ISO
8
9
FEATURES OF TSQL
UNIFIED LANGUAGE
CREATE
9
10
SYNTAX:-
(<COLUMNNAME> <DATATYPE><SIZE>,
<COLUMNNAME> <DATATYPE><SIZE>,
-------------------------------------- )
SP_HELP DEPT
10
11
11
12
system.
DEPT
ALTER
SYNTAX:-
EXAMPLE:-
12
13
SYNTAX
SYNTAX
SYNTAX:-
SP_RENAME 'STUDENT.SNO','STUDENTID'
DROP
SYNTAX:-
13
14
THERE ARE TWO TYPES OF INSERT ROWS INTO THE DATABASE TABLE
SYNTAX:-
EXAMPLE:-
SYNTAX:-
EXAMPLE:-
SYNTAX:-
EXAMPLE:-
OPERATORS
1) ARITHMETIC OPERATORS
14
15
+ =5+4=9
- =5-4=1
* =5*4=20
/ =5/2=2.5
% =28%4=0
>
>=
<
<=
<> OR !=
3) LOGICAL OPERATORS
AND
OR
NOT
4) SPECIAL OPERATORS
15
16
(OR)
16
17
17
18
DISPLAY THE EMPLOYEE NAME OF EMPLOYEE TABLE WHOSE ENAME ENDING WITH
S
TRUNCATE IS USED DELETING ALL THE ROWS FROM THE DATABASE TABLE AT A
TIME. WHERE CLAUSE IS NOT USED.
SYNTAX:-
EXAMPLE:-
18
19
DISPLAY THE DEPTNO, TOTAL SALARY FROM EMPLOYEE TABLE DEPARTMENT WISE
19
20
DISPLAY THE JOB, TOTAL AVERAGE MAXM MINM SALARY NO OF ROWS FROM
EMPLOYEE TABLE JOB WISE
DISPLAY THE JOB, TOTAL AVERAGE MAXM MINM SALARY NO OF ROWS FROM
EMPLOYEE TABLE JOB WISE
20
21
65 - 90 A - Z UPPERCASE LETTERS
SELECT ASCII('A')
SELECT ASCII('b')
SELECT CHAR(66)
SELECT CHAR(98)
SELECT LOWER('HELLOWORLD')
SELECT UPPER('helloworld')
21
22
REPLACE(<STRING/COLUMNNAME>,'SEARCHINGSTRING','REPLACINGSTRING')
YY YEAR
MM MONTH
DD DAY
22
23
5) GENERAL FUNCTIONS
DISPLAY THE EMPNO,SAL ,SALARY AS PER MONTH AND SALARY PER YEAR FOR ALL
EMPLOYEES
23
24
JOINS
ARE USED TO QUERY DATA FROM MORE THAN ONE TABLE.
THE RELATIONSHIP BETWEEN MASTER TABLE AND CHILD TABLE IS CALLED EQUI
JOINS. MASTER TABLE COLUMN VALUES MUST MATCH CORRESPONDING COLUMN
VALUES IN THE CHILD TABLE AND BOTH THE TABLES MATCHING COLUMN VALUES.
SYNTAX:-
SELECT DEPT.DEPTNO,DEPT.DNAME,EMP.EMPNO,EMP.JOB,EMP.SAL,EMP.DEPTNO
FROM DEPT,EMP WHERE DEPT.DEPTNO=EMP.DEPTNO;
SELECT DEPT.DEPTNO,DEPT.DNAME,EMP.EMPNO,EMP.JOB,EMP.SAL,EMP.DEPTNO
FROM DEPT,EMP
2) OUTER JOINS ARE USED TO DISPLAY ROWS WHICH DO NOT MATCH FROM
ONE TABLE TO OTHER TABLE.
i) LEFT OUTER JOIN:- MASTER TABLE SIDE ROWS ARE EXISTING WHICH DO
NOT MATCH CORRESPONDING ROWS OR COLUMN VALUES IN THE CHILD TABLE
AND BOTH THE TABLES MATCHING COLUMN VALUES.
24
25
SELECT DEPT.DEPTNO,DEPT.DNAME,EMP.EMPNO,EMP.JOB,EMP.SAL,EMP.DEPTNO
FROM DEPT LEFT OUTER JOIN EMP ON DEPT.DEPTNO=EMP.DEPTNO ORDER BY
DEPT.DEPTNO
ii) RIGHT OUTER JOIN:- CHILD TABLE SIDE ROWS ARE EXISTING WHICH DO
NOT MATCH CORRESPONDING ROWS OR COLUMN VALUES IN THE MASTER TABLE
AND BOTH THE TABLES MATCHING COLUMN VALUES.
SELECT DEPT.DEPTNO,DEPT.DNAME,EMP.EMPNO,EMP.JOB,EMP.SAL,EMP.DEPTNO
FROM DEPT RIGHT OUTER JOIN EMP
iii) FULL OUTER JOIN:- BOTH THE TABLES MATCHING ROWS OR COLUMN
VALUES AND BOTH THE WHICH ARE INOT MATCHING COLUMN VALUES. IT IS A
COMBINATION OF EQUI JOIN ,LEFT OUTER AND RIGHT OUTER JOIN.
SELECT DEPT.DEPTNO,DEPT.DNAME,EMP.EMPNO,EMP.JOB,EMP.SAL,EMP.DEPTNO
FROM DEPT FULL OUTER JOIN EMP
WHERE MANAGER.EMPNO=WORKER.MGR
4) CROSS JOINS:- join condition is not used. all the rows in the first table
are joined to all the rows in the second table.
25
26
i) UNION ALL :- THE ROWS OF THE FIRST QUERY + THE ROWS OF THE SECOND
QUERY
ii) UNION:- THE ROWS OF THE FIRST QUERY + THE ROWS OF THE SECOND QUERY
eliminates or deletes the repeating column values
UNION
SUB QUERIES
QUERY WITHIN A QUERY IS CALLED SUB QUERY
26
27
i) single row subquery :- queries that executes only one row from the in.ner
select statement is called single row sub query. single row comparison operators
are used in single row sub query.
ii) multiple row subquery :- queries that executes more than one row from the
inner select statement is called multiple row sub query. multiple row comparison
operators are used in multiple row sub query.
i) single row comparison operator < <= > >= = != (or) <>
SELECT * FROM EMP WHERE SAL>(SELECT SAL FROM EMP WHERE EMPNO=7566)
ii) DISPLAY THE EMPLOYEE DETAILS OF EMPLOYEE TABLE WHOSE SALARY IS MORE
THAN all average salaries of employee table DEPARTMENTWISE
iii) DISPLAY THE EMPLOYEE DETAILS OF EMPLOYEE TABLE WHOSE MAX SALARIES
OF EMPLOYEE table DEPARTMENTWISE
SELECT * FROM EMP WHERE SAL IN (SELECT MAX(SAL) FROM EMP GROUP BY
DEPTNO)
iv) DISPLAY THE EMPLOYEE DETAILS OF EMPLOYEE TABLE WHOSE SALARY IS LESS
THAN ANY HIGHEST SALARY OF THE CLERK
SELECT * FROM EMP WHERE SAL<ANY (SELECT SAL FROM EMP WHERE
JOB='CLERK')
27
28
SELECT * FROM EMP WHERE SAL>ANY (SELECT SAL FROM EMP WHERE
JOB='CLERK')
CORELATED SUB QUERY:- PARENT QUERY VALUES MUST CHECK IN THE CHILD
QUERY THEN IT EXECUTES THE PARENT QUERY
DISPLAY THE TOP 2 EARNERS (OR) 2 HIGHEST SALARIES FROM EMPLOYEE TABLE
VIEWS
1) SIMPLEX VIEWS
2) COMPLEX VIEWS
SYNTAX:-
EXAMPLE:-
28
29
SELECT * FROM V1
SELECT * FROM V1
DROP VIEW V1
SYNTAX:-
EXAMPLE:-
SELECT * FROM V2
SELECT * FROM V1
DROP VIEW V1
SYNTAX:-
EXAMPLE:-
29
30
SYNTAX:-
INDEXES
TYPES OF INDEXES
i) CLUSTERED INDEX:- ONLY ONE CLUSTERED INDEX IS ADDED FOR A TABLE. THE
ORDER OF VALUES IN A TABLE. ORDER OF VALUES IN INDEX IS ALSO SAME WHEN
CLUSTERED INDEX IS CREATED ON TABLE . DATA IS ARRANGED IN ASCENDING
SYNTAX:-
EXAMPLE:-
30
31
EXAMPLE
SYNTAX
TCL(ROLLBACK,COMMIT)
BEGIN TRAN
ROLLBACK TRAN
31
32
SET IMPLICIT_TRANSACTIONS ON
COMMIT
SAVE POINTS
SAVE POINTS ARE LIKE PAPER MARKS USED TO MARK THE TRANSACTIONS.
YOU CAN CREATE SAVE POINTS FOR EACH TRANSACTION LATER YOU CAN
ROLLBACK ONLY ONE PARTICULAR TRASANCTION (OR) ALL THE TRASACTIONS AT
A TIME.
BEGIN TRAN
SAVE TRAN A
BEGIN TRAN
UPDATE EMP SET SAL=1814 WHERE EMPNO=7499
SAVE TRAN B
BEGIN TRAN
UPDATE EMP SET SAL=1564 WHERE EMPNO=7521
SAVE TRAN C
ROLLBACK TRAN B
SELECT * FROM EMP
DCL (GRANT,REVOKE)
32
33
CONNECT VENKAT/BHARGAV
REVOKE ALL ON EMP FROM VENKAT
REVOKE SELECT,INSERT ON EMP FROM VENKAT
SYNTAX
DROP USER <USERNAME>
EXAMPLE:-
DROP USER VENKAT
PLSQL
the sequence of instructions are used to produce specific desired result is known as
procedural language
in non procedural language one single statement that must be terminated with
semicolon.
example:- sql
Variables are declared in the body of a batch or procedure with the DECLARE
statement and are assigned values by using either a SET or SELECT statement.
Cursor variables can be declared with this statement and used with other cursor-
related statements. After declaration, all variables are initialized as NULL, unless a
value is provided as part of the declaration.
@ local_variable
Is the name of a variable. Variable names must begin with an at (@) sign
set @a=10
set @b=5
33
34
set @c=@a+@b
set @p=10000
set @n=15
set @r=7.5
for applying the conditions or checking the values at the time of inserting from the
keyboard
syntax:-
if <condition is true>
<statement1>
else
34
35
<statement2>
example:-
declare @a int
select @a=COUNT(*) from emp
if (@a > 6)
print 'TABLE HAVA RECORDS ' + CONVERT(VARCHAR, @a)
else
PRINT 'NO RECORDS IN THE TABLE '
WHILE STATEMENT
SYNTAX
INITIALIZATION
WHILE(<CONDITION>)
BEGIN
<STATEMENTS>
-----------------
END
DECLARE @n int
set @n=1
while(@n<=10)
begin
print @n
set @n=@n+1
end
35
36
DECLARE @n int
set @n=1
while(@n<=10)
begin
if(@n%2=0)
print @n
set @n=@n+1
end
CURSORS
Cursor Is A Database Used To Process The Set Of Records Individually, One Record
At A Time.
TYPES OF CURSORS
1) STATIC CURSORs
2) DYNAMIC CURSOR
3) FORWARD ONLY
4) KEY SET CURSORS
1) DECLARE CURSOR
2) OPEN CURSOR
3) FETCH RECORD FROM THE CURSOR
4) CLOSE CURSOR
5) DEALLOCATE CURSOR
KEYWORDS
ii) NEXT - > used to fetch the record next to the previously fetched record
iii) LAST - > USED TO FETCH THE PREVIOUS RECORD FROM THE RESULTSET
iv) PRIOR - > USED TO FETCH THE PREVIOUS RECORD FROM CURRENT POSITION
36
37
Vi) RELATIVE n -> if n is positive, it fetches 10th record from the previously fetched
record. if n is negative is fetches nth record before the previously fetched record. if
n=0, same record will be fetched
37
38
PRINT @NAME
CLOSE dept6
DEALLOCATE <CURSORNAME>
DEALLOCATE DEPT6
OPEN DEPT7
PRINT @DNO
PRINT @NAME
PRINT @DNO
PRINT @NAME
CLOSE dept7
38
39
ARE USED TO PERFORM SOME TASK. PROCEDURE DO NOT HAVE RETURN CLAUSE.
A STORED PROCEDURE IS AN ALREADY WRITTEN SQL STATEMENT THAT IS SAVED
IN THE DATABASE.
THE PROCEDURES CREATED BY THE USER ARE CALLED USER DEFINED STORED
PROCEDURES
SYNTAX:-
<STATEMENTS>
AS
BEGIN
-------------------
END
EXAMPLE:-
exec addnum
39
40
set @c=@a+@b
print 'THE SUM IS ' + CONVERT(VARCHAR,@c)
end
SYNTAX:-
RETURN TABLE AS
------------------
BEGIN
<FUNCTION BODY>
-------------------
END
40
41
Stored procedures are a powerful part of SQL Server. They can assist programmers and administrators
greatly in working with the database configuration and its data.
A stored procedure is a precompiled group of Transact-SQL statements, and is saved to the database (under
the "Stored Procedures" node). Programmers and administrators can execute stored procedures either from
the SQL Server Management Studio or from within an application as required.
Transact-SQL, which is based on SQL (Structured Query Language), is the programming language used to
interface between applications and their databases. Transact-SQL is a relatively easy language to learn and I
highly recommend becoming familiar with it.
Modular programming You can write a stored procedure once, then call it from
multiple places in your application.
41
42
Creates a user-defined function in SQL Server 2012. A user-defined function is a Transact-SQL or common language
runtime (CLR) routine that accepts parameters, performs an action, such as a complex calculation, and returns the
result of that action as a value. The return value can either be a scalar (single) value or a table. Use this statement to
create a reusable routine that can be used in these ways:
In Transact-SQL statements such as SELECT
In applications calling the function
In the definition of another user-defined function
To parameterize a view or improve the functionality of an indexed view
To define a column in a table
To define a CHECK constraint on a column
To replace a stored procedure
SELECT * FROM dbo.MyTable WHERE col1 = dbo.MyFunction(col2)
Where MyFunction is declared as:
CREATE FUNCTION MyFunction (@someValue INTEGER) RETURNS INTEGER
AS
BEGIN
DECLARE @retval INTEGER
SELECT localValue
FROM dbo.localToNationalMapTable
WHERE nationalValue = @someValue
RETURN @retval
END
42
43
SQL Server user-defined functions and stored procedures offer similar functionality. Both allow you to create bundles of SQL
statements that are stored on the server for future use. This offers you a tremendous efficiency benefit, as you can save
programming time by:
Reusing code from one program to another, cutting down on program development time
Hiding the SQL details, allowing database developers to worry about SQL and application developers to deal only in higher-
level languages
Centralize maintenance, allowing you to make business logic changes in a single place that automatically affect all dependent
applications
At first glance, functions and stored procedures seem identical. However, there are several subtle, yet important differences
between the two:
Stored procedures are called independently, using the EXEC command, while functions are called from within another SQL
statement.
Stored procedure allow you to enhance application security by granting users and applications permission to use stored
procedures, rather than permission to access the underlying tables. Stored procedures provide the ability to restrict user
actions at a much more granular level than standard SQL Server permissions. For example, if you have an inventory table that
cashiers must update each time an item is sold (to decrement the inventory for that item by 1 unit), you can grant cashiers
permission to use a decrement_item stored procedure, rather than allowing them to make arbitrary changes to the inventory
table.
Functions must always return a value (either a scalar value or a table). Stored procedures may return a scalar value, a table
value or nothing at all.
Overall, stored procedures are one of the greatest treasures available to SQL Server developers. I use them heavily in my
databases and encourage you to do the same. The efficiency and security benefits you’ll reap are well worth the upfront
investment in time.
A Parameterized Function
To create a function that takes a parameter, specify a name and the type of value of the
parameter(s) in its parentheses. Here is an example:
43
44
When a function takes a parameter, in the body of the function, you can use the
parameter as if you knew its value, as long as you respect the type of that value. Here is
an example:
Once again, in the body of the function, you can use the parameters as if you already
knew their value. You can also declare local variables and involve them with parameters
as you see fit. Here is an example:
You can also pass the names of already declared and initialized variables. Here is an
example that calls the above function:
QL Server’s own list of functions is limited as far as what is available for database
developers to use in their applications. Starting with SQL Server 2000, database developers
were given the ability to create their own routines that accept parameters, perform custom
actions and return results.
SQL Server's own list of available functions is not enough for database developers to use in
their applications, especially when it comes to business logic, complex algorithmic
calculations and custom actions. In this light, beginning with SQL 2000, SQL Server allows
44
45
database developers to create their own routines, which can accept parameters, perform
custom actions and return results. These routines are called user-defined functions.
Initially SQL Server only allowed user-defined functions in T-SQL. Following CLR integration
in the SQL Server engine, the later versions of SQL Server (including SQL Server 2008 R2)
allow users to create user-defined functions (called UDFs from here on) in a managed code,
in addition to T-SQL.
With UDFs, database developers can express their business logic in a form they know best
and get their business logic executing in the SQL engine from where it can be called in their
SQL queries.
Extend programming richness via user code - Your database can now do more
than only process data. With UDFs, databases can now also validate business logic
and do custom actions.
Faster performance than T-SQL functions for computational logic - T-SQL
functions are great at processing data. When it comes to business logic and custom
algorithms, UDFs can do a much better job. UDFs work akin to stored procedures.
Optimizes network traffic - UDFs allow data manipulation such that you don't
need a lot of talking to the database and you can optimize your results based on
your business logic within the database. This reduces network bandwidth utilization.
Reusable code, which can be called akin to stored procedures with business logic.
When called in SQL queries, UDFs are only executed in a single thread. They follow serial
execution plan. Hence, if the business logic inside UDFs would work better in a multi-
threaded environment, it would be better to not implement it as a user-defined function,
since it would lead to over-all performance degradation.
UDFs cannot change database state so there might be usage constraints if you are
attempting to change the database information inside your business logic.
45
46
1. Header
2. Function body
The header contains the function name, input parameter info (name and type), and return
parameter info (name and type). The function body contains the logic. It contains one or
more T-SQL statements that contain the logic and it can also contain a reference to a .NET
assembly (in case of a CLR UDF).
Based on the return type, UDFs can be classified as scalar functions and table-value
functions.
Scalar Functions
There is no function body in the case of an inline scalar function, and the scalar value (the
return value) is the result of a single statement.
Execution:
select dbo.EmployeeContactID(1)
46
47
UPDATE @Result
SET name = 'N'
RETURN
END
Exectution :
Select * from dbo.multi_test(1)
Difference between Stored procedures and User defined functions:
i)A stored procedure is pre compiled while a User defined function is compiled and
executed at runtime.
ii)A Stored procedure is more flexible than user defined function like you can write
complex logic (for example exceptional handling using try catch block is possible in
stored procedures which is not possible in user defined functions)
iii) A stored procedure can call another stored procedure or user defined function inside
it but a user defined function can’t call stored procedure inside it.
iv)A stored procedure can return non deterministic values but a user defined function
can’t return a non deterministic values like Get Date () function.
v) A user defined functions does not support DML operations like insertion, deletion and
update on the base table but it is possible via stored procedure.
vi) A user defined function is easier to execute and can be used inside selection and
even for joins but stored procedure can’t be used inside selection queries and it can’t be
used to join with other tables.
47
48
TRIGGERS
Are Special Types Of Stored Procedures That Are Defined To Execute Automatically In Place Of
Or After Data Modifications. They Can Be Executed Automatically On The Insert, Delete And
Update Triggering Actions.
There Are Two Different Types Of Triggers In Sql Server. They Are Dml Triggers And Ddl Triggers
48
49
Under Dml Triggers We Have Two Types They Are Instead Of Triggers And After Triggers.
These Triggers Differ From Each Other In Terms Of Their Purpose And When They Are Fixed.
Trigger Is One Type Of Stored Procedure, Executed Implicitly When User Performs A Dml Or Ddl
Operation On The Table.
It Will Not Accept Parameters. It Is Permanently Stored In Database.
TYPES OF TRIGGERS
SYNTAX:-
BEGIN
<STATEMENTS>
END
INSERT TRIGGER:- This Trigger Fires When User Performs Insert Operation On
The Table. When User Insert A Record Into The Table The Temporary Table Called
Inserted Is Created In The Temporary Memory.
EXAMPLE:-
SYNTAX:-
49
50
<STATEMENTS>
END
DDL TRIGGERS
SYNTAX:-
EXAMPLE:-
50
51
1. Which TCP/IP port does SQL Server run on? How can it be changed?
SQL Server runs on port 1433. It can be changed from the Network Utility TCP/IP properties.
1. A clustered index is a special type of index that reorders the way records in the table are
physically stored. Therefore table can have only one clustered index. The leaf nodes of a
clustered index contain the data pages.
2. A non clustered index is a special type of index in which the logical order of the index
does not match the physical stored order of the rows on disk. The leaf node of a non
clustered index does not consist of the data pages. Instead, the leaf nodes contain index
rows.
1. No indexes
2. A clustered index
3. A clustered index and many nonclustered indexes
4. A nonclustered index
5. Many nonclustered indexes
51
52
In OLTP - online transaction processing systems relational database design use the discipline of
data modeling and generally follow the Codd rules of data normalization in order to ensure
absolute data integrity. Using these rules complex information is broken down into its most
simple structures (a table) where all of the individual atomic level elements relate to each other
and satisfy the normalization rules.
Both primary key and unique key enforces uniqueness of the column on which they are defined.
But by default primary key creates a clustered index on the column, where are unique creates a
nonclustered index by default. Another major difference is that, primary key doesn't allow
NULLs, but unique key allows one NULL only.
Delete command removes the rows from a table based on the condition that we provide with a
WHERE clause. Truncate will actually remove all the rows from a table and there will be no data
in the table after we run the truncate command.
1. TRUNCATE:
1. TRUNCATE is faster and uses fewer system and transaction log resources than
DELETE.
2. TRUNCATE removes the data by deallocating the data pages used to store the
table's data, and only the page deallocations are recorded in the transaction log.
3. TRUNCATE removes all rows from a table, but the table structure, its columns,
constraints, indexes and so on, remains. The counter used by an identity for new
rows is reset to the seed for the column.
4. You cannot use TRUNCATE TABLE on a table referenced by a FOREIGN KEY
constraint. Because TRUNCATE TABLE is not logged, it cannot activate a
trigger.
5. TRUNCATE cannot be rolled back.
6. TRUNCATE is DDL Command.
7. TRUNCATE Resets identity of the table
2. DELETE:
1. DELETE removes rows one at a time and records an entry in the transaction log
for each deleted row.
2. If you want to retain the identity counter, use DELETE instead. If you want to
remove table definition and its data, use the DROP TABLE statement.
3. DELETE Can be used with or without a WHERE clause
4. DELETE Activates Triggers.
5. DELETE can be rolled back.
6. DELETE is DML Command.
7. DELETE does not reset identity of the table.
52
53
This command is basically used when a large processing of data has occurred. If a large amount
of deletions any modification or Bulk Copy into the tables has occurred, it has to update the
indexes to take these changes into account. UPDATE_STATISTICS updates the indexes on
these tables accordingly.
They specify a search condition for a group or an aggregate. But the difference is that HAVING
can be used only with the SELECT statement. HAVING is typically used in a GROUP BY
clause. When GROUP BY is not used, HAVING behaves like a WHERE clause. Having Clause
is basically used only with the GROUP BY function in a query whereas WHERE Clause is
applied to each row before they are part of the GROUP BY function in a query.
1. Properties of Sub-Query
1. A sub-query must be enclosed in the parenthesis.
2. A sub-query must be put in the right hand of the comparison operator, and
3. A sub-query cannot contain an ORDER-BY clause.
4. A query can contain more than one sub-query.
2. Types of Sub-Query
1. Single-row sub-query, where the sub-query returns only one row.
2. Multiple-row sub-query, where the sub-query returns multiple rows,. and
3. Multiple column sub-query, where the sub-query returns multiple columns
SQL Profiler is a graphical tool that allows system administrators to monitor events in an
instance of Microsoft SQL Server. You can capture and save data about each event to a file or
SQL Server table to analyze later. For example, you can monitor a production environment to
see which stored procedures are hampering performances by executing too slowly.
Use SQL Profiler to monitor only the events in which you are interested. If traces are becoming
too large, you can filter them based on the information you want, so that only a subset of the
event data is collected. Monitoring too many events adds overhead to the server and the
monitoring process and can cause the trace file or trace table to grow very large, especially when
the monitoring process takes place over a long period of time.
12. What are the authentication modes in SQL Server? How can it be changed?
Windows mode and Mixed Mode - SQL and Windows. To change authentication mode in SQL
Server click Start, Programs, Microsoft SQL Server and click SQL Enterprise Manager to run
SQL Enterprise Manager from the Microsoft SQL Server program group. Select the server then
from the Tools menu select SQL Server Configuration Properties, and choose the Security page.
53
54
13. Which command using Query Analyzer will give you the version of SQL server and
operating system?
SQL Server agent plays an important role in the day-to-day tasks of a database administrator
(DBA). It is often overlooked as one of the main tools for SQL Server management. Its purpose
is to ease the implementation of tasks for the DBA, with its full- function scheduling engine,
which allows you to schedule your own jobs and scripts.
15. Can a stored procedure call itself or recursive stored procedure? How much level SP nesting
is possible?
Yes. Because Transact-SQL supports recursion, you can write stored procedures that call
themselves. Recursion can be defined as a method of problem solving wherein the solution is
arrived at by repetitively applying it to subsets of the problem. A common application of
recursive logic is to perform numeric computations that lend themselves to repetitive evaluation
by the same processing steps. Stored procedures are nested when one stored procedure calls
another or executes managed code by referencing a CLR routine, type, or aggregate. You can
nest stored procedures and managed code references up to 32 levels.
Log shipping is the process of automating the backup of database and transaction log files on a
production SQL server, and then restoring them onto a standby server. Enterprise Editions only
supports log shipping. In log shipping the transactional log file from one server is automatically
updated into the backup database on the other server. If one server fails, the other server will
have the same db and can be used this as the Disaster Recovery plan. The key feature of log
shipping is that it will automatically backup transaction logs throughout the day and
automatically restore them on the standby server at defined interval.
17. Name 3 ways to get an accurate count of the number of records in a table?
18. What does it mean to have QUOTED_IDENTIFIER ON? What are the implications of
having it OFF?
54
55
19. What is the difference between a Local and a Global temporary table?
1. A local temporary table exists only for the duration of a connection or, if defined inside
a compound statement, for the duration of the compound statement.
2. A global temporary table remains in the database permanently, but the rows exist only
within a given connection. When connection is closed, the data in the global temporary
table disappears. However, the table definition remains with the database for access when
database is opened next time.
20. What is the STUFF function and how does it differ from the REPLACE function?
STUFF function is used to overwrite existing characters. Using this syntax, STUFF
(string_expression, start, length, replacement_characters), string_expression is the string that will
have characters substituted, start is the starting position, length is the number of characters in the
string that are substituted, and replacement_characters are the new characters interjected into the
string. REPLACE function to replace existing characters of all occurrences. Using the syntax
REPLACE (string_expression, search_string, replacement_string), where every incidence of
search_string found in the string_expression will be replaced with replacement_string.
A PRIMARY KEY constraint is a unique identifier for a row within a database table. Every table
should have a primary key constraint to uniquely identify each row and only one primary key
constraint can be created for each table. The primary key constraints are used to enforce entity
integrity.
A UNIQUE constraint enforces the uniqueness of the values in a set of columns, so no duplicate
values are entered. The unique key constraints are used to enforce entity integrity as the primary
key constraints.
A FOREIGN KEY constraint prevents any actions that would destroy links between tables with
the corresponding data values. A foreign key in one table points to a primary key in another
table. Foreign keys prevent actions that would leave rows with foreign key values when there are
no primary keys with that value. The foreign key constraints are used to enforce referential
integrity.
A CHECK constraint is used to limit the values that can be placed in a column. The check
constraints are used to enforce domain integrity.
55
56
A NOT NULL constraint enforces that the column will not accept null values. The not null
constraints are used to enforce domain integrity, as the check constraints.
If @@Rowcount is checked after Error checking statement then it will have 0 as the value of
@@Recordcount as it would have been reset. And if @@Recordcount is checked before the
error-checking statement then @@Error would get reset. To get @@error and @@rowcount at
the same time do both in same statement and store them in local variable.
Scheduled tasks let user automate processes that run on regular or predictable cycles. User can
schedule administrative tasks, such as cube processing, to run during times of slow business
activity. User can also determine the order in which tasks run by creating job steps within a SQL
Server Agent job. E.g. back up database, Update Stats of Tables. Job steps give user control over
flow of execution. If one job fails, user can configure SQL Server Agent to continue to run the
remaining tasks or to stop execution.
1. Stored procedure can reduced network traffic and latency, boosting application
performance.
2. Stored procedure execution plans can be reused, staying cached in SQL Server's memory,
reducing server overhead.
3. Stored procedures help promote code reuse.
4. Stored procedures can encapsulate logic. You can change stored procedure code without
affecting clients.
5. Stored procedures provide better security to your data.
29. What is a table called, if it has neither Cluster nor Non-cluster Index? What is it used for?
Unindexed table or Heap. Microsoft Press Books and Book on Line (BOL) refers it as Heap. A
heap is a table that does not have a clustered index and, therefore, the pages are not linked by
pointers. The IAM pages are the only structures that link the pages in a table together. Unindexed
tables are good for fast storing of data. Many times it is better to drop all indexes from table and
then do bulk of inserts and to restore those indexes after that.
SQL Server can be linked to any server provided it has OLE-DB provider from Microsoft to
allow a link. E.g. Oracle has an OLE-DB provider for oracle that Microsoft provides to add it as
linked server to SQL Server group.
56
57
BulkCopy is a tool used to copy huge amount of data from tables and views. BCP does not copy
the structures same as source to destination. BULK INSERT command helps to import a data file
into a database table or view in a user-specified format.
32. How to implement one-to-one, one-to-many and many-to-many relationships while designing
tables?
One-to-One relationship can be implemented as a single table and rarely as two tables with
primary and foreign key relationships. One-to-Many relationships are implemented by splitting
the data into two tables with primary key and foreign key relationships. Many-to-Many
relationships are implemented using a junction table with the keys from both the tables forming
the composite primary key of the junction table.
33. What is an execution plan? When would you use it? How would you view the execution
plan?
An execution plan is basically a road map that graphically or textually shows the data retrieval
methods chosen by the SQL Server query optimizer for a stored procedure or ad- hoc query and
is a very useful tool for a developer to understand the performance characteristics of a query or
stored procedure since the plan is the one that SQL Server will place in its cache and use to
execute the stored procedure or query. From within Query Analyzer is an option called "Show
Execution Plan" (located on the Query drop-down menu). If this option is turned on it will
display query execution plan in separate window when query is ran again.
57
58
58
59
59
60
LIKE
PL/SQL
60