PIVOT function in SQL Server 2005


PIVOT:

This is one of the most important enhancements to TSQL in SQL 2005 and is extremely useful for generating reports based on cross tab values.The PIVOT operator rotates rows into columns, optionally performing aggregations or other mathematical calculations along the way.


The syntax for the PIVOT relational operator is:


FROMtable_source
PIVOT ( aggregate_function ( value_column )
FOR pivot_column
IN (<column_list>)
) table_alias


table_source : The table where the data will be pivoted.
aggregate_function : The aggregate function that will be used against the specified column. pivot_column : The column that will be used to create the column headers.
column_list : The values to pivot from the pivot column.


For Example:


create table parameter
(
pid int,
pname varchar(50)
)
GO


create table TransactionInfo
(
TransId int,
pid int,
pvalue int
)
GO


insert into parameter values(1,'Para1')
GO
insert into parameter values(2,'Para2')
GO
insert into parameter values(3,'Para3')
GO
insert into parameter values(4,'Para4')
GO
insert into parameter values(5,'Para5')
GO

insert into TransactionInfo values(1,1,30)
GO
insert into TransactionInfo values(1,2,40)
GO
insert into TransactionInfo values(1,3,50)
GO
insert into TransactionInfo values(1,4,35)
GO
insert into TransactionInfo values(1,5,45)
GO
insert into TransactionInfo values(2,1,50)
GO
insert into TransactionInfo values(2,2,60)
GO
insert into TransactionInfo values(2,3,70)
GO
insert into TransactionInfo values(2,4,85)
GO
insert into TransactionInfo values(2,5,45)
GO


In TransactionInfo table row wise records are stored. If you need columnwise report we go for PIVOT functions.

select TransID,para1,para2,para3,para4,para5 from
(select a.pname,b.pvalue,TransID from parameter a,TransactionInfo b
where a.pid = b.pid and TransID in (1,2) ) as aa
pivot
(
sum(pvalue)
for pname in([para1],[para2],[para3],[para4],[para5])
) as bb
GO


The Following result set is obtained after executing the above query, which PIVOTS data based on the parameters thats been selected.


Output of above query is as follows


SQL Server 2005 - INTERSECT and EXCEPT operands.



INTERSECT and EXCEPT operands:


Like Union and Union all SQL Server 2005 introduces INTERSECT and EXCEPT operands.


INTERSECT :

It is useful for retrieving only distinct rows that exist in both the left and right queries.

EXCEPT :

It is useful for retrieving only distinct rows that exist in the left query.


For example :

Create table DeptA

( DeptId int, DeptName varchar(40))

GO

Create table DeptB

( DeptId int, DeptName varchar(40))

GO

insert into DeptA values(10,'Sales')

GO

insert into DeptA values(20,'Service')

GO

insert into DeptA values(30,'Puchase')

GO

insert into DeptB values(10,'Sales')

GO

insert into DeptB values(20,'Service')

GO

insert into DeptB values(30,'Marketing')

GO

--Intersect

select * From DeptA

Intersect

Select * From DeptB

GO




--Except

select * From DeptA

Except

Select * From DeptB

GO






Step by Step procedure of CLR Integration in SQL Server 2005


CLR integration in SQL Server 2005:


In T-SQL impossible when we need a stored procedure with some array-operations, text-parsing or complex math operations. However, it is quite easy if our Server allows us to deploy C# or VB.NET code that is used within the Server process. In other words, if we need complex procedural code, we can write it as managed code.


SQL Server 2005 we can write store procedure, triggers,user defined functions , user defined types etc in managed code(CLR) also. It acts as the operating system for the CLR when it is hosted inside SQL Server.


Procedure for Creating CLR integrated Store Procedure in SQL Server 2005 using Visual Studio 2005:

Open Visual Studio 2005 IDE.
· Go to menu File -> New -> Project.
· Within the “New Project” dialog box, select “database” (VB) as the project type and select “SQL Server Project” as the template. Provide your own project name, choose your own location and finally click OK.




