Counter of Festivals

Ashok Blog for SQL Learners and Beginners and Experts

Wednesday, 30 September 2015

SSRS Concepts


Ref:


http://basireddysubbareddy.blogspot.in/2013/08/deploy-ssrs-report-server-project.html

http://basireddysubbareddy.blogspot.in/2013/08/ssrs-some-concepts.html



Deploy SSRS Report Server Project



To deploy Report Server Project, please go through below steps:

1. Go to Report Service Configuration Manager then click on the Report Manager URL tab in order to get Report Server URL.

Deploy SSRS Report Server Project-1
2. Now click on the Report Manager URL. We will get a empty screen as below:
Deploy SSRS Report Server Project-2

3. Let us query catalog table of ReportServer Database.
SELECT * FROM CATALOG
It will show below output:
Deploy SSRS Report Server Project-3
When we design a report, Report Definition Language File (.rdl) is generated whcih is basically a XML file which contains all the information about our report. So when we deploy the report, the .rdl file gets inserted into the our Report Server Database.
4. . Now come back to our SSRS Project. Right Click the Project and click on properties.
Deploy SSRS Report Server Project-4-1
Alternatively we can also go from Project Menu.
Deploy SSRS Report Server Project-4-2

5. In both case we will be directed to Project’s Properties Page where we are going to insert our Target Server URL Which is our Report Server Web Service URL.
In my case it is like
http://bhushan-pc:8080/ReportServer
Deploy SSRS Report Server Project-5
6. After click on OK, right click the Project and select Deploy from the context menu.
Deploy SSRS Report Server Project-6
7. If all fine we will receive Success Message.
Deploy SSRS Report Server Project-7
8. If here we query our Catalog table of Report Server database we will get results like following.
SELECT * FROM CATALOG
Deploy SSRS Report Server Project-8
Here we can see the entries of Our Project and Report.In above result Type 1 means Project and 2 means Report.
If you want to see the XML content, execute following query:
SELECT
[REPORT NAME] = NAME,
[RDL CONTENT] = CAST(CAST(CONTENT AS VARBINARY(MAX)) AS XML)
FROM CATALOG
WHERE TYPE = 2
You will get results like following:
Deploy SSRS Report Server Project-9
9. Now let us see our report from the browser.Go to Report Manager URL and you will get a screen like below:
Deploy SSRS Report Server Project-10
10. Now click on StartSSRS and it will show the list of report.In our case it will show only 1 report which is PersonAddresDetails.
Deploy SSRS Report Server Project-11
11. Now Click on PersonAddresDetails Report and you will get following screen:
Deploy SSRS Report Server Project-12
Congratulations! Our First SSRS Project is successfully deployed.

Moving the Report Server Databases to Another Computer

You can move the report server databases that are used in a current installation to a SQL Server Database Engine instance that is on a different computer. Both the reportserver and reportservertempdb databases must be moved or copied together. A Reporting Services installation requires both databases; the reportservertempdb database must be related by name to the primary reportserver database you are moving.

Moving a database does not effect scheduled operations that are currently defined for report server items.

Schedules will be recreated the first time that you restart the Report Server service.

SQL Server Agent jobs that are used to trigger a schedule will be recreated on the new database instance. You do not have to move the jobs to the new computer, but you might want to delete jobs on the computer that will no longer be used.

Subscriptions, cached reports, and snapshots are preserved in the moved database. If a snapshot is not picking up refreshed data after the database is moved, clear the snapshot options in Report Manager, click Apply to save your changes, re-create the schedule, and click Apply again to save your changes.

Temporary report and user session data that is stored in reportservertempdb are persisted when you move that database.

SQL Server provides several approaches for moving databases, including backup and restore, attach and detach, and copy. Not all approaches are appropriate for relocating an existing database to a new server instance. The approach that you should use to move the report server database will vary depending on your system availability requirements. The easiest way to move the report server databases is to attach and detach them. However, this approach requires that you take the report server offline while you detach the database. Backup and restore is a better choice if you want to minimize service disruptions, but you must run Transact-SQL commands to perform the operations. Copying the database is not recommended (specifically, by using the Copy Database Wizard); it does not preserve permission settings in the database.

