This is default featured slide 4 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured slide 1 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured slide 2 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured slide 4 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

Me And My Respected Teacher Mr Kamal Sheel Mishra

Mr. K.S. Mishra is HOD of Computer Science from SMS Varanasi where I have completed my MCA

Me And My Respected Teacher Mr Udayan Maiti

Mr. Udayan Maiti is a senior .Net Expert and has guided many professionals of multi national Companies(MNC)

Me And My Best Friend Mr Ravinder Goel

Mr. Ravinder Goel is a senior Software Engineer and now he is working Wipro Technology

Tuesday, 18 October 2016

What is Derived Tables & CTE in Sql Server and Compare with – views, tables variables, local and global temp tables

What is Derived Tables & CTE in Sql Server

Compare with – views, tables variables, local and global temp tables

--*********************************************************

create table Department
(
DeptId int primary key,
Deptname varchar(23)
)

create table Employee
(
Id int,
Name varchar(32),
Salary float,
Gender varchar(23),
DepartmentId int  foreign key references Department(DeptId) on delete cascade
)


insert into Department values(1,'IT')
insert into Department values(2,'HR')
insert into Department values(3,'PAYROLL')
insert into Department values(4,'ADMIN')

insert into Employee values(1,'Kiran',4500,'male',3)
insert into Employee values(2,'Sara',3400,'female',1)
insert into Employee values(3,'john',4000,'male',2)
insert into Employee values(4,'kenny',5200,'female',4)

SELECT * FROM Department
SELECT * FROM Employee

--*********************************************************


1. VIEWS:-  Views gets saved in the database, and can be available to other queries and stored procedures. However, if this view is only used at this one place, it can be easily eliminated using other options, like CTE,Derived tables, temp tables, table variables etc.
-- using View  ...................

create view VwCompareViewCount
as
select Deptname,deptId, COUNT(*) as TotalEmployee
from Employee
join Department
on Employee.DepartmentId=Department.DeptId
group by Deptname, DeptId

--****************
select * from VwCompareViewCount

--******************
select DeptId,Deptname,TotalEmployee from VwCompareViewCount
where TotalEmployee>=2

Result:

 
2. TEMP TABLES:-Temporary tables are stored in TempDB. Local temporary tables are visible only in the current session, and can be shared between nested stored procedure calls. Global temporary tables are visible to other sessions and are destroyed ,when the last connection referencing the table is closed.


---USING TEMP TABLES---

Select Deptname,DepartmentId, COUNT(*) as totalEmployee
into #TempEmployeeCount
from Employee em
join Department dp
on em.DepartmentId=dp.DeptId
group by Deptname,DepartmentId

--******************
select * from #TempEmployeeCount
--****************
select Deptname,totalEmployee
from #TempEmployeeCount
where totalEmployee>=2

-- drop temp table
Drop table #TempEmployeeCount

Result:


 3. TABLE VARIABLES:-
Note:-  Just like TempTables, A table variable is also created in TempDB. The scope of a table variable is the batch, stored procedure, or statement block in which it is declared.
They can be passed as parameters between procedures.

---using tables variables---

Declare @TableEmployeCount table
(
Deptname varchar(32),
DepartmentId int,
TotalEmployee int
)
insert @TableEmployeCount
select Deptname,DepartmentId, COUNT(*) as Totalemployee
from dbo.Employee em
join dbo.Department dp
on em.DepartmentId=dp.DeptId
group by Deptname,DepartmentId

select DepartmentId,Deptname,Totalemployee
from @TableEmployeCount
where Totalemployee>=2

Result:

Note-:if we execute then we select all both created @TableEmployeCount table and select query include to run this query but output is SAME



4. DERIVED  TABLES:- A derived table is a table expression that appears in the FROM clause of a query. You can apply derived tables when the use of column aliases is not possible because another clause is processed by the SQL translator before the alias name is known.

--USING DERIVED TABLES---

Select DepartmentId,Deptname,TotalEmployee
from
            (
                        select Deptname,DepartmentId, COUNT(*) as Totalemployee
                        from Employee em
                        join Department dp
                        on em.DepartmentId=dp.DeptId
                        group by Deptname,DepartmentId
            )
as EmployeeCount                               --(EmployeeCount is variable)
where Totalemployee>=2

Result


Note: if we execute then we select all both created EmployeeCount table and select query include to run this query but output is SAME

 Derived tables are available only in the context of the current query.

5. CTE  (Comman Table Expression):-  CTE is used as start WITH keyboard. We can called as temporary table

---Using CTE..................

With EmployeeCountCTE(Deptname,DepartmentId, TotalEmployee)
as
(
            select Deptname,DepartmentId, COUNT(*) as TotalEmployee
            from Employee em
            join Department dp
            on em.DepartmentId=dp.DeptId
            group by Deptname,DepartmentId
)
select DepartmentId, Deptname, TotalEmployee
from   EmployeeCountCTE
where Totalemployee>=2