You will be prompted with the “New Database Reference” dialog, where you need to provide the instance name of your SQL Server 2005 with database information.



When you are prompted for “SQL/CLR debugging” press “YES”.


Go to the Solution Explorer, right click on project and go to Add -> Stored Procedures




Select “Stored procedure” as in the template, provide the name of the stored procedure as “StoreProcedure1” and finally click add.





Add your code like this


Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Data.SqlTypes
Imports Microsoft.SqlServer.Server

Partial Public Class StoredProcedures1

Public Shared Sub SP_DisplayEmp()
Dim Con As New SqlConnection("context connection=true")
Try
Con .Open()
Dim Cmd As New SqlCommand("select eid,ename,sal from emp", Con)
Dim oReader As SqlDataReader
oReader = Cmd .ExecuteReader()
SqlContext.Pipe.Send(oReader)
Catch ex As Exception
SqlContext.Pipe.Send(ex.ToString())
End Try
End Sub

End Class


Here SqlContext.Pipe statement is an sql ouput statement.
After this ReBuild and Deploy the project through solution explorer.

Now new procedure named "SP_DisplayEmp" is added in master database. This procedure retrieve all the data which available in Emp table.


Open SQL server 2005 Query wizard and execute the following statements


use master
GO
--To enable SQL Server 2005 for CLR integration
EXEC sp_configure @configname = 'clr enabled', @configvalue = 1
RECONFIGURE WITH OVERRIDE
GO
create table emp
(
eid varchar(10),
ename varchar(40),
sal int
)
GO

insert into emp values('E01','Crys',81000)
GO
insert into emp values('E02','Jhon',72000)
GO
insert into emp values('E03','Gogul',90000)
GO

execute SP_DisplayEmp
GO


CLR integrated Procedure Ouput is

XML Serialization in .NET


XML Serialization:

By using XML serialization only public properties and fields can be serialized.

If private members are to be serialized, other serialization methods should be used (Binary Serialization and SOAP Serialization).

It requires a parameterless constructor. This constructor is called during deserialization.


Serialized form of the object does not contain any type, assembly information of the class. Only the data is stored.

Using XML serialization not all the classes can be serialized. Classes that implement IDictionary cannot be serialized. E.g. Hashtables cannot be serialized. Arrays of objects can be easily serialized. Collections can be serialized but to serialize collections certain rules must be followed.

Null values are not serialized with XML serialization. To include the null members in the serialized form IsNullable attribute should be set to true.

For example: [ XmlElement( IsNullable = true ) ]


Here ClsSample is a Serializable class. It has private and Public members,

using System;
using System.Collections.Generic;
using System.Text;

namespace XMLSerilization
{
public class ClsSample
{
private int m_TotalCount = 5;
public String m_StrWord = "Ten";

public void ReAssignMemberValues()
{
m_TotalCount = 20;
m_StrWord = "Twenty";
}
public void DisplayMemberValueAfterDeSerialization()
{
Console.WriteLine("Private member value is " + m_TotalCount);
Console.WriteLine("Public member value is " + m_StrWord);
}
}
}

Following way you can Serialize and Deserialize the objects(through files)

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace XMLSerilization
{
public class ClsXML
{
public void ToXMLSerilization(Object objToXml, string filePath)
{
StreamWriter stWriter = null;
XmlSerializer xmlSerializer;
try
{
xmlSerializer = new XmlSerializer(objToXml.GetType());
stWriter = new StreamWriter(filePath);
xmlSerializer.Serialize(stWriter, objToXml);
}
catch (Exception exception)
{
throw exception;
}
finally
{
if (stWriter != null) stWriter.Close();
}
}

public object FromXMLSerilization(string filePath, Type type)
{
XmlSerializer xmlSerializer;
FileStream fileStream = null;
try
{
xmlSerializer = new XmlSerializer(type);
fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
object objectFromXml = xmlSerializer.Deserialize(fileStream);
return objectFromXml;
}
catch (Exception Ex)
{
throw Ex;
}
finally
{
if (fileStream != null) fileStream.Close();
}
}
}
}