Important 
The steps provided in this topic are recommended when relocating the report server database is the only change you are making to the existing installation. Migrating an entire Reporting Services installation (that is, moving the database and changing the identity of the Report Server Windows service that uses the database) requires connection reconfiguration and an encryption key reset. For more information about migrating a Reporting Services installation, see Migration (Reporting Services).


Detaching and Attaching the Report Server Databases
--------------------------------------------------------------------------------

If you can take the report server offline, you can detach the databases to move them to the SQL Server instance you want to use. This approach preserves permissions in the databases. If you are using a SQL Server 2008 database, you must move it to another SQL Server 2008 instance. After you move the databases, you must reconfigure the report server connection to the report server database. If you are running a scale-out deployment, you must reconfigure the report server database connection for each report server in the deployment.

Use the following steps to move the databases:

1.Backup the encryption keys for the report server database you want to move. You can use the Reporting Services Configuration tool backup the keys.

2.Stop the Report Server service. You can use the Reporting Services Configuration tool to stop the service.

3.Start SQL Server Management Studio and open a connection to the SQL Server instance that hosts the report server databases.

4.Right-click the report server database, point to Tasks, and click Detach. Repeat this step for the report server temporary database.

5.Copy or move the .mdf and .ldf files to the Data folder of the SQL Server instance you want to use. Because you are moving two databases, make sure that you move or copy all four files.

6.In Management Studio, open a connection to the new SQL Server instance that will host the report server databases.

7.Right-click the Databases node, and then click Attach.

8.Click Add to select the report server database .mdf and .ldf files that you want to attach. Repeat this step for the report server temporary database.

9.After the databases are attached, verify that the RSExecRole is a database role in the report server database and temporary database. RSExecRole must have select, insert, update, delete, and reference permissions on the report server database tables, and execute permissions on the stored procedures. For more information, see How to: Create the RSExecRole.

10.Start the Reporting Services Configuration tool and open a connection to the report server.

11.On the Database page, select the new SQL Server instance, and then click Connect.

12.Select the report server database that you just moved, and then click Apply.

13.On the Encryption Keys page, click Restore. Specify the file that contains the backup copy of the keys and the password to unlock the file.

14.Restart the Report Server service.

Backing Up and Restoring the Report Server Databases
--------------------------------------------------------------------------------

If you cannot take the report server offline, you can use backup and restore to relocate the report server databases. You should use the ‘Copy_Only’ option. Beginning in SQL Server 2008, SQL Server Management Studio supports copy-only backups. After you restore the databases, you must configure the report server to use the database on the new server instance. For more information, see the instructions at the end of this topic.

Using BACKUP and COPY_Only to Backup the Report Server Databases
When backing up the databases, set the COPY_OnlyL option and backup type to Full.

Note 
Be sure to back up both the ReportServer and ReportServerTempDB databases as well as their associated log files.


For more information on using SQL Server Management Studio to backup a database, see How to: Back Up a Database (SQL Server Management Studio)

Using RESTORE and MOVE to Relocate the Report Server Databases
When restoring the databases, you can Use the RESTORE WITH NORECOVERY argument to perform the initial restore; this keeps the database in a restoring state, giving you time to review log backups to determine which one to restore. You would then repeat the RESTORE operation but use the RESTORE WITH RECOVERY argument.

Note 
Be sure to restore both the ReportServer and ReportServerTempDB databases as well as their associated log files.


For more information on using SQL Server Management Studio to restore a database, see How to: Restore a Database Backup (SQL Server Management Studio)

How to Configure the Report Server Database Connection
1.Start the Reporting Services Configuration tool and open a connection to the report server.

2.On the Database page, click Change Database. Click Next.

3.Click Choose an existing report server database. Click Next.

4.Select the SQL Server that now hosts the report server database and click Test Connection. Click Next.