--we executed select all data query output as same

Result




Note:- A CTE can be thought of as  a temporary result set that is defined with in the execution scope of a single SELECT,INSERT,UPDATE,DELETE, OR CREATE VIEW statement. A CTE is similar to a derived table in that it is not stored as an object and lasts only for the duration of the query. 

Temporary tables in Sql Server

Temporary tables in Sql Server

Temporary tables , are very similar to the permanent tables. Permanent tables get created in the database you specify, and remain in the database permanently, until you delete(drop)them.On the other hand, temporary tables get created in the TempDB and are automatically deleted, when they are no longer used.
Different types of temporary tables:
  1. Local temporary tables
  2. Global temporary tables.

Now we create the temporary table..........................

use test
create table #EmpTable
(
Id int,
Name varchar(50)
)
select * from #EmpTable
insert into #EmpTable values(1,'kiran')
insert into #EmpTable values(2,'kk')
insert into #EmpTable values(3,'sp')

Check if the local temprory tables is created :-
 Temporary tables are created in the TempDB. Query the subobjects system table in TempDB. The name of the table, is suffixed with the lot of underscores and a random number. For this reason you have to use the LIKE Operator in the query
--when we create the # use in front that table then it create in TempDB
--then go in system database then TempDB in tempprary tables

Ex-:   select name from tempdb..sysobjects where name like '#EmpTable%'

When we create the temporary table in end of table name behind some random number take in sql server like this:-
If we want to name of table then use query:-

select name from tempdb..sysobjects where name like '#EmpTable'

output:  null  because each temp table  have  name with some random number

Note:- A local temporary table is available, only for the connection that has created the table.
Now we want use the query the one window like 2nd  query window first connection if we want to open the new window like 2nd query window second connection. In case first connection window query we can use the 2nd connection query window if we use then show this error like that:-

Msg 208, Level 16, State 0, Line 1
Invalid object name '#personltbles'.


A local temporary table is automatically dropped, when the connection that has created the it, is closed.
Note:- now when we closed the query window connection then temporary table automatically drop and refresh the system database table table automatically deleted.

If the user want to explicitly drop the temporary table, he can do so using
DROP TABLE # EmpTable'

LOCAL Temprory procedure:If the temprory table , created inside the stored procedure, it’s gets dropped automatically upon the completion of stored procedure execution.

Create the stored procedure:-

---create stored procedure…………………..

create procedure splocaltmptable
as
begin
create table #personaldetail
(
Id int,
name varchar(20)
)

insert into #personaldetail values (1,'pukki')
insert into #personaldetail values (2,'sukki')
insert into #personaldetail values (1,'tukki')

select * from #personaldetail
end

--now execute the procedure
execute  splocaltmptable
it retrieve the value as output.

Note:- now when we execute the stored procedure then it will retrieve the value of output but we use 
select * from #personaldetail
this select query execute then select data automatically deleted.
Then show this error like this:-
Msg 208, Level 16, State 0, Line 1
Invalid object name '#personaldetail'.

Its temporary table in stored procedure automatically immediately  destroyed when we execute the stored procedure

 Now it is also possible for different connections , to create a local temporary table with the same name.
For example user1 and user2, both can create the a local temporary table with the same name  #personaldetail.
In case the same one query window connection and second window query connection using the create the table and any procedure  with same structure its possible and its provide the temporary table random number its basically different randomly.


