Groups in SSRS 2008



Groups in SSRS 2008

In Report Designer, Groups are created to organize data on the report or to calculate aggregate summaries. An understanding how to define groups and use group features helps you design reports that are more concise and communicate summarized data in a more compact format.

We also use Groups in SSRS reports to provide Drill-down features. In this article, I'll walk you through SSRS Groups to create a report shown in below image:

[pic]

STEP1: Add new report in Report Server project and rename it to GroupsInSSRS.rdl. 

Create new Shared DataSource for database AdventureWorksDW2008R2. 

Click here to download AdventureWorksDW2008R2 database.

STEP2: Create a new dataset dsMain with Shared Data Source. Use below query for this dataset:

SELECT

D.CalendarYear AS [Year]

,D.CalendarQuarter AS [Quarter] 

,D.EnglishMonthName AS [Month]

,D.FullDateAlternateKey AS [Date]

,P.EnglishProductName AS [ProductName]

,C.FirstName + LastName AS [CustomerName]

,ST.SalesTerritoryRegion AS [SalesRegion]

,ST.SalesTerritoryCountry AS [SalesCountry]

,F.SalesOrderNumber AS [OrderNumber]

,F.SalesAmount 

FROM FactInternetSales F

JOIN DimProduct P 

  ON P.ProductKey = F.ProductKey 

JOIN DimCustomer C 

  ON C.CustomerKey = F.CustomerKey 

JOIN DimDate D 

  ON D.DateKey = F.OrderDateKey 

JOIN DimSalesTerritory ST 

  ON ST.SalesTerritoryKey = F.SalesTerritoryKey 

STEP3: Drag and drop a table control and select CustomerName, OrderNumber, and SalesAmount fields in the table. 

[pic]

STEP4: Select table detail row --> Right click --> select Add Group --> Row Group --> Parent Group

[pic]

STEP5: Select ProductName in Tablix group window and check add group header check box. Click OK and sace changes.

[pic]

Now you can see Product Group in the table as shown below:

[pic]

Delete Group1 Column and rename Customer Name as Particulars. Select ProductName in Product Group as shown below:

[pic]

STEP6: Select ProductName group and add one more group for SalesCountry in similar way mentioned atstep5. Delete the group column and select SalesCountry in CountryGroup as shown below:

[pic]

STEP7: In the same way add Groups for the following Fields:

▪ SalesRegion

▪ Date

▪ Month

▪ Quarter

▪ Year

Finally table will look like one shown in below image:

[pic]

STEP8: we are done with report Groups. You can Preview the report:

[pic]

STEP9: Format Groups: This is the final step. Without formatting the tabular data look meaningless and its very difficult to understand the report. You can do following formatting to make it easier to understand:

|Group |Left Indent |BackgroundColor |

|Year |2pt |#7c73c8 |

|Quarter |12pt |#9894ca |

|Month |22pt |#b4b4c8 |

|Date |32pt |#c7c7d8 |

|SalesRegion |42pt |#dadaeb |

|SalesCountry |52pt |#e7e7f0 |

|ProductName |62pt |#f4f4fc |

|CustomerName |72pt |White |

|(detail row) | | |

[pic]

Toggle Groups:

Select Quarter Group and click on Group Properties. Select Visibility in Group Properties and select Hideoption button. Check Dispaly can be toggled by this report item  check box and select Year from combo box.

[pic]

Similar way toggle other report items.

Also Toggle Order Number column with Particular text box.

Now click on Preview and generate the report:

[pic]

Thats all about Report Groups...

Cheers!!!

Conditional Formatting in SSRS 2008

Posted: Sat, 04 Sep 2010 07:29:00 +0000

Alternate Background Color in Tabular Report:

Alternate background color of rows in a table make it easier to read horizontally. Also it makes report look and feel better. This is very common but simple task to achieve in SSRS report using expression.

Select the detail row of the data table in the layout tab.

[pic]

Go to property window and select expression of BackgroundColor and enter below expression:

=IIF(RowNumber(Nothing) Mod 2 = 0,"Transparent","#cdfcbe")

Now click and Preview the report:

[pic]

Format Phone number using REGEX function:

Suppose you want to display Phone no in (ddd) ddd-dddd format instead of ddd-ddd-dddd. To do this, Right click on the required textbox --> click expression... and enter below expression:

=System.Text.RegularExpressions.Regex.Replace(Fields!Phone.Value, "(\d{3})[ -.]*(\d{3})[ -.]*(\d{4})", "($1) $2-$3")

Now click on Preview and see the report: 

[pic]

  

Changing Font Color dynamically:

Sometime we need to format data based on the their values. Below is an example for Base rate color selection:

|Base Rate |Color |

| 15 AND 25 AND 40 | Red |

To do this, Enter C (Currency format) in Format and below expression in Color property of BaseRate field:

=SWITCH(Fields!BaseRate.Value = 10, "Green", IIF(Fields!PercentComplete.Value >= 1, "Blue", "Red"))

A different way to get the same functionality uses the Switch function. The Switch function is useful when you have three or more conditions to test. The Switch function returns the value associated with the first expression in a series that evaluates to true: 

=Switch(Fields!PercentComplete.Value >= 10, "Green", Fields!PercentComplete.Value > 1,"Blue", Fields!PercentComplete.Value = 1, "Yellow", Fields!PercentComplete.Value 7,"Red","Blue") 

[pic]

[pic]

Recursive Hierarchy Group in SSRS 2008

Posted: Wed, 25 Aug 2010 23:29:00 +0000

In this article, I am going to explain how to create a Recursive Hierarchy Group in SSRS 2008 to display hierarchical levels. This is helpful when we want to display hierarchical data in a report e.g. employees in an organizational chart as shown below: 

[pic]

Pre-requisites for this article:

▪ SQL Server 2008 along with SSRS installed

▪ Business Intelligence Development Studio (BIDS)

▪ AdventureWorksDW2008R2 database. Click here to install this database from codeplex.

▪ Familier with SSRS