5.In Database Name, select the report server database that you want to use. Click Next.

6.In Credentials, specify the credentials that the report server will use to connect to the report server database. Click Next.

7.Click Next and then Finish.

Note 
A Reporting Services installation requires that the SQL Server Database Engine instance include the RSExecRole role. Role creation, login registration, and role assignments occur when you set the report server database connection through the Reporting Services Configuration tool. If you use alternate approaches (specifically, if you use the rsconfig.exe command prompt utility) to configure the connection, the report server will not be in a working state. You might have to write WMI code to make the report server available. For more information, see Reporting Services WMI Provider.

MONDAY, DECEMBER 20, 2010


SQL Server Reporting Services: Quick way to get 10 digit year (all the zero’s) using String.Format

Dates are fun. See, by default most dates come out like 5/6/2008. But computers, and programs like them formatted as 05/06/2008. That way, all the dates, no matter what month or day, are all the same length, cool huh?

Well, in Reporting Services, if you have a date field coming back in a dataset, and you want to format it as a 10 digit string, there are about 50 different ways to do it. You can use old VBA Left and Mid etc, or you can use String.Format like..

=String.Format(“{0:MM}/{0:dd}/{0:yyyy}”,CDate(Fields!CalendarDate.Value))

MONDAY, SEPTEMBER 27, 2010


Working with Report Snapshots in SQL Server Reporting Services (SSRS)

Problem


We have many SQL Server Reporting Services (SSRS) reports that use our OLTP systems as data sources. We are always adding new reports and the number of users running these reports is also increasing rapidly. We would like to look at leveraging report snapshots as a way to reduce some of the load on our database servers. Can you provide us with an example of how to do this?

Solution

A report snapshot provides the ability to run a report at a scheduled time or on demand and save the report in the ReportServer database. When a user requests the report, they automatically get the snapshot version stored in the ReportServer database rather than executing the SQL queries to retrieve the data from the underlying data source. You can schedule report snapshots to be run during off-peak hours; this can reduce the load on your database servers. You can also create snapshots manually and select which snapshot version of a report that you would like to run. You can save as many snapshots as you like or you can have Reporting Services limit the number of snapshots that are saved. Besides reducing the load on your database servers, you can use report snapshots to archive reports at a particular point in time for later viewing; e.g. month-end reports, year-end reports, etc. Depending on how many report snapshots you keep, you could use a significant amount of space in the ReportServer database


Creating a Drill Down Report with SQL Server 2008

In SSRS we can generate drill down reports in very easy way. To create Drill down reports, please follow the following steps.
Step1: Create New Report Project with one Shared DataSource with data query for generating report.
Step1: Create report by taking Table type report as shown bellow
Step3: Now Add Group for product by right clicking on Product Column as shown bellow
Select Add Parent group

Selet Product from Group By DropDown and check Add Group Header, then click OK

The report table looks like this
Step 4: From Row groups > select Product group details (group Details and not group header) > go to Group Properties > select Visibility tab > select Hide > click on Display can be toggled by this group item and select the name of the group then click on OK
Then the  preview the report
Step 5:We can also change the drill down and make it reverse by setting ‘InitialToggleState’ to True and by selecting the group properties (header), visibility tab and click Show

Navigating in SQL Server Reporting Services 2008

We can make three types navigations in SQL Server Reporting Services
  •  Navigating in same report(Book Marking)
  • Navigating to another Report(Jump to Report)
  • Navigation Website(Jum to URL)
 Any text box or image item can be used for intrareport or interreport navigation, for navigation to external resources like web pages and documents, and also to send e-mail. All of these features are enabled by using navigation properties that can be specified in the Textbox Properties or Image Properties dialog.

1.Navigating in same report(Book Marking)

This can be achieve with Book Marking in Reports.
Abookmark is a text box or image in a report that can be used as a navigational link. If you want to allow the user to click an item and navigate to another item, assign a bookmark value to each of the target items.

First, open the Textbox Properties dialog by right-clicking the text box and selecting Properties from the pop-out menu. In the Textbox Properties dialog, then switch to the Action tab in left panel.