GLOBAL Temporary table:- To create a global temporary table prefix the name of the table with 2 pound (##) symbols.

Syntax:-  --global temporary table
create table ##employeedetails
(
Id int,
name varchar(20),
)
--then refresh table in system database

 insert into ##employeedetails values(1,'kiran')
insert into ##employeedetails values(2,'kk')
insert into ##employeedetails values(3,'sp')

select * from ##employeedetails
--now if we select the table of another window then it retrieved data successfully
We use select data from any window connection

--but we can't create the table another with the same name.
It will show error like this:-

Msg 2714, Level 16, State 6, Line 1
There is already an object named '##employeedetails' in the database.

--In ##table not show the any random number

Global temporary table are visible to all the connections of the sql server, and are only destroyed when the last connection referencing the table is closed.

Multiple users , across multiple connections can have local temporary tables with the same name, but the global temporary table name has to be unique, and if you inspect the name of the global temp table, in the objecct explorer . there will be no random numbers suffixed at the end of the table name. 

Difference B/W local and Global Temporary tables
  1. Local Temp Tables are prefixed with single pound(#)symbol, where as Global temp tables are prefixed with 2 pound(##)symbols.
  2. Sql server appends some random numbers at the end of the local temp table name, where this is nit done for global tempo table names.
  3. Local temporary tables are only visibleto that session of the sql server which has created it, where as global temporary tables are visibles to all thesql server sessions.
  4. Local temporary tables are automatically dropped , when the session that created the temporary tables is closed, where as global temporary tables are destroyed when the last connection that is referencing the global temp table is closed.


Monday, 17 October 2016

Veiw and its Advantages in Sql Server and What is INDEX VIEWS what is solution of this error SQL SCHEMABINDING Error

Veiw and its Advantages in Sql Server and What is INDEX VIEWS what is solution of this  error SQL SCHEMABINDING Error

 View:--  A view is nothing more than a saved SQL query. A view can also be considered as a virtual table. A view is defined by a query and only shows the data which is defined at the time of creation of the view. If you hide particular columns then use the view. A view hides the complexity of the underlying database schema, or customizes the data and schema for a set of users.

Advantages of view:-
  1. View can be used to reduce the complexity of the database schema
  2. Views can be used as a machinsm to implement row and column level security.
  3. View can be used to present aggregated data and hide detailed data.
  4. A view is virtual, the data from a view is not stored physically. It is a set of queries that, when applied to one or more tables, is stored in the database as an object
  5. A view encapsulates the name of the table. A virtual table contains column and data from multiple tables
  6. Views are used for security purpose in the database because it hides the name of the table and logic and provides the virtual table. A view is used to store the SELECT statement only
  7. In the view we can modify the data and table. A view provides a convenient way to retrieve and manipulate data. A view contains rows and columns, the same as a real table. The fields in a view are fields from one or more real tables in the database. A view shows up-to-date 
--create table.....................................

create table Department
(
DeptId int primary key,
Deptname varchar(23)
)

create table Employee
(
Id int,
Name varchar(32),
Salary float,
Gender varchar(23),
DepartmentId int  foreign key references Department(DeptId) on delete cascade
)

insert into Department values(1,'IT')
insert into Department values(2,'HR')
insert into Department values(3,'PAYROLL')
insert into Department values(4,'ADMIN')

insert into Employee values(1,'Kiran',4500,'male',3)
insert into Employee values(2,'Sara',3400,'female',1)
insert into Employee values(3,'john',4000,'male',2)
insert into Employee values(4,'kenny',5200,'female',4)

SELECT * FROM Department
SELECT * FROM Employee

---now join the tables

select id,Name,Salary,Gender,DepartmentId
from Employee
join Department
on Employee.DepartmentId=Department.DeptId

---create the view…………………

create view VWGetbyDepartment
as
select e1.id,e1.Name,e1.Salary,e1.Gender,d1.Deptname
from Employee e1
join Department d1
on e1.DepartmentId=d1.DeptId


--use store procedure query like this

sp_helptext  VWGetbyDepartment

select * from VWGetbyDepartment


---we used join in creating view the table procedure only IT data from table----

create view VWDepartment_IT
as
select e1.id,e1.Name,e1.Salary,e1.Gender,d1.Deptname
from Employee e1
join Department d1
on e1.DepartmentId=d1.DeptId
where d1.Deptname='IT'

-- query---

select * from VWDepartment_IT

---we can view for summarized  data from table----

create view VWSummarize_Data
as
select d1.Deptname,Count(e1.id) as 'Total Employee'
from Employee e1
join Department d1
on e1.DepartmentId=d1.DeptId
group by d1.Deptname

-- query---

select * from VWSummarize_Data

To Modify a view –ALTER VIEW statement.
To Drop a view- DROP VIEW VWname.

UPDATEABLE VIEWS :- 

SELECT * FROM dbo.Department
SELECT * FROM dbo.Employee

create view VWexceptsalaryEmployee
as
select id,name,gender,departmentId
from Employee
---here this create view select data from table Employee then execute that
select * from VWexceptsalaryEmployee

----now we update a view in table that
update VWexceptsalaryEmployee
set Name='sapna' where id=4
--after executed data updated-then select query used that---

----now we can delete data increated view----
delete from  VWexceptsalaryEmployee where id=3
---after execute the view data deleted

----insert data in created view----
insert into VWexceptsalaryEmployee values(3,'john','male',2)
---after execute data insert---

 ---update view in both tables using create view----
 create view VWbothviewtabls
 as
 select id,name,gender,deptname
 from dbo.Employee
 join dbo.Department
 on Employee.DepartmentId=Department.DeptId  

 ---then select data---
 select * from VWbothviewtabls

 ---update the created view in both table
 update VWbothviewtabls
 set Name='kenny' where Deptname='IT'
 ---after execute this query data is update

 Conclusion:- if a view is based on multiple tables, and if you update the view, it may not update the underlying base tables correctly. To correctly update a view, that is based on multiple table, INSTEAD OF triggers are used.

We will discuss about triggers and correctly updating a view that is based on multiple tables.next

VIEW LIMITATIONS:-
  1. You can not pass  parameter to a view. Table valued functions are not excellent replacement for parameterized views.
  2. Rules and default cannot be associated with views.
  3. The ORDER BY clause is invalid in view unless TOP or FOR XML is also specified.
  4. View can not be based on temporary tables.
---create table in another selected----
select * from dbo.Employee

---now create the view--

create view VWviewlimitations
as
select Id,name,salary,gender,departmentId
from dbo.Employee

---after created

select * from dbo.Employee

alter view VWviewlimitations
as
select Id,name,salary,gender,departmentId
from dbo.Employee
order by id

--In view created order by id it occured error like this-:
--ERROR
--Msg 1033, Level 15, State 1, Procedure VWviewlimitations, Line 5
--The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP or FOR XML is also specified.


select * from VWviewlimitations

---with parameter Error : cannot pass parameter view as same

create view VWviewlimitations
@gender nvarchar(32)
as
select Id,name,salary,gender,departmentId
from dbo.Employee
where Gender=@Gender

--it will occured error if we execute that query----

---then now we create inline table value function in view

select * from VWviewlimitations where gender='male'

create function Fn_viewtbledetails(@gender varchar(33))
returns table
as
return
(select Id,name,gender,departmentId
from Employee where gender=@gender)

select * from Fn_viewtbledetails('male')


--we can not create temporary table on temp tables--- 

create table ##Tempotable
(
Id int,
name varchar(32),
gender varchar(23)
)
insert into ##Tempotable values(101,'Tom','Male')
insert into ##Tempotable values(102,'sara','female')
insert into ##Tempotable values(103,'kenny','female')
insert into ##Tempotable values(104,'sam','Male')

select * from ##Tempotable

--if we create again temporary table then.....

create view VWTemptable
as
select id,name,gender
from ##Tempotable

--it will occured the same error

--Msg 4508, Level 16, State 1, Procedure VWTemptable, Line 4
--Views or functions are not allowed on temporary tables. Table names that begin with '#' denote temporary tables.

INDEX VIEWS:- A standard or Non-Indexed view, is just a stored SQL query. When we try to retrieve data from the view, the data is actually retrieved from the underlying base tables.
So, view is just a virtual table it does not store data by default.
However, when you create the index , on a view, the view gets materialized. This means, the view is now, capable of storing data.
In sql server, we call them indexed view and in oracle, materialized view.

Guidelines for creating Indexed View
  1. The view should be created with schema Binding option
  2. If an aggregate function in the select list references an expression, and if there is a possibility for that expression to be null, then a replacement value should be specified
  3. If group by is specified, the view select list must contains a Count_Big(*) expression
  4. The base tables in the view, should be references with two part name.



-- Sql Query..............

use test

create table tblProducts
(
ProductId int primary key,
Name varchar(50),
UnitPrice int
)

create table tblProductSales
(
ProductId int foreign key references tblProducts(ProductId),
QuantitySold int
)

insert into tblProducts values(1,'Pens',56)
insert into tblProductSales values(1,6)

--we can create view   from table----

create view VMTotalSales_ByProduct
with schemaBinding
as
select Name,
Sum(isnull((QuantitySold * UnitPrice),0)) as TotalSales,
COUNT_BIG(*) as TotalTransactions from  tblProductSales  join tblProducts  on tblProducts.ProductId=tblProductSales.ProductId
group by name

Error

Msg 4512, Level 16, State 3, Procedure VMTotalSales_ByProduct, Line 21
Cannot schema bind view 'VMTotalSales_ByProduct' because name 'tblProductSales' is invalid for schema binding? Names must be in two-part format and an object cannot reference itself.

Solution:

When You Create a view "WITH SCHEMABINDING", Database will keep the reference with object name. many database object can be created with same name from difference user, if we create the view by using only name. There are lot of difficulties to handle. To avoid that, SQL Server expects the Object Name in Proper Format like
Owner.Object_Name.

In My Query I changed to DBO.tblProductSales  , then i tried to create the view then it works fine.


create view VMTotalSales_ByProduct
with schemaBinding
as
select Name,
Sum(isnull((QuantitySold * UnitPrice),0)) as TotalSales,
COUNT_BIG(*) as TotalTransactions from  dbo.tblProductSales  join dbo.tblProducts  on tblProducts.ProductId=tblProductSales.ProductId
group by name

-- create unique Clustered Index which name UIxwithName
create unique Clustered Index UIxwithName
on  VMTotalSales_ByProduct(Name)


select * from VMTotalSales_ByProduct


Result