Below are the stpes to create Recursive Hierarchy Group:

STEP 1: To begin, create new report in your existing solution. Add new Shared Data Source. If you don't know how to create a shared data source, click Creating Shared Data Source in SSRS 2008.

 

STEP 2: Create a new dataset for the report. Just right click on the data source and click Add Dataset... to create new data set as shown below:

[pic]

In Dataset Properties window, enter dsMain in Name textbox and below T-SQL code in Query textbox:

SELECT [EmployeeKey],[ParentEmployeeKey

,[FirstName] + ' ' + ISNULL([MiddleName],'') + ' ' + [LastName] EmployeeName],[Title]

FROM [AdventureWorksDW2008R2].[dbo].[DimEmployee] 

 

Finally click OK to close the window and save changes. The Report Data will look like below image:

[pic]

STEP 3: Drag and drop Table control and map with dsMain dataset. Select EmployeeName in first column,Title in second column and =Level() expression in the third column. Set following properties for table control:

▪ Header Background color = DarkBlue

▪ Header Color = White

▪ Font = Verdana, 8pt

[pic]

STEP 4:  Set Group Properties to reference Recursive Parent. Select table control --> click View and checkGrouping as shown below:

[pic]

Open Row Group properties, click on add button and select [EmployeeKey] in Group on box.

 

[pic]

Click on Advance tab of Group Properties window and select [ParentEmployeeKey] in Recursive parentbox. Click OK and save changes.

 

STEP 5: We are done with report development. Click on Preview to generate the report. You can see a report like one shown below:

[pic]

Here, you can see the Employee Hierarchy but not as per standard. We need to format the text to make it better report. Do below formating for EmployeeName textbox:

1) Enter below expression in FontWeight under Font Property:

=IIF(Count(Fields!EmployeeName.Value, "Details", Recursive) > 1, "Bold", "Normal")

2)  Enter below expression in LeftIndent under Indent Property:

=CStr(2 + (Level()*20)) + "pt"

Again Preview the report, report will look like below image:

[pic]

Cheers!!!

• [pic]

Pulling SharePoint List using SSIS 2008

Posted: Mon, 23 Aug 2010 23:18:00 +0000

Do you want to pull SharePoint List data into SQL database using SSIS? If your answer is Yes then you can go for SharePoint List Source. You can download the setup from Microsoft SQL Server Community Sample: Integration Services: here is the link: SharePointListAdaptersSetup

This component has two controls - SharePoint List Source and SharePoint List Destination. The Specific Features of the included SSIS Components are:

SharePoint Source Component

▪ Auto-detects all of the public fields from a SharePoint List or view of the list.

▪ Supports removal of fields from the output flow, which optimizes the query against SharePoint for increased performance.

▪ Supports restricting SharePoint data by a custom CAML query, which can be provided through a variable expression for fine tuned filtering over large lists.

▪ Provides a tuning feature for the # of rows to return at a time. Often with SharePoint, large lists need to be brought over in smaller batches than wide (many field) lists, or else the Webservice will die.

SharePoint Destination Component

▪ Auto-detects all of the editable fields from a SharePoint List

▪ Only fields bound to columns from the input flow will be ‘updated’, for performance.

▪ Supports deleting rows by ID

System Requirements

▪ .Net 3.5 Framework

▪ SQL Server Integration Services 2008

 How to Use

▪ Download the sample from SharePointListAdaptersSetup

▪ Run SharePointListAdaptersSetup.msi to install the SSIS component. This installer places pre-built binaries into the Global Assembly Cache (GAC) and into the C:\Program Files\Microsoft SQL Server\100\DTS\PipelineComponents directory (if present).

▪ A good way to explore the sample is to try using it, understand its behavior, and then begin reviewing the source code for the component. If you do not see the SharePoint adapters in your toolbox automatically, then follow these instructions:

▪ Open Business Intelligence Development Studio, open a package, and then click Choose Toolbox Items on the Tools menu.

▪ In the Choose Toolbox Items dialog box, click the SSIS Data Flow Items tab, and then checkSharePoint Destination and SharePoint Source.

▪ Click Ok.

▪ The SharePoint source and destination components should now appear in the toolbox for the data flow task. You can add the source and destination components to the data flow of the package.

[pic]

[pic]

Dynamic SSIS Package to Import Excel files into SQL Server Database

Posted: Thu, 12 Aug 2010 07:38:00 +0000

Problem/Scenario

Need to import Excel files to a SQL table. Everyday one file is created at specified location in the source system. We need to copy that file from Source System to Local system and then load to SQL Table.

Conditions:

1.  Each file should be loaded only once. Everynight Job should be executed to load data into reporting Data mart.

2.  Source system will maintain all the history files so files at souce should not be deleted.

3.  If Job failed due to some reason (schema changes, server down, connection issues etc.), it should load all the files from last run date to current date in next successul run. For example, job didn't run last one week then whenever job runs next time successfully, it should load current file as well as all the files of last week which were missing.

4.  All the source files will have the same structure (Schema)

5.  Nomenclature - Each file will have name Transaction followed by current date in YYYY-MM-DD format. For example, if a file was created on 01-Aug-2010 then its name should be Transaction2010-08-01.

Solution

I will take advantage of the ForEach Loop Container. I'll create a new SSIS package to solve the above problem.

STEP 1:

Create following tables in your local database (destination database).

CREATE TABLE [TransactionHistory](

   [TransactionID] [int] NOT NULL,

   [ProductID] [int] NOT NULL,

   [ReferenceOrderID] [int] NOT NULL,

   [TransactionDate] [datetime] NOT NULL,

   [TransactionType] [nchar](1) NOT NULL,

   [Quantity] [int] NOT NULL,

   [ActualCost] [money] NOT NULL,

   CONSTRAINT [PK_TransactionHistory_TransactionID] 

   PRIMARY KEY CLUSTERED ([TransactionID] ASC)

) ON [PRIMARY]

GO