To enable Hyperlink to a bookmark, set the Go to bookmark property to the target bookmark.

Using bookmarks to navigate within a report is very easy to do. Each report item has a BookMark property that may be assigned a unique value.

After adding bookmarks to any target items, use the Go to Bookmark Selection list to select the bookmark in the Properties for the Source item. This allows the user to navigate to items within the same report.


 2.Navigating to another Report(Jump to Report)

This powerful feature enables a text box or image to be used as a link to another report by passing parameter values to the target report. The target report can consist of a specific record or multiple records, depending on the parameters passed to the target report.

The following example uses a Products by Category report.That means the Products report shows the list of all Products and the Category Report shows the information about perticular Product. Name text box is used to link to a report that will display the details of a single product record. The Product Details report is very simple. This report accepts a ProductID parameter to filter the records and narrow down to the record requested.

First, open the Textbox Properties dialog by right-clicking the text box and selecting Properties from the pop-out menu. In the Textbox Properties dialog, then switch to the Action tab.

Then select the Go to report radio button, and select the target report from the drop-down list. And Add the perameters for the targetting report by clicking on Add button.

When a product name is clicked on the main report, the viewer redirects to the detailed report for the specific product by passing the ProductID parameter value.

3.Navigation Website(Jum to URL)

The Go to URL option can be used to navigate to practically any report or document content on your report server, and files, folders, and applications in your intranet environment or on the World Wide Web. It can also be set to an expression that uses links stored in a database, custom code, or any other values. It’s more accurate to say that any URI (Uniform Resource Identifier) can be used since a web request is not limited only to a web page or document. With some creative programming, queries, and expressions, your reports could be designed to navigate to a web page, document, e-mail address, Web service request, or a custom web application, directed by data or custom expressions.
Click on "Fx" to enter custom Web URL like http://www.google.co.in/ then click on ok.
Once you run the Report and click on the column which you have set "Go to URL", then you will be redirected to that web site.



Friday, 11 September 2015

Incorrect syntax near the keyword 'with'. If this statement is a common table expression, an xmlnamespaces clause or a change tracking context clause, the previous statement must be terminated with a semicolon.

Incorrect syntax near the keyword 'with'. If this statement is a common table expression, an xmlnamespaces clause or a change tracking context clause, the previous statement must be terminated with a semicolon.

Solution:

Starting with SQL Server 2008 you must always put a semicolon before WITH statement in CTE

But it is not need on below SQL version of SQL 2008 like SQL 2005,SQL 2000


Code:
create table #t
(
  pName Varchar(20),
  DateBegin DateTime,
  DateEnd DateTime
)

Insert Into #t(pName, DateBegin, DateEnd)
Values('Player1', '01/04/2012', '01/05/2012')

Insert Into #t(pName, DateBegin, DateEnd)
Values('Player2', '02/01/2012', '02/05/2012')


With DateRange(dt) As
(
    Select Convert(Datetime, '01/01/2012')
    UNion All
    Select DateAdd(dd, 1, Dat.dt) From DateRange Dat Where Dat.dt < CONVERT(Datetime, '01/31/2012')
)

Select T.pName, Dt.dt from #t T
Inner Join DateRange Dt on Dt.dt BETWEEN T.DateBegin and T.DateEnd

Drop Table #t

Correct Code:

Code:
create table #t
(
  pName Varchar(20),
  DateBegin DateTime,
  DateEnd DateTime
)

Insert Into #t(pName, DateBegin, DateEnd)
Values('Player1', '01/04/2012', '01/05/2012')

Insert Into #t(pName, DateBegin, DateEnd)
Values('Player2', '02/01/2012', '02/05/2012')


;With DateRange(dt) As----------------------------------To fix error added semicolon on SQL 2008
(
    Select Convert(Datetime, '01/01/2012')
    UNion All
    Select DateAdd(dd, 1, Dat.dt) From DateRange Dat Where Dat.dt < CONVERT(Datetime, '01/31/2012')
)