//Main Class

using System;
using System.Collections.Generic;
using System.Text;

namespace XMLSerilization
{
public class Program
{
static void Main(string[] args)
{
ClsSample ObjSample;
ClsXML ObjXML;
ObjSample = new ClsSample();
ObjSample.ReAssignMemberValues();
ObjXML = new ClsXML();
//Serialize
ObjXML.ToXMLSerilization(ObjSample, "c:\\XMLSerialized.TXT");
ObjSample = null;
//Deserilize
ClsSample ObjDeseialXML;
ObjDeseialXML = (ClsSample) ObjXML.FromXMLSerilization("c:\\XMLSerialized.TXT", typeof(ClsSample)) ;
ObjDeseialXML.DisplayMemberValueAfterDeSerialization();
}
}
}

Output :
Private member value is 5
Public member value is Twenty

Actually reassigned value for the private member is 20 but you are unable to get that value in deserialized object. Because XML Serilization does not keep private members information

SOAP Serialization in .NET

SOAP Serialization :

SOAP Serialization and Binary Serialization having many similar properties.

In SOAP Serialization private fields, type information including assembly, namespace, public key token information are also serialized.

Deserialization gives the same object as it was before serialization.

Serialization can be controlled to exclude a field using [NonSerialized] attribute.

[Serializable] attribute is used to mark a class as serializable.

Classes do not need to have a parameterless constructor. Because of performance issues, the constructor of the class is not called during deserialization.

Use if the serialization and deserialization platforms are not .NET.

Use if the message is sent through a firewall.

Here ClsSample is a Serializable class. It has private and Public members,


using System;
using System.Collections.Generic;
using System.Text;

namespace SOAPSerilization
{
[Serializable]
public class ClsSample
{
private int m_TotalCount = 5;
public String m_StrWord = "Ten";
public void ReAssignMemberValues()
{
m_TotalCount = 20;
m_StrWord = "Twenty";
}
public void DisplayMemberValueAfterDeSerialization()
{
Console.WriteLine("Private member value is " + m_TotalCount);
Console.WriteLine("Public member value is " + m_StrWord);
}
}
}

Following way you can Serialize and Deserialize the objects(through files)

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Soap;

namespace SOAPSerialization
{
public class ClsSOAP
{
//Serialization
public void ToSoapSerialization(Object objToSoap,string filePath)
{
IFormatter formatter;
FileStream fileStream = null;
try
{
fileStream = new FileStream(filePath,FileMode.Create, FileAccess.Write);
formatter = new SoapFormatter();
formatter.Serialize(fileStream, objToSoap);
}
catch (Exception exception)
{
throw exception;
}
finally
{
if (fileStream != null) fileStream.Close();
}
}

//Deserialization
public object FromSoapSerialization(string filePath)
{
IFormatter formatter;
FileStream fileStream = null;
try
{
fileStream = new FileStream(filePath,FileMode.Open, FileAccess.Read);
formatter = new SoapFormatter();
return formatter.Deserialize(fileStream);
}
catch (Exception exception)
{
throw exception;
}
finally
{
if (fileStream != null) fileStream.Close();
}
}
}
}

//Main Class
using System;
using System.Collections.Generic;
using System.Text;

namespace SOAPSerialization
{
public class Program
{
static void Main(string[] args)
{
ClsSample ObjSample;
ClsSOAP ObjSOAP;
ObjSample = new ClsSample();
ObjSample.ReAssignMemberValues();
ObjSOAP = new ClsSOAP();
//Serialize
ObjSOAP.ToSoapSerialization(ObjSample, "c:\\SOAPSerialized.TXT");
ObjSample = null;
//Deserilize
ClsSample ObjDeseialSOAP;
ObjDeseialSOAP = (ClsSample)ObjSOAP.FromSoapSerialization("c:\\SOAPSerialized.TXT");
ObjDeseialSOAP.DisplayMemberValueAfterDeSerialization();
}
}
}

Output:

Private member value is 20

Public member value is Twenty

Here both private and public members are serialized