CREATE TABLE [ExcelFilesLog](

   [FileName] [varchar](100),

   [FileCreatedDate] [datetime],

   [FileLoadDate] [datetime],

   [RecordCount] [int],

) ON [PRIMARY]

GO

STEP 2: Create a new SSIS package and rename it to LoadDynamicExcelFiles.dtsx

STEP 3: Add following package variables:

|VariableName |Description |Examle |

|LastRunDate |To store last run date  |2010-07-30 |

|CurrentDate |To hold running date  |2010-08-10 |

|Directory |To store source  |D:\SSIS\Hari\SourceFiles |

|Source |directory path | |

|Directory |To store local |D:\SSIS\Hari\DestinationFiles |

|Destination |directory path | |

|CurrentFile |To store current |D:\SSIS\Hari\SourceFiles\ |

|Name |file name |Transaction2010-08-01 |

Create one OLE DB connection (I will use (local).TestHN connection manager) for local database where you want to load excel files data. Create one Excel Connection Manager for excel files located in D:\SSIS\Hari\DestinationFiles. At least one file should be there to create excel connection manager.

[pic]

Click on Excel Connection Manager --> go to Properties window --> Select Expression and set ExcelFilePathwith package variable User::CurrentFileName as shown below:

[pic]

For this article, I'll use two directories - one for sources files and one for destination files. Location of these files are given below:

Source Files: D:\SSIS\Hari\SourceFiles

Destination Files: D:\SSIS\Hari\DestinationFiles

I have created few excel files from Production.TransactionHistory table of AdventureWorks2008R2database as shown below:

[pic]

I have created files from 2010-07-20 to 2010-08-01. After executing the package first time, I will create files from 2010-08-02 to 2010-08-09 to test the package.

STEP 4:

Drag and drop File System Task and double click to open File System Task Editor. Enter FST - Delete destination directory content in name and  select Delete directory content as Operation. Set IsSourcePathVariable to True and select SourceVariable as User::DirectoryDestination. Finally click on OK and save changes.

[pic]

Drag and drop Execute SQL Task and double click to open Execute SQL Task Editor. Enter Execute SQL Task - Get LastRunDate in Name, select Single row as Result Set, Conection Type as OLE DB and Connection as (local).TestHN and SQLSourceType as Direct input. Enter below query in SQLStatement:

SELECT ISNULL(MAX([FileCreatedDate]),'2010-01-01') AS LastRunDate

FROM [dbo].[ExcelFilesLog] (NOLOCK)

In Result Set tab, set Result Name 0 to variable User::LastRunDate.

Finally click OK and save changes.

[pic]

Drag and drop Script Task and double click to open Script Task Editor. Select User::DirectoryDestination, User::DirectorySource, User::LastRunDate in ReadOnlyVariables. Click on Edit Script... and paste below code:





using System.IO; 

public void Main()

{

   try

   {

      string DirectorySource = Dts.Variables["User::DirectorySource"].Value.ToString();

      string DirectoryDestination = Dts.Variables["User::DirectoryDestination"].Value.ToString();

      DateTime LastRunDate = (DateTime)Dts.Variables["User::LastRunDate"].Value;

      string fileName,fileExtension;

      string[] files = Directory.GetFiles(DirectorySource);

      //Copy source files to destination

      foreach (string f in files)

      {

         fileName = Path.GetFileName(f);

         fileExtension = Path.GetExtension(f);

         DateTime CurrentDate = DateTime.Parse(fileName.Substring("Transaction".Length, 10));

         if ((pare(CurrentDate,LastRunDate)>0) && (fileExtension == ".xlsx"))

        {

            //MessageBox.Show(fileName.ToString());

            File.Copy(f, bine(DirectoryDestination, fileName), true);

         } 

      }

      Dts.TaskResult = (int)ScriptResults.Success;

   }

   catch (Exception ex)

   {

      Dts.Log(ex.Message, 0, null);

      Dts.TaskResult = (int)ScriptResults.Failure;

   }

}

Drag and drop Foreach Loop container. Select Foreach File Enumerator as Enumerator, enterD:\SSIS\Hari\DestinationFiles in Folder path and *.xlsx in files textbox. Select Fully qualified as Retrieve file name. In Variable Mappings, Select User::CurrentFileName for Index 0 to store current file name for each iteration.

[pic]

Now drag and drop Data Flow Task inside Foreach loop container. Use Excel Source reader to read excel files from destination directory. Use Excel Connection Manager as connection manager for excel files. In connection properties, Select @[User::CurrentFileName] as ExcelFilePath. Use Data Conversion, if required. Use Row Count Task to count number of rows in data flow and store it in User::RecordCountvariable. Use OLE DB Destination to load data into SQL table.

[pic]

Drag and drop Execute SQL Task inside Foreach loop container to log information about current file.

Double click on Execute SQL Task to open Execute SQL Task Editor, enter Execute SQL Task - Insert info into Log table as Name, None as Result Set, OLE DB as connection type, (local).TestHN as connection,Direct input as SQLSourceType and below query as SQLStatement.

DECLARE

@FileName varchar(500)

,@FilePath varchar(500)

,@DestinationPath varchar(500)

SET @DestinationPath = ?

SET @FilePath = ?