Select T.pName, Dt.dt from #t T
Inner Join DateRange Dt on Dt.dt BETWEEN T.DateBegin and T.DateEnd

Drop Table #t


Tuesday, 18 August 2015

CTE (Common Table Expression)

CTE (Common Table Expression)


Overview
  • It is called Common Table Expression, introduced in SQL 2005
  • It is kind of temporary result set with a scope of single DML operation (INSERT / UPDATE / DELETE)
  • It will be stored in memory
  • It will last only till the duration of the query
  • It can be self referenced which is the best usage of CTE
  • It is really useful in terms of recursion and deleting duplicate records

Advantages
  • Improved readability
  • Easy maintenance of complex queries
  • Can be defined in views also
  • Really works well for recursion and deleting duplicate records

Disadvantages
  • Above statement should be enclosed with ;
  • Cannot handle millions of records, #TEMP table will be a replacement in that scenario

Basic Syntax

WITH cte_name (optional column list)
AS
(
  Cte_query
)
  statement that uses the above CTE

Recursive Syntax

WITH cte_name (optional column list)
AS
(
  Cte_query --Anchor Member
Union All
Cte_query -- Recursive Member
)
  statement that uses the above CTE

Different Usages

  1. Basic use to replace Table variable or #TEMP table

-- Creating Table
CREATE TABLE Employee (EmployeeID INT, Name VARCHAR(50), ManagerID INT, DOB DATETIME)
-- Inserting Records
INSERT INTO Employee
VALUES
(1,'Kamlesh',NULL, '1960-01-01')
,(2,'Pratibha',1, '1960-05-01')
,(3,'Maulik',1 ,'1980-01-01')
,(4,'Nisarg',1,'1983-01-01')
,(5,'Dipa',3,'1982-01-01')
,(6,'Swara',5,'2008-01-01')
,(7,'Megha',4,'1986-01-01');

-- Query
WITH StartsWithM
AS
(
SELECT Name FROM Employee WHERE Name LIKE 'M%'
)
SELECT * FROM StartsWithM


  1. Using CTE for recurssion

-- Query  (Find out complete hierarchy of Swara)

WITH Hierarchy (EmployeeID, Name, ManagerID, Level)
AS
(
    -- Anchor Member Definition
    SELECT      EmployeeID, Name, ManagerID, 1 Level
    FROM  Employee
    WHERE EmployeeID = 6
    UNION ALL
    -- Recursive Member Definition
    SELECT      E.EmployeeID, E.Name, E.ManagerID, Level + 1
    FROM  Employee E
                INNER JOIN Hierarchy H ON H.ManagerID = E.EmployeeID
)
SELECT     
H.EmployeeID
, H.Name EmployeeName
, Level
, H.ManagerID
, ISNULL(E.Name,'<--No Manager-->') ManagerName
FROM        Hierarchy H
        LEFT JOIN Employee E ON H.ManagerID = E.EmployeeID
        

  1. CTE within CTE / CTE with multiple reference

/* Find out the employees with their managers who born prior to 1985
 We can write without using CTE in a much simpler way but this is just an example of using one CTE inside other CTE */

WITH PriorTo1985
AS
(
SELECT        *
FROM        Employee
WHERE        DOB < '1985-01-01'
),
Manager
AS
(
SELECT        E.Name, ISNULL(M.Name,'No Manager') ManagerMame
FROM        PriorTo1985 P
INNER JOIN        Employee E
ON P.EmployeeID = E.EmployeeID
LEFT JOIN Employee M
ON E.ManagerID = M.EmployeeID
)
SELECT * FROM Manager


  1. CTE within MAXRECURSION Hint

Maximum recursion is 100, if we want to go beyond that then we have to use MAXRECURSION Hint
If we don’t use it, by default it will take 100
We can give number from 0 to 32767

DECLARE        @startDate DATETIME,
@endDate DATETIME

SET                @startDate = '11/10/2011'
SET                @endDate = '03/25/2012';

