Temp Variables are also used for holding data temporarily just like a temp table. Temp Variables are created using a “DECLARE” statement and are assigned values using either a SET or SELECT command.
Declare @My_vari TABLE
(
IID int,
Name Nvarchar(50),
Salary Int ,
City_Name Nvarchar(50)
)
We can use all the same methods of insertion that are used for tables but we cannot use a “SELECT INTO” statement for Temp Variables.
Id | Name | Salary | Gender |
---|---|---|---|
1 | Ashish | 60000 | Male |
2 | Ashutosh | 70000 | Male |
3 | Shree | 90000 | Male |
4 | Swapnil | 50000 | Male |
Select * from tblEmployee where Salary > 50000 and Salary < 70000
To find all the employees, who has salary greater than 50000 and less than 70000, the query engine has to check each and every row in the table, resulting in a table scan, which can adversely affect the performance, especially if the table is large. Since there is no index, to help the query, the query engine performs an entire table scan.
Here, we are creating an index on Salary column in the employee table
CREATE Index IX_tblEmployee_Salary
ON tblEmployee (SALARY ASC)
The index stores salary of each employee, in the ascending order
Now, when the SQL server has to execute the same query, it has an index on the salary column to help this query. Salaries between the range of 5000 and 7000 are usually present at the bottom, since the salaries are arranged in an ascending order. SQL server picks up the row addresses from the index and directly fetch the records from the table, rather than scanning each row in the table.
A view is nothing more than a saved SQL query. A view can also be considered as a virtual table.
Create View vWEmployeesByDepartment
as
Select Id, Name, Salary, Gender, DeptName
from tblEmployee
join tblDepartment
on tblEmployee.DepartmentId = tblDepartment.DeptId
To select data from the view, SELECT statement can be used the way, we use it with a table.
SELECT * from vWEmployeesByDepartment
A SQL trigger is a database object which fires when an event occurs in a database. We can execute a SQL query that will "do something" in a database when a change occurs on a database table such as a record is inserted or updated or deleted. For example, a trigger can be set on a record insert in a database table.
if you want to increase the count of blogs in the Reports table when a new record is inserted in the Blogs table, we can create a trigger on the Blogs' table on INSERT and update the Reports table by increasing blog count to 1.
create trigger TrSamp
on emp
for
insert,update,delete
as
print'you can not insert,update and delete this table i'
rollback;