SET @FileName = REPLACE(@FilePath,@DestinationPath + '\','')

INSERT INTO [ExcelFilesLog]

(

   [FileName]

   ,[FileCreatedDate]

   ,[FileLoadDate]

   ,[RecordCount]

)

SELECT 

@FileName [FileName]

,CAST(SUBSTRING(@FileName,12,10) as datetime) [FileCreatedDate]

,GETDATE() [FileLoadDate]

,?

In Parameter mapping,  map User::DirectoryDestination, User::CurrentFileName, and User::RecordCount with parameter 0,1,2 respectively as shown below.

[pic]

Finally click OK and save changes.

Below is the final layout of our package: 

[pic]

STEP 6:

We are done with the package development. To execute the package, go to SSIS package location, (in this example, it is D:\SSIS\Hari\Sample\SSIS-Sample1), right click on LoadDynamicExcelFiles.dtsx --> Open with --> SQL Server 2008 Integration Services Package Execution Utility. This will open Execute Package Utility. Click on Execute button to run ssis package. Now you can see the progress of package execution in Package Execution Progress window.

[pic]

Now you can check ExcelFileLog table to cross check the result of package.

[pic]

Now I'll add few more excel files in source location - from

Transaction2010-08-02 to Transaction2010-08-09 as shown below:

[pic]

When I execute this package next time, it will load only new files. Yon can check ExcelFileLog for each iteration:

[pic]

[pic]

[pic]

Cascading Parameters in SSRS 2008

Posted: Sat, 07 Aug 2010 07:35:00 +0000

Cascading parameters provide a way of managing large amounts of report data. You can define a set of related parameters so that the list of values for one parameter depends on the value chosen in another parameter. For example, the first parameter is independent and might present a list of product categories. When the user selects a category, the second parameter is dependent on the value of the first parameter. Its values are updated with a list of subcategories within the chosen category. When the user views the report, the values for both the category and subcategory parameters are used to filter report data. 

In this post we will walk through the steps of building a report and with query parameters for both product category and subcategory items. Then we will develop individual datasets to provide values for the cascading parameters.

I will use AdventureWorks2008R2 database for this article. You can install this database from codeplex.

STEP 1:

Open your existing Report Server project or create a new Report Server project. Add a new report and rename it as CascadingParameters.rdl. Now create a Data Source for AdventureWorksDW2008R2 database. For more information about creating shared Data Source, Click Creating Shared Data Source in SSRS 2008.

STEP 2:

Create three data sets as mentioned below:

1. dsProductCategory: This Data Set will be used to create a parameter for Product Categories. Use below query for this data set:

SELECT ProductCategoryID,Name AS ProductCategory

FROM Production.ProductCategory (NOLOCK)

ORDER BY Name

[pic]

 2. dsProductSubcategory: This Data Set will be used to create a Cascading Parameter for Product Subcategories. Use below stored procedure for this data set.

CREATE PROC procProductSubcategory

(

   @ProductCategoryID varchar(1000)

)

AS

BEGIN

   SELECT ProductSubcategoryID,Name AS ProductSubcategory

   FROM Production.ProductSubcategory (NOLOCK)

   WHERE ProductCategoryID IN (SELECT Value 

   FROM [dbo].[SplitMultivaluedString](@ProductCategoryID,','))

   ORDER BY Name

END

-------- UNIT TESTING ------------------

-- EXEC procProductSubcategory '1'

-- EXEC procProductSubcategory '1,2'

-- EXEC procProductSubcategory '1,3'

----------------------------------------

GO

Note: Function SplitMultivaluedString is used to split comma seperated values of parameter @ProductCategoryID. Click Function to Split Multi-valued Parameters to get T-SQL script of this function.

Result of EXEC procProductSubcategory '1,3' is shown below:

[pic]

3. dsProduct: This data set will give the list of all the products based on the Product SubCategories selected at run time. Use below stored procedure for this data set:

CREATE PROC procProductsList

(

   @ProductSubcategoryID varchar(1000)

)

AS

BEGIN

   SET NOCOUNT ON

   SELECT

      PC.Name ProductCategory

      ,PS.Name ProductSubcategory

      ,P.Name ProductName,ProductNumber

      ,Color,Size,[Weight]

   FROM Production.Product P (NOLOCK)

   INNER JOIN Production.ProductSubcategory PS

     ON PS.ProductSubcategoryID = P.ProductSubcategoryID 

   INNER JOIN Production.ProductCategory PC

      ON PC.ProductCategoryID = PS.ProductCategoryID 

   WHERE P.ProductSubcategoryID IN (SELECT Value 

    FROM [dbo].[SplitMultivaluedString](@ProductSubcategoryID,','))

END

-- EXEC procProductsList '6,7,8,18,30,36'

GO

Result of EXEC procProductsList '6,7,8,18,30,36' is shown below:

[pic]

STEP 3:

Once you create above data sets, you can see two parameters created automatically - ProductCategoryIDand ProductSubcategoryID as shown below:

• [pic]

Now double click on parameter ProductCategoryID to open Report Parameter Properties window. InGeneral, change the Prompt value as Product Category and check Allow multiple values checkbox. InAvailable Values, Select Get values from a query option and select dsProductCategory in Dataset,ProductCategoryID in Value field and ProductCategory in Label field. Now click on Default Values, Click on Get values from a query option and select dsProductCategory in Dataset, ProductCategoryID in Value field. Finally click OK to save changes.

Similarily change the properties of parameter ProductSubcategoryID. In General, change the Prompt value as Product Subcategory and check Allow multiple values checkbox. In Available Values, Select Get values from a query option and select dsProductSubcategory in Dataset, ProductSubcategoryID inValue field and ProductSubcategory in Label field. In Default Values, Click on Get values from a queryoption and select dsProductSubcategory in Dataset, ProductSubcategoryID in Value field.

Finally click OK to save changes.

STEP 4:

In report Design, drag and drop a table control and map with dsProduct data set. select all the columns from dsProduct in the tables and format this as shown below:

[pic]

Thats all. We are done with a report having one cascading parameter. Click on Preview to view the report. Now you can see that values of Parameter Product Subcategory depends on the parameter Product Category. By Default, Product Category parameter has (Selected All) so Product Subcategory will also display all the values.

[pic]

Values of Product Subcategory parameter will be filtered as per selection of the values of Product Category parameter, which will filter the actual report data because Product Subcategory parameter is used to filter report data.

[pic]

[pic]

[pic]

Function to convert a string in Camel Case (Proper Case)

Posted: Wed, 04 Aug 2010 22:08:00 +0000

Sometime, we need to display string data in proper case, i.e. first character of each word should be in UPPER case. SQL Server doesn't provide any built-in function for this requirement. In this article, I am putting T-SQL code to create this function. This is a generalised Function that will return any input string in Proper Case [Camel Case]. Means Afetr every space, first later will be in UPPER case.

Example:

Input String    :  'microSoft sql server'

Output String : 'Microsoft Sql Server'

  

/************************************************* 

CREATED BY : HARI SHARMA ON MAR 30, 2007

PURPOSE : TO CONVERT INPUT STRING IN CAMEL CASE

**************************************************/

CREATE FUNCTION [dbo].[CamelCase]

(@Str varchar(8000))

RETURNS varchar(8000) AS

BEGIN

  DECLARE @Result varchar(2000)

  SET @Str = LOWER(@Str) + ' '

  SET @Result = ''

  WHILE 1=1

  BEGIN

    IF PATINDEX('% %',@Str) = 0 BREAK

    SET @Result = @Result + UPPER(Left(@Str,1))+

    SubString  (@Str,2,CharIndex(' ',@Str)-1)

    SET @Str = SubString(@Str,

      CharIndex(' ',@Str)+1,Len(@Str))

  END

  SET @Result = Left(@Result,Len(@Result))

  RETURN @Result

END

---------------------------------------------------

-- HOW TO USE --

-- SELECT dbo.CamelCase('hARi nARAyan shARMa')

-- Output: Hari Narayan Sharma

---------------------------------------------------

GO

[pic]

[pic]

Creating First Cube in SSAS 2008

Posted: Sun, 01 Aug 2010 20:34:00 +0000

Nowadays, analytical solutions are becoming mission critical for many organizations. Microsoft SQL Server 2008 Analysis Services (SSAS) is designed to provide exceptional performance and scalable support with millions of records and thousands of users from different locations.

Why to Build a Cube?

There are many advantages of cube over relational data mart.

▪ While querying a data mart, you can get most of the results but not everything you need for business analysis and decsion making. Cube can help you to get answers of all "What-If" scenarios.

▪ Building a cube helps to house your data to centralize the business rules for calculations that you can't easily store in a relational data mart.

▪ The structure of the cube makes it much easier to write queries to compare data year over year (YOY), or to create cumulative values such as year-to-date (YTD) sales.

▪ Scalable Infrastructure - Analysis Services can scale to support databases of many terabytes in size with many thousands of users.

▪ Superior Performance - Analysis Services cubes are multidimensional structures that enable fast access to high volumes of pre-aggregated data, empowering end users to gain insight into relevant business data at the speed of thought.

▪ You gain the ability to manage aggregated data in the cube. To improve query performance in a relational data mart, we often create summary tables to prepare data for queries that don't require transaction-level detail. SSAS creates the logical equivalent of summary tables (called aggregations) and keeps them up-to-date.

I would like to introduce beginners to Microsoft SQL Server Analysis Services (SSAS) by creating a simple cube from AdventureWorksDW2008R2. You can install this database from codeplex.

I'll cover following things in this article:

▪ Creating Analysis Services Project

▪ Creating Data Source

▪ Creating Data Source View

▪ Creating Cube and Dimensions

▪ Creating Dimension Hierarchies

▪ Deploying Cube Database from BIDS

Creating Analysis Services Project.

First step is to create a project in Business Intelligence Development Studio (BIDS). Launch BIDS from Start --> All Programs --> Microsoft SQL Server 2008 --> SQL Server Business Intelligence Development Studio and then click File --> New --> Project. In the New Project dialog box, select Analysis Services Project. In the Name text box, type LearnSSAS and, if you like, change the location for your project. I'll store this project at locationD:\Hari. Click OK to create the project.

[pic]

 

Creating Data Source

Now add a data source to define the connection string for data mart AdventureWorksDW2008R2. In Solution Explorer, right-click the Data Sources folder and click New Data Source.

[pic]

In the Data Source Wizard, click Next on the Welcome to the Data Source Wizard page if it hasn't been disabled. On the Select how to define the connection page, click New to set up a new connection. In theConnection Manager, the default provider is the Native OLE DB\SQL Server Native Client 10.0, which is correct for our project.

To define the connection, type the name of your server in the Server Name text box. Alternatively you can select it from the drop-down list, then select AdventureWorksDW2008R2 in the database drop-down list and click Test Connection button to check the connection. Finally click on OK as shown below:

 

[pic]

When you're back in the Data Source Wizard, click Next. On the Impersonation Information page, select Use the service account option so that service account will be used to read data from the source when loading data into your SSAS database and service account  must have read permissions to do so. Click Next and thenFinish to complete the wizard.

 

Creating Data Source View

Now next step is to create a data source view (DSV) from the data source to define dimensions and cubes. You can make changes to the DSV without modifying the actual data source, which is very useful if you have only read permissions to the data mart. In Solution Explorer, right-click on the Data Source Views folder and then click New Data Source Views...You can see Data Source View Wizard. Click Next on the Welcome page. On the Select a Data Source page, select the data source just added to the project (Adventure Works DW2008R2.ds) and click Next. Now add required objects to the DSV by double-clicking each table or view onSelect Tables and Views page. I want to add the following tables to the DSV to make it easy to understand for beginners:

DimDate, DimProduct, DimProductCategory, DimProductSubcategory, and FactInternetSales. You can always add more tables later if you want to explore advance BI questions. Now click Next in the Data Source View Wizard once you are finished adding required tables followed by click on Finish. You can give a name to your DSV before clicking Finish button.

I would recommend you to change the name of objects by selecting each one in the DSV designer and remove the Dim and Fact prefixes from the FriendlyName property because when you create dimensions and cubes, only FriendlyName property will be assigned to the objects.

The DSV is shown below:

 [pic]

Creating Cube and Dimensions

Next step is to create a Cube and Dimensions from the data source view. In Solution Explorer, right-click on the Cubes folder and then click New Cube...You can see Cube Wizard. Click on Next in Welcome to the Cube Wizard page.On the Select Creation Method page, keep the default option Use existing tables and click Nextbutton. On the Select Measure Group Tables page, choose InternetSales table and click Next.

[pic]

Now the wizard displays all the measures available in the selected measure group tables. Measures are basically numeric values e.g. OrderQuantity, Unit Price, Sales Amount, Tax Amount etc. Select only the following measures from Internet Sales Group: Order Quantity, Unit Price, Total Product Cost, Sales Amount, and Internet Sales Count

[pic]

Now click on Next button to open Select New Dimensions page and select Date and Product dimensions. ClickNext to proceed.

[pic]

In the Completing the Wizard page, enter the cube name as AdventureWorksCube and click Finish button to complete the wizard. Cube layout is shown below:

[pic]

Now click on each dimensions and add required attributes from the Data Source View.

Date Dimension:

Drag and drop FullDateAlternateKey, CalendarYear, CalendarQuarter, EnglishMonthName, and EnglishDayNameOfWeek. Rename FullDateAlternateKey with Full Date, EnglishMonthName with Calendar Month, and EnglishDayNameOfWeek with Calendar Week as shown below:

[pic]

Product Dimension:

Drag and drop EnglishProductCategoryName from ProductCategory table, EnglishProductSubcategoryName from ProductSubcategory table and Color, ModelName, Size and Weight from Product table.

Creating Dimension Hierarchies

Navigate to Date Dimension Structure. Drag and drop Calendar Year attribute into Hierarchies surface area following by Calendar Quarter, Calendar Month, Calendar Week , and Full Date attributes.

Rename hierarchy with Calendar. You'll see a warning mark in the hierarchy because attribute relationship is not set properly.

[pic]

Set Attribute Relationships

Click on the Attribute Relationships tab in the dimension designer. This tab is available only in Analysis Services 2008. By default, all attributes relate directly to the key attribute, Date Key as shown below:

[pic]

To optimize the design by reassigning relationships, Right Click on Full Date and select New Attribute Relationship. Select Related Attribute as Calendar Week and Relationship type as Rigid (will not change over time). Repeat same thing for remaining attributes. Finally Attribute Relation will look like below image:

[pic]

Deploying Cube Database from BIDS

Now its time to deploy the cube at required server. Right click on the project (LearnSSAS in this example) and click properties to open project properties page. Enter Server Name name Server property and Database name in Database property as shown below:

[pic]

Click OK to save changes. Now right click on the project and click on Process to Build and Deploy the project. You will a message while deploying the database first time.

[pic]

Click on Yes to proceed. Now you can see Process Database - PreojectName window. Click on Run to continue.

[pic]

Once the database is deployed and processed successfully, you can see the data through Browser tab or directly through SQL Server Analysis Services. You can also pull cube data in Excel using Excel OLAP Pivot Tables, which is the prefered option used by business managers.

[pic]

[pic]

Send Mail Task in SSIS 2008

Posted: Mon, 26 Jul 2010 17:38:00 +0000

How to send a notification/mail to specific group of peoples through SSIS packages? Thanks to Send Mail Task. This can be achieved easily using send mail task.

By using the Send Mail task, a package can send messages if tasks in the package workflow succeed or fail, or send messages in response to an event that the package raises at run time. For example, the task can notify a database administrator about the success or failure of the Backup Database task.

You can configure the Send Mail task in the following ways:

▪ Write the message text for the e-mail.

▪ Write a subject line for the e-mail message.

▪ Set the priority level of the message. The task supports three priority levels: normal, low, and high.

▪ Specify the recipients on the To, Cc, and Bcc lines. If the task specifies multiple recipients, they are separated by semicolons.

I'll explain this by an example:

STEP 1:

Create a new SSIS Package and rename it with SendMailTask.dtsx.

STEP 2:

Add two package variable MessageSource and SMTPServer of type string to this package as shown below:

[pic]

STEP 3:

Add a new SMTP Connection manager and configure its properties. Enter SMTP Connection manager in Name andConnection for sending mails inDescription boxes. Now enter your SMTPServerName in SMTP server box as shown below:

[pic]

Set SmtpServer property of above connection manager with variableUser::SMTPServer by clicking on Expression in properties of SMTP Connection Manager. This is highlighted in below snap shot:

[pic]

STEP 4:

Drag and drop Script Task to set your message. Double click on Script Task to open Script Task Editor, Select User::MessageSource as ReadWriteVariables and click on Edit Script... button to set the message. Write below code in main function. (This is for , you can choose C# or )

Public Sub Main()

   'Set MessageSource variable

   Dts.Variables("User::MessageSource").Value = "Hi," & vbCrLf & _

   "This is a test mail to check Send Mail Task in SSIS!" & vbCrLf & vbCrLf & _

   "Thanks and Regards," & vbCrLf & "_____________" & vbCrLf & "Hari"

   Dts.TaskResult = ScriptResults.Success

End Sub

  

However, the message text can be a string that you provide, a connection to a file that contains the text, or the name of a variable (in our case) that contains the text. 

  

STEP 5: 

Drag and drop Send Mail Task and double click on it to open Send Mail Task Editor. Select Mail from Left side and set mail properties as shown below: 

[pic]

  

Thats all. We are done with Send Mail Task setup, this package will look like below snapshot. Just right click on package in Solution Explorer and Execute. Receiver will get an email as soon as package executes successfully. However, mail delivery depends on the response of SMTP Server as well. 

  

[pic]

  

  

  

  

  

  

  

  

  

Note: 

▪ The To, Cc, and Bcc lines are limited to 256 characters.

▪ The SMTP connection manager supports only anonymous authentication and Windows Authentication.

[pic]

[pic]

Find Largest Size Tables in a Database

Posted: Sat, 24 Jul 2010 05:30:00 +0000

Below is the stored procedure to return largest tables of a database.

IF OBJECT_ID('sp_LargestTables' ,'P') IS NOT NULL

DROP PROC sp_LargestTables

GO

/***************************************************************

CREATE BY : Hari Sharma

PURPOSE : To get a list of tables according to their size.

***************************************************************/

CREATE PROC sp_LargestTables

(

   @n int = NULL,

   @IsSystemAllowed bit = 0

)

AS

BEGIN

   SET NOCOUNT ON

   DECLARE @LOW int

   SELECT @LOW = LOW 

   FROM [master].[dbo].[spt_values] (NOLOCK) 

   WHERE [number] = 1 AND [type] = 'E'

   IF @n > 0 SET ROWCOUNT @n

   SELECT TableName,[Row Count],[Size (KB)] FROM 

   (

      SELECT QUOTENAME(USER_NAME(o.uid)) + '.' + 

                     QUOTENAME(OBJECT_NAME(i.id)) 

         AS TableName

         ,SUM(i.rowcnt) [Row Count]

         ,CONVERT(numeric(15,2),

            (((CONVERT(numeric(15,2),SUM(i.reserved)) * @LOW) / 1024.0))) AS [Size (KB)]

      FROM sysindexes i (NOLOCK)

      INNER JOIN sysobjects o (NOLOCK) 

         ON i.id = o.id AND 

         ((@IsSystemAllowed = 1 AND o.type IN ('U', 'S')) OR o.type = 'U') 

      WHERE indid IN (0, 1, 255)

      GROUP BY 

         QUOTENAME(USER_NAME(o.uid)) + '.' + 

         QUOTENAME(OBJECT_NAME(i.id))

   ) AS Z

   ORDER BY [Size (KB)] DESC

   SET ROWCOUNT 0

END

GO

How to use:

1. If you want all the user tables in the database with largest db size then:

EXEC sp_LargestTables [No Need to pass parameters]

2. If you want only 3 tables in the database with largest db size then:

EXEC sp_LargestTables 3

3. If you want only 20 tables in the database with largest db size including system tables then:

EXEC sp_LargestTables 20,1

[pic]

[pic]

Function to Split Multi-valued Parameters

Posted: Wed, 21 Jul 2010 22:00:00 +0000

How to split a comma seperated value?

Many times we need to write T-SQL statements to split a comma seperated value, however string is not necessarily to be comma seperated, it can be seperated by any delimiter e.g. comma (,), @, &, ; etc.

How to use Multi-valued Parameters of SSRS report in a Stored procedures?

One more question comes around, how to use a multi valued parameter of SSRS report in a Stored Procedure to filter report data? I am sure you can't use a multi valued parameter directly in T-SQL code without spliting multiple values, if you do so without spliting values, SPROC will throw an error.

To find the answer of above questions, you create a user defined function using below T-SQL code:

/********************************************** 

CREATED BY HARI 

PURPOSE : To split any multivalued string 

seperated by any delimiter into multiple rows

***********************************************/ 

CREATE FUNCTION [dbo].[SplitMultivaluedString] 



   @DelimittedString [varchar](max), 

   @Delimiter [varchar](1) 



RETURNS @Table Table (Value [varchar](100)) 

BEGIN 

   DECLARE @sTemp [varchar](max) 

   SET @sTemp = ISNULL(@DelimittedString,'') 

                + @Delimiter 

   WHILE LEN(@sTemp) > 0 

   BEGIN 

      INSERT INTO @Table 

      SELECT SubString(@sTemp,1,

             CharIndex(@Delimiter,@sTemp)-1) 

      

      SET @sTemp = RIGHT(@sTemp,

        LEN(@sTemp)-CharIndex(@Delimiter,@sTemp)) 

   END 

   RETURN 

END 

GO 

/* How to use this function:

-----------------------------------------

SELECT * FROM [dbo].[SplitMultivaluedString] ('1,2,3,4', ',') 

SELECT * FROM [dbo].[SplitMultivaluedString] ('1;2;3;4', ';')

SELECT * FROM [dbo].[SplitMultivaluedString] ('Hari#Thomas','#')

*/

[pic]

[pic]

Sequence Container in SSIS - Different ways of using Sequence Containers

Posted: Tue, 20 Jul 2010 00:32:00 +0000

Integration Services includes the Sequence container, which makes it simple to divide the control flow in a package into groups of tasks and containers that you can manage as a unit.

Using Sequence containers lets you handle the control flow in a package in more detail, without having to manage individual tasks and containers.

If a package has many tasks, it can be helpful to group the tasks in Sequence containers.

I'll explain different scenarios where Sequence Container paly an important role to implement business rules.

Scenario 1:

▪ Sequence Task SC1 must execute first. SC1 may have many task with or without precedence constraints. The group of these task must execute prior to any other tasks in the package.

▪ Sequence Task SC2 must start after completion of SC1. SC2 must execute irrespective of Failure/Success of SC1.

▪ Sequence Task SC3 contains Maintenence Plan Tasks and should be followed by SC2. SC3 must execute only after successfully execution of SC2. [pic]

Scenario 2:

▪ Sequence Task SC1 must execute first.

▪ Sequence Task SC2 must start based on logical condition. This condition can be based on package variables. 

▪ Sequence Task SC3 contains Maintenence Plan Tasks and should be followed by both SC1 and SC2. SC3 must execute after successfully execution of SC1. SC3 should execute regardless of SC2 but if SC2 executes, SC3 must execute after SC2.[pic]

  Scenario 3: This is real scenario in many BI applications. 

▪ SC1 must execute prior to other task. This Sequence Container may contain many tasks to pull data from hetrogenious data sources.

▪ SC2 should be followed by SC1. This can be used to Insert/Update dimension tables and fact tables along with intermediate tables (if any). This container may further contain Sub - Sequence Containers e.g. SC2(a) to handle dimension Insert/Update and SC2(b) to update Intermediate and Fact tables.

▪ SC3 should be followed by SC2. This may contains SSAS Tasks to Build/Prcoess Cubes. This container may also have Sub - Sequence Containers e.g. SC3(a) to check whether Current Month partition exists or not. If Yes than Do Nothing Else Create Current Month Partitions using Script task. SC3(b) can be used to Process Dimensions and Current Month Partitions.

▪ SC4 can be used for Maintenence Plan tasks. If SC3 successfully completed (Evolution operation - Expression and Constraint) than take Backup of Cube, Shrink Datamart and Take Backup of Datamart.

▪ SC5 can be used for Recovery Paln. If SC3 fails, Restore Cube from previos & Latest Backup available.. 

[pic]

However, there are many more ways of utilizing Sequence Containers. Further, things depends on complexity of business requirement rules defined.

[pic]

[pic]

Report Parameters in SSRS 2008

Posted: Sun, 18 Jul 2010 07:24:00 +0000

What is Report Parameters in SSRS?

In SSRS, parameters are used to specify the data to use in a report, narrow down your report data for better analysis, connect related reports together, and vary report presentation. Report parameters can be Single-Valued and Multivalued.

Using Parameters in Reporting Services:

The most common use of parameters is to vary report data retrieved by dataset queries. In this scenario, users are prompted for a value or values when they run the report, and the dataset query retrieves only the data that is requested. You can change the report parameter properties in the report design tools to include a valid values list that displays at run time.

You can also create cascading parameters, which retrieve hierarchical data from a data source. I'll explain cascading parameters in my nect post. First I want to explain creating a report parameter in SSRS 2008.

Below are the uses of report parameters:

▪ To Control Report Data - by selecting required parameters values to filter the report data.

▪ To Control Report Appearance - use parameters to change report appearance using expression-based properties, including conditionally hiding report items and conditionally changing text color.

▪ To Connect to Other Reports - use parameters to link to drillthrough reports, subreports, and linked reports.

▪ To Select Specific Data Columns - parameters can be used to select specific columns of a table/matrix at run time.

How to create Report Parameters:

Query parameters are added to a dataset query by way of the query designers or the Dataset Properties dialog box. After you create a query with parameters, Reporting Services automatically links query parameters to report parameters with the same name. Below are the steps to create parameters:

STEP 1:

To begin, start a new Report Server Project project in Visual Studio 2008 by clicking on Start --> All Programs --> SQL Server 2008 --> SQL Server Business Intelligence Development Studio. Then, from the menu, select File --> New --> Project to open New Project wizard. Now select Report Server Project from Visual studio installed templates and specify Name, Location and Solution Name. 

I'll use the solution ctreated in my previous article. I'll use FirstReport.rdl for this example and I'll create a parameter Designation to filter report data for selected designations.

STEP 2:

Create a new Data Set for the report parameter. I will add a dataset dsDesignation for Employee's Designation using query 

SELECT DISTINCT Desg AS Designation FROM Employee 

as shown below:

[pic]

STEP 3:

Now I will add a parameter Designation. In Report Data section, right click on Parameters node and clickAdd Parameter... as shown below:

[pic]

STEP 4:

In Report Parameter Properties window, enter Name and Prompt of the parameter and select the Data type from dropdown box. For our example, enter Designation in Name and Prompt text boxes and selectText as data type.

[pic]

STEP 4: 

Now click on Avaliable Values to set available values for the parameter. Select Get values from a query. Select dsDesignation as Dataset, Designation as Value field and Label field.

[pic]

STEP 5: Click on Default Values, SelectGet values from a query. Select dsDesignation as Dataset, Designation as Value field. Click OK to save changes.

[pic]

STEP 6:

Double click on your main dataset (dsMain) to open Dataset Properties. Now Select  Parameters and click on Add button to map Designation parameter. 

STEP 7:

Now final step, just add parameter in your query as shown in below snapshot:

WHERE [Desg] = @Designation

[pic]

Now preview the report to check the action of parameter used:

[pic]

Note: This article describes onlu about single valued parameter. I'll explain multi-valued parameter in my next article.

[pic]

[pic]

First Report in SSRS 2008

Posted: Tue, 13 Jul 2010 18:52:00 +0000

In this article, I will explain how to create a simple report (that could be first report for a newbie) using SSRS 2008. Here I am assuming that you have successfully installed SQL Server 2008 along with SSRS.

There are two ways to create Reports in SSRS. You can develop the report manually, or you can use the Report Wizard to give yourself a head start. For this first report, I am going to take advantage of the wizard.

STEP 1:

To begin, start a new Business Intelligence project in Visual Studio 2008 by clicking on Start --> All Programs --> SQL Server 2008 --> SQL Server Business Intelligence Development Studio. Then, from the menu, selectFile --> New --> Project to open New Project wizard. Now select Report Server Project from Visual studio installed templates and specify Name, Location and Solution Name. I am specifying theseReportProjectSSRS, D:\Hari, and ReportProjectSSRS respectively as shown below:

[pic]

STEP 2:

In Solution Explorer, right click on Reports folder and select Add New Report. [pic]This will open Report Wizard. Click Next on the Welcome screen and this will bring you to the Select the Data Source screen.

STEP 3:

Enter the name of Data Source as dsLocal and select type as Microsoft SQL Server. Now click on Edit button to set the connecting string for data source, this will open Connection Properties window. Enter Server name and database name and click onTest Connection buttion to make sure the connection is established. Click OK button twice to close Test Results and Conection Properties windows.

[pic]

You can check the Make this a shared data sourcecheckbox to make this data source as shared so that it can be used for other reports as well. Now click onNext to proceed.

[pic]

STEP 4:

This will open Design the Query wizard. Here you can define your Query string. Alternatively you can use Query Builder... to build your query. I will use below query to pull data from Employee table:

SELECT

   [Emp_code],[Emp_Name],[Desg],

   [Head],[DOB],[Basic],[Dept_Code] 

FROM Employee (NOLOCK)

  

Click Next to proceed. It will display Select the Report Type wizard. Select Tabular option and click Next to proceed. 

  

STEP 5: 

Now you can see Design the Table wizard. Select required fields from Available fields and clicked on details button to make these fields available in details part of a report. You can do data grouping as well usingGroup button. Click Next to proceed.

[pic]

STEP 6:

Now you can see Choose the Table Style wizard. Select default style Slate and click Next. Finally you can see Completing the Wizard. Enter report name FirstReport and click Finish to complete the wizard.

[pic]

Thats all. We are done with our First report in SSRS 2008. Report at design time will look like one shown below:

[pic]

Click on Preview to generate the report:

[pic]

[pic]

[pic]

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download