WITH CTE AS
(
SELECT        YEAR(@startDate) AS 'yr',
MONTH(@startDate) AS 'mm',
DATENAME(mm, @startDate) AS 'mon',
DATEPART(d,@startDate) AS 'dd',
@startDate 'new_date'
UNION ALL
SELECT
YEAR(new_date) AS 'yr',
MONTH(new_date) AS 'mm',
DATENAME(mm, new_date) AS 'mon',
DATEPART(d,@startDate) AS 'dd',
DATEADD(d,1,new_date) 'new_date'
FROM        CTE
WHERE        new_date < @endDate
)
SELECT        yr AS 'Year', mon AS 'Month', count(dd) AS 'Days'
FROM        CTE
GROUP BY mon, yr, mm
ORDER BY yr, mm
OPTION (MAXRECURSION 1000)

PIVOT UNPIVOT in SQL Server

PIVOT and UNPIVOT


Overview
  • Introduced in SQL 2005
  • PIVOT transforms row level data to column level
  • UNPIVOT transforms column level data to row level data
  • Really useful in cross tab functionality


Example of PIVOT
  • Let's us take following example.

create table Income(EmpName nvarchar(10), IncomeDay nvarchar(10), IncomeAmount int)

insert into Income values ('Nisarg', 'FRI', 100)
insert into Income values ('Nisarg', 'MON', 300)
insert into Income values ('Nisarg', 'WED', 500)
insert into Income values ('Nisarg', 'TUE', 200)
insert into Income values ('Swara', 'WED', 900)
insert into Income values ('Nisarg', 'FRI', 100)
insert into Income values ('Swara', 'MON', 300)
insert into Income values ('Swara', 'FRI', 300)
insert into Income values ('Megha', 'TUE', 500)
insert into Income values ('Megha', 'TUE', 200)
insert into Income values ('Nisarg', 'MON', 900)
insert into Income values ('Megha', 'FRI', 900)
insert into Income values ('Megha', 'MON', 500)
insert into Income values ('Nisarg', 'FRI', 300)
insert into Income values ('Nisarg', 'WED', 500)
insert into Income values ('Nisarg', 'FRI', 300)
insert into Income values ('Swara', 'THU', 800)
insert into Income values ('Nisarg', 'TUE', 100)
insert into Income values ('Nisarg', 'THU', 300)
insert into Income values ('Megha', 'WED', 500)
insert into Income values ('Megha', 'THU', 800)
insert into Income values ('Swara', 'TUE', 600)

  • Now the table is looking like this

EmpName
IncomeDay
IncomeAmount
Nisarg
FRI
100
Nisarg
MON
300
Nisarg
WED
500
Nisarg
TUE
200
Swara
WED
900
Nisarg
FRI
100
Swara
MON
300
Swara
FRI
300
Megha
TUE
500
Megha
TUE
200
Nisarg
MON
900
Megha
FRI
900
Megha
MON
500
Nisarg
FRI
300
Nisarg
WED
500
Nisarg
FRI
300
Swara
THU
800
Nisarg
TUE
100
Nisarg
THU
300
Megha
WED
500
Megha
THU
800
Swara
TUE
600

  • Now, we want result something like this. Basically we want total income of each person for each day as a matrix shown below.

EmpName
MON
TUE
WED
THU
FRI
Megha
500
700
500
800
900
Nisarg
1200
300
1000
300
800
Swara
300
600
900
800
300

  • Now, using PIVOT, we can achieve the same thing with very simple query

SELECT        EmpName, [MON],[TUE],[WED],[THU],[FRI]
FROM        Income
PIVOT (
SUM (IncomeAmount)
for IncomeDay in
(
[MON],[TUE],[WED],[THU],[FRI]
)
) as TotalIncomePerDay


  • Above query has basically 3 portions
    • SELECT
      • Contains column names. Basic fields (e.g. EmpName) and Pivoted values (Mon, Tue, etc.)
    • FROM
      • Which result set you want to PIVOT
      • In above example, we have usedIncome table, we can use some query as derived table also
    • PIVOT
      • Aggregation of a field from base table (mentioned in FROM clause)
        • Any aggregation (min, max, avg, sum, etc..) is required, otherwise it will throw an error
      • Pivot fields name (e.g. Incomeday)
      • Pivot Values ([MON], [TUE], etc..)
        • Brackets are not required, but if you would like to have white space in a name of field, then they are required
        • Even though a value does not exist in actual table records, still you can mention, it won't throw any error. e.g. Saturday is not part of any resultset, and if I include SAT as a column, it won't throw any error, and simply it will give me NULL in the final resultset

Example of UNPIVOT
  • Let's us take following example.
  • Assume that we have a table which is having TotalIncome of each employee for each working day as a matrix.
  • Following query will create that kind of data for us

SELECT        EmpName, [MON],[TUE],[WED],[THU],[FRI]
INTO        TotalSalary
FROM        Income
PIVOT (
SUM (IncomeAmount)
for IncomeDay in
(
[MON],[TUE],[WED],[THU],FRI
)
) as TotalIncomePerDay

  • So TotalSalary is looking something like this

EmpName
MON
TUE
WED
THU
FRI
Megha
500
700
500
800
900
Nisarg
1200
300
1000
300
800
Swara
300
600
900
800
300

  • Now we want to transform them into row based data
  • Following query will do the same

SELECT        EmpName, IncomeDay, Income
FROM        TotalSalary
UNPIVOT
(
Income
for IncomeDay in
(
[MON],[TUE],[WED],[THU],FRI
)
) as TotalIncomePerDay

  • Unlike PIVOT, if you put some wrong value in highlighted portion, it will throw an error. e.g. If we add SAT here, but SAT is not part of columns of Income table, so it will throw an error.
  • Once you PIVOT a resultset and then UNPIVOT the same, you won't get actual set of data

Example of Dynamic PIVOT
  • Assume that we have rows without static data and we would like to generate cross-tab report dynamically  based on data available at that time.
  • Let's assume that, we want to generate cross-tab report where rows will be Days and columns will be EmpName.
  • So basically , we are looking for result something like this

IncomeDay
Nisarg
Megha
Swara
FRI
800
900
300
MON
1200
500
300
THU
300
800
800
TUE
300
700
600
WED
1000
500
900

  • Now in that case, following query will give the same

SELECT        IncomeDay, [Nisarg], [Megha], [Swara]
FROM        Income
PIVOT (
SUM (IncomeAmount)
for EmpName in
(
[Nisarg], [Megha], [Swara]
)
) as TotalIncomePerDay

  • Now, let's say, 2 more employees are getting added to the table, in that case, our result will include 2 more columns, but we don't want to change our query. Currently EmpNames are hard-coded but now we want to pull them from a table and dynamically generate a result set of all available employees
  • So in this case, we have to go for dynamic PIVOT

-- Variable Declaration
DECLARE @Query NVARCHAR(MAX)
, @EmpNameXMLString NVARCHAR(MAX)
, @EmpNameString NVARCHAR(MAX)
, @ParmDefinition nvarchar(500);

SELECT @EmpNameXMLString = 'SELECT DISTINCT ''['' + EmpName  + ''],'' FROM Income FOR XML PATH('''')'
SELECT @Query = 'SELECT @EmpNameStringOUT = SUBSTRING((' + @EmpNameXMLString + '), 1,LEN((' + @EmpNameXMLString + '))-1)'
SET @ParmDefinition = N'@EmpNameStringOUT NVARCHAR(MAX) OUTPUT';

-- Building EmpName String
EXECUTE SP_EXECUTESQL @Query, @ParmDefinition, @EmpNameStringOUT=@EmpNameString OUTPUT
--SELECT @EmpNameString

SET @Query =
'
SELECT        IncomeDay, ' + @EmpNameString + '
FROM        Income
PIVOT (
SUM (IncomeAmount)
for EmpName in
(
' + @EmpNameString + '
)
) as TotalIncomePerDay'

EXECUTE SP_EXECUTESQL @Query