Professional Documents
Culture Documents
SQL Server
SQL Server
select sal from emp a where N = (select count(distinct sal) from emp b where
a.sal <= b.sal)
or
There are mainly two types of They can be declared in batch or stored
Temporary Tables-Local & Global procedure. Unlike Temporary Tables,
Temporary Tables. they cannot be dropped explicitly. Once
Local Temporary Table: These tables the batch execution is finished, the
are only available for the session that Table Variables are dropped
has created them. Once the session is automatically.
terminated, these tables are
automatically deleted. They can be also
be deleted explicitly.
Global Temporary Table: These tables
are available for all the sessions and
users. They are not deleted until the
last session using them is terminated.
Similar to local Temporary Table, a
user can delete them explicitly.
The Temporary Tables are stored in The Table Variables are stored in both
tempdb database of SQL server. the memory and the disk in the
Table Variable tempdb database.
The structure of Temporary Tables can The structure of Table Variables cannot
be created even after its creation. be changed once they are created.
Thus, we can use DDL statements like Thus, it means that DDL commands
ALTER, DROP and CREATE as shown in cannot be run in Table Variables.
the below-mentioned example. In the
example we have created a Temporary
Table named as Employee. In this we
will add an Address column and then
finally drop the table.
--Create Temporary Table
CREATE TABLE#Employee
(Id INT, Name VARCHAR(50))
GO
--Add Address Column
ALTER TABLE#Employee
ADD Address VARCHAR(400)
GO
--DROP Temporary Table
DROP TABLE#Employee
GO
Table Variable
They are not allowed in the user- The table variables can be used in
defined functions. user-defined functions.
Local and Global Temporary Tables Table Variables do not allow creation of
support creation of indexes on them in indexes on them.
order to increase the performance.
SQL performance tuning can be an incredibly difficult task. Even a minor change can
have a dramatic impact on performance. Here are the 10 most effective ways to
optimize your SQL queries.
Causes SQL Server to stop processing the query after the specified number of rows are
returned.
-- Syntax
To set this option off so that all rows are returned, specify SET ROWCOUNT 0.
Example:
set ROWCOUNT 5
output:
Difference between stored procedure and function
1) Procedure can return zero or n values whereas function can return one value
which is mandatory.
2) Procedures can have input, output parameters for it whereas functions can
have only input parameters.
3) Procedure allows select as well as DML statement in it whereas function
allows only select statement in it.
4) Functions can be called from procedure whereas procedures cannot be called
from function.
5) Exception can be handled by try-catch block in a procedure whereas try-catch
block cannot be used in a function.
6) We can go for transaction management in procedure whereas we can't go in
function.
7) Procedures cannot be utilized in a select statement whereas function can be
embedded in a select statement.
@@IDENTITY
t will return last or newly inserted record id of any table in current session but
it’s not limited to current scope. In current session if any trigger or functions
inserted record in any table that it will return that latest inserted record id
regardless of table. We need to use this property whenever we don’t have any
other functions or triggers that run automatically.
Syntax:
SELECT @@IDENTITY
SCOPE_IDENTITY()
This property will return last or newly inserted record id of table in current
session or connection and it’s limited to current scope that means it will return id
of newly inserted record in current session / connection stored procedure or
query executed by you in current scope even we have any other functions or
triggers that run automatically. Its better we can go with property whenever we
need to get last or newly inserted record id in table.
The scope_identity() function returns the last identity created in the same
session and the same scope
Syntax
SELECT SCOPE_IDENTITY()
IDENT_CURRENT
This property will return last or newly inserted record id of specified table. It’s
not limited to any session or scope it’s limited to mentioned table so it will return
last inserted record id of specified table.
Syntax
SELECT IDENT_CURRENT(table_name)
Select
BusinessEntityID,[FirstName], [LastName],[JobTitle]
from
HumanResources.vEmployee
Order By BusinessEntityID
OFFSET 10 ROWS
FETCH NEXT 10 ROWS ONLY
If we use offset with order by clause, the query excludes the number of records
we mentioned in OFFSET n Rows. In the above example, we used OFFSET 10
ROWS so, SQL will exclude first 10 records from the result and display the rest
of all records in the defined order.
If we use offset with fetch next, we can define how many records we need to
exclude. Also we can define that after exclusion how many records we need to
pick up. In the above example, SQL excludes first 10 records and will pick up 10
records afterwards.
In other words, we can say that whenever we need to do paging we need 2
things. 1st, the page no. and 2nd the no. of records in each page.
Here OFFSET is used for page number and FETCH NEXT is the number of
records in each page.
In this example, creating a stored procedure with both ORDER BY OFFSET and
FETCH NEXT keyword to enhancement the paging in SQL Server 2012.
CREATE PROCEDURE TestPaging
(
@PageNumber INT,
@PageSize INT
)
AS
DECLARE @OffsetCount INT
SET @OffsetCount = (@PageNumber-1)*@PageSize
SELECT *
FROM [UserDetail]
ORDER BY [User_Id]
OFFSET @OffsetCount ROWS
FETCH NEXT @PageSize ROWS ONLY
select * from (
select ad.dealer_hierarchy_id,ad.dealer_id,ad.parent_dealer_hierarchy_id,
ROW_NUMBER() over(partition by ad.parent_dealer_hierarchy_id order by ad.dealer_id
desc) as rnk
--ad1.dealer_hierarchy_id,ad1.dealer_id,ad1.parent_dealer_hierarchy_id
from #temp ad,#temp ad1
where
ad.parent_dealer_hierarchy_id=ad1.dealer_hierarchy_id
) as t
where
rnk=1
What is Trigger ?
A trigger is a special kind of stored procedure that automatically executes when an event
occurs in the database server. DML triggers execute when a user tries to modify data
through a data manipulation language (DML) event. DML events are INSERT, UPDATE, or
DELETE statements on a table or view.
Types Of Triggers
There are three action query types that you use in SQL which are INSERT, UPDATE and DELETE.
So, there are three types of triggers and hybrids that come from mixing and matching the events
and timings that fire them. Basically, triggers are classified into two main types:
Let’s create After triggers. First of all, let’s create a table and insert some sample data. Then, on
this table, I will be attaching several triggers.
I will be creating an AFTER INSERT TRIGGER which will insert the rows inserted into the table into
another audit table. The main purpose of this audit table is to record the changes in the main
table. This can be thought of as a generic audit trigger.
This trigger is fired after an INSERT on the table. Let’s create the trigger as:
The CREATE TRIGGER statement is used to create the trigger. THE ON clause specifies the table
name on which the trigger is to be attached. The FOR INSERT specifies that this is an AFTER
INSERT trigger. In place of FOR INSERT, AFTER INSERT can be used. Both of them mean the
same.
In the trigger body, table named inserted has been used. This table is a logical table and
contains the row that has been inserted. I have selected the fields from the logical inserted table
from the row that has been inserted into different variables, and finally inserted those values into
the Audit table.
To see the newly created trigger in action, lets insert a row into the main table as:
Now, a record has been inserted into the Employee_Test table. The AFTER INSERT trigger
attached to this table has inserted the record into the Employee_Test_Audit as:
6 Chris 1500.00 Inserted Record -- After Insert Trigger. 2008-04-26 12:00:55.700
This trigger is fired after an update on the table. Let’s create the trigger as:
if update(Emp_Name)
set @audit_action='Updated Record -- After Update Trigger.';
if update(Emp_Sal)
set @audit_action='Updated Record -- After Update Trigger.';
insert into
Employee_Test_Audit(Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_Timestamp)
values(@empid,@empname,@empsal,@audit_action,getdate());
This trigger is fired after a delete on the table. Let’s create the trigger as:
In this trigger, the deleted record’s data is picked from the logical deleted table and inserted
into the audit table. Let’s fire a delete on the main table. A record has been inserted into the
audit table as:
6 Chris 1550.00 Deleted -- After Delete Trigger. 2008-04-26 12:52:13.867
All the triggers can be enabled/disabled on the table using the statement
This disables the After Delete Trigger named trgAfterDelete on the specified table.
These can be used as an interceptor for anything that anyone tried to do on our table or view. If
you define an Instead Of trigger on a table for the Delete operation, they try to delete rows, and
they will not actually get deleted (unless you issue another delete instruction from within the
trigger)
BEGIN
if(@emp_sal>1200)
begin
RAISERROR('Cannot delete where salary > 1200',16,1);
ROLLBACK;
end
else
begin
delete from Employee_Test where Emp_ID=@emp_id;
COMMIT;
insert into
Employee_Test_Audit(Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_Timestamp)
values(@emp_id,@emp_name,@emp_sal,'Deleted -- Instead Of Delete
Trigger.',getdate());
PRINT 'Record Deleted -- Instead Of Delete Trigger.'
end
END
GO
This trigger will prevent the deletion of records from the table where Emp_Sal > 1200. If such a
record is deleted, the Instead Of Trigger will rollback the transaction, otherwise the transaction
will be committed. Now, let’s try to delete a record with the Emp_Sal >1200 as:
In a similar way, you can code Instead of Insert and Instead Of Update triggers on your tables.
Transactions:
A transaction is a unit of work that is performed against a database
Properties of Transactions
Transactions have the following four standard properties, usually referred to by the
acronym ACID.
Atomicity − ensures that all operations within the work unit are completed
successfully. Otherwise, the transaction is aborted at the point of failure and
all the previous operations are rolled back to their former state.
Consistency − ensures that the database properly changes states upon a
successfully committed transaction.
Isolation − enables transactions to operate independently of and transparent
to each other.
Durability − ensures that the result or effect of a committed transaction
persists in case of a system failure.
Example1:
1. -- If an error occurred, roll back
2. if @maxerr <> 0
3. begin
4. ROLLBACK
5. print 'Transaction rolled back'
6. end
7. else
8. begin
9. COMMIT
10. print 'Transaction committed'